swarm-controller: move the secrets concern into its own module
Refs #6897
This commit is contained in:
parent
7c7c94d184
commit
6d0c0dc391
15 changed files with 35 additions and 25 deletions
291
swarm-controller/src/secrets/agent_cutoff.rs
Normal file
291
swarm-controller/src/secrets/agent_cutoff.rs
Normal file
|
|
@ -0,0 +1,291 @@
|
|||
//! Cutting a destroyed agent's identity off at the store.
|
||||
//!
|
||||
//! Destroying an agent stops its renewal and nothing else: its client
|
||||
//! certificate stays valid for days, and the cert-auth role it logs in under
|
||||
//! stays in the store. [`cut_off`] ends both. It disables the agent's identity
|
||||
//! entity, which the store enforces at once — tokens already issued stop
|
||||
//! working and a new login is refused — and then deletes the role, so the
|
||||
//! certificate cannot start a login.
|
||||
//!
|
||||
//! The renewal pass ([`crate::agent_renewal`]) calls [`cut_off_destroyed`] on
|
||||
//! every agent that still has a role and is declared `Destroyed` on some hive
|
||||
//! and live on none ([`cut_off_targets`]). The role is the marker that work is
|
||||
//! left, so the entity is disabled before the role is deleted: a failure
|
||||
//! between the two leaves the role, and the next pass runs both again. An
|
||||
//! agent declared nowhere is not cut off, since an unreadable or emptied
|
||||
//! declaration would otherwise read as every agent destroyed.
|
||||
//!
|
||||
//! A new agent with the same name is brought back by [`restore`], which the
|
||||
//! mint runs ([`crate::agent_identity::mint_and_verify`]) before it writes the
|
||||
//! role. The entity keeps its name and alias throughout, so the shared policy
|
||||
//! reads the same entity afterwards.
|
||||
//!
|
||||
//! The grants are the `identity/entity/name/+` and `auth/cert/certs/hive-*`
|
||||
//! stanzas of `swarm-bao.nix`'s `controllerPolicyText`.
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
use swarm_secret_client::{client::DEFAULT_CERT_MOUNT, policy};
|
||||
use swarm_wire::wanted::{AgentState, HiveWanted};
|
||||
|
||||
use crate::store::AccessStore;
|
||||
|
||||
/// Agents that are declared `Destroyed` on at least one hive and live on none.
|
||||
fn destroyed_agents(declarations: &[HiveWanted]) -> BTreeSet<String> {
|
||||
let live = crate::agent_renewal::live_agents(declarations);
|
||||
declarations
|
||||
.iter()
|
||||
.flat_map(|d| &d.agents)
|
||||
.filter(|(agent, wanted)| wanted.state == AgentState::Destroyed && !live.contains(*agent))
|
||||
.map(|(agent, _)| agent.clone())
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The agents of `with_role`, those that have a cert-auth role, that are
|
||||
/// destroyed in `declarations`.
|
||||
pub fn cut_off_targets(
|
||||
with_role: &BTreeSet<String>,
|
||||
declarations: &[HiveWanted],
|
||||
) -> BTreeSet<String> {
|
||||
destroyed_agents(declarations)
|
||||
.intersection(with_role)
|
||||
.cloned()
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Disable `agent`'s identity entity, then delete its cert-auth role.
|
||||
///
|
||||
/// A missing entity is not an error: an agent that never logged in has none,
|
||||
/// and disabling would make one. Safe to repeat.
|
||||
///
|
||||
/// # Errors
|
||||
/// When a store call fails. The entity is disabled before the role is deleted,
|
||||
/// so a failed role delete leaves the entity disabled and the role in place.
|
||||
pub async fn cut_off(store: &impl AccessStore, agent: &str) -> Result<()> {
|
||||
let role = policy::agent_object_name(agent)?;
|
||||
let entity = store
|
||||
.entity_id_by_name(agent)
|
||||
.await
|
||||
.with_context(|| format!("looking up the entity named {agent}"))?;
|
||||
if entity.is_some() {
|
||||
store
|
||||
.set_entity_disabled(agent, true)
|
||||
.await
|
||||
.with_context(|| format!("disabling the entity {agent}"))?;
|
||||
}
|
||||
store
|
||||
.delete_cert_role(DEFAULT_CERT_MOUNT, &role)
|
||||
.await
|
||||
.with_context(|| format!("deleting the cert-auth role {role}"))?;
|
||||
tracing::info!(
|
||||
agent,
|
||||
entity_disabled = entity.is_some(),
|
||||
%role,
|
||||
"destroyed agent cut off from the store: identity entity disabled, cert-auth role deleted"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Undo [`cut_off`]'s disable for `agent`, whose entity exists.
|
||||
///
|
||||
/// Called for every mint, a live agent's renewal included, where it rewrites a
|
||||
/// flag that is already clear.
|
||||
///
|
||||
/// # Errors
|
||||
/// When the store refuses the write.
|
||||
pub async fn restore(store: &impl AccessStore, agent: &str) -> Result<()> {
|
||||
store
|
||||
.set_entity_disabled(agent, false)
|
||||
.await
|
||||
.with_context(|| format!("enabling the entity {agent}"))
|
||||
}
|
||||
|
||||
/// [`cut_off`] every agent of `with_role` that `declarations` leave destroyed
|
||||
/// ([`cut_off_targets`]), logging the ones that fail; the next pass retries
|
||||
/// them, since their role is still there.
|
||||
pub async fn cut_off_destroyed(
|
||||
store: &impl AccessStore,
|
||||
with_role: &BTreeSet<String>,
|
||||
declarations: &[HiveWanted],
|
||||
) {
|
||||
for agent in cut_off_targets(with_role, declarations) {
|
||||
if let Err(e) = cut_off(store, &agent).await {
|
||||
tracing::warn!(
|
||||
agent,
|
||||
error = %format!("{e:#}"),
|
||||
"cutting this destroyed agent off from the store failed; its certificate still logs in until the next pass succeeds"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::store::fake::{FakeAccess, FakeRole};
|
||||
use std::collections::BTreeMap;
|
||||
use swarm_secret_client::client::{CERT_ROLE_TOKEN_TTL_SECS, CertRoleTokenTtls};
|
||||
use swarm_wire::wanted::AgentWanted;
|
||||
|
||||
fn declared(agents: &[(&str, AgentState)]) -> HiveWanted {
|
||||
HiveWanted {
|
||||
agents: agents
|
||||
.iter()
|
||||
.map(|(name, state)| ((*name).to_owned(), AgentWanted { state: *state }))
|
||||
.collect::<BTreeMap<_, _>>(),
|
||||
}
|
||||
}
|
||||
|
||||
fn role() -> FakeRole {
|
||||
FakeRole {
|
||||
certificate: "CA".to_owned(),
|
||||
common_name: "hive-agent-x".to_owned(),
|
||||
policies: vec!["hive-agent".to_owned()],
|
||||
ttls: CertRoleTokenTtls {
|
||||
token_ttl: CERT_ROLE_TOKEN_TTL_SECS,
|
||||
token_max_ttl: CERT_ROLE_TOKEN_TTL_SECS,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
fn with_roles(names: &[&str]) -> BTreeSet<String> {
|
||||
names.iter().map(|n| (*n).to_owned()).collect()
|
||||
}
|
||||
|
||||
/// A store that holds `agents`' roles and entities.
|
||||
fn store_with(agents: &[&str]) -> FakeAccess {
|
||||
agents.iter().fold(FakeAccess::default(), |store, a| {
|
||||
store
|
||||
.with_role(&format!("hive-agent-{a}"), role())
|
||||
.with_entity(a)
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_an_agent_destroyed_everywhere_and_holding_a_role_is_a_target() {
|
||||
let declarations = [
|
||||
declared(&[
|
||||
("gone", AgentState::Destroyed),
|
||||
("moved", AgentState::Destroyed),
|
||||
("alive", AgentState::Up),
|
||||
("asleep", AgentState::Offline),
|
||||
("held", AgentState::Paused),
|
||||
("no-role", AgentState::Destroyed),
|
||||
]),
|
||||
declared(&[("moved", AgentState::Up)]),
|
||||
];
|
||||
let roles = with_roles(&[
|
||||
"gone",
|
||||
"moved",
|
||||
"alive",
|
||||
"asleep",
|
||||
"held",
|
||||
"undeclared",
|
||||
"unnamed",
|
||||
]);
|
||||
assert_eq!(
|
||||
cut_off_targets(&roles, &declarations),
|
||||
with_roles(&["gone"]),
|
||||
"destroyed on one hive and live on another is live; declared nowhere is left alone"
|
||||
);
|
||||
// The control: without the live declaration on `b`, `moved` is a target
|
||||
// too, so the line above can see a destroyed agent.
|
||||
assert_eq!(
|
||||
cut_off_targets(&roles, &declarations[..1]),
|
||||
with_roles(&["gone", "moved"])
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_destroyed_agent_loses_its_entity_and_its_role() {
|
||||
let store = store_with(&["gone"]);
|
||||
let declarations = [declared(&[("gone", AgentState::Destroyed)])];
|
||||
cut_off_destroyed(&store, &with_roles(&["gone"]), &declarations).await;
|
||||
assert!(store.is_disabled("gone"), "{:?}", store.calls());
|
||||
assert_eq!(store.role("hive-agent-gone"), None, "{:?}", store.calls());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_live_agent_is_never_touched() {
|
||||
let store = store_with(&["alive", "gone"]);
|
||||
let declarations = [declared(&[
|
||||
("alive", AgentState::Up),
|
||||
("gone", AgentState::Destroyed),
|
||||
])];
|
||||
cut_off_destroyed(&store, &with_roles(&["alive", "gone"]), &declarations).await;
|
||||
assert!(!store.is_disabled("alive"), "{:?}", store.calls());
|
||||
assert_eq!(store.role("hive-agent-alive"), Some(role()));
|
||||
// The control: the same pass did cut the destroyed one off.
|
||||
assert!(store.is_disabled("gone"));
|
||||
assert_eq!(store.role("hive-agent-gone"), None);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn an_agent_without_an_entity_has_its_role_deleted_and_no_entity_made() {
|
||||
let store = FakeAccess::default().with_role("hive-agent-gone", role());
|
||||
cut_off(&store, "gone").await.expect("accepted");
|
||||
assert_eq!(store.role("hive-agent-gone"), None);
|
||||
assert!(
|
||||
!store
|
||||
.calls()
|
||||
.iter()
|
||||
.any(|c| c.starts_with("set_entity_disabled")),
|
||||
"{:?}",
|
||||
store.calls()
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_failed_disable_keeps_the_role_so_the_next_pass_retries() {
|
||||
let declarations = [declared(&[("gone", AgentState::Destroyed)])];
|
||||
let refused = store_with(&["gone"]).refusing_disable();
|
||||
cut_off_destroyed(&refused, &with_roles(&["gone"]), &declarations).await;
|
||||
assert_eq!(
|
||||
refused.role("hive-agent-gone"),
|
||||
Some(role()),
|
||||
"the role is the marker that work is left"
|
||||
);
|
||||
assert!(
|
||||
!refused
|
||||
.calls()
|
||||
.iter()
|
||||
.any(|c| c.starts_with("delete_cert_role")),
|
||||
"{:?}",
|
||||
refused.calls()
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_failed_role_delete_leaves_the_entity_disabled_and_the_next_pass_finishes() {
|
||||
let declarations = [declared(&[("gone", AgentState::Destroyed)])];
|
||||
let refused = store_with(&["gone"]).refusing_role_delete();
|
||||
cut_off_destroyed(&refused, &with_roles(&["gone"]), &declarations).await;
|
||||
assert!(refused.is_disabled("gone"));
|
||||
assert_eq!(refused.role("hive-agent-gone"), Some(role()));
|
||||
|
||||
// The next pass, against a store that now accepts the delete.
|
||||
let healthy = store_with(&["gone"]);
|
||||
cut_off_destroyed(&healthy, &with_roles(&["gone"]), &declarations).await;
|
||||
assert!(healthy.is_disabled("gone"));
|
||||
assert_eq!(healthy.role("hive-agent-gone"), None);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_cut_off_is_repeatable() {
|
||||
let store = store_with(&["gone"]);
|
||||
cut_off(&store, "gone").await.expect("first");
|
||||
cut_off(&store, "gone").await.expect("second");
|
||||
assert!(store.is_disabled("gone"));
|
||||
assert_eq!(store.role("hive-agent-gone"), None);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn restore_clears_what_a_cut_off_set() {
|
||||
let store = store_with(&["gone"]);
|
||||
cut_off(&store, "gone").await.expect("accepted");
|
||||
assert!(store.is_disabled("gone"));
|
||||
restore(&store, "gone").await.expect("accepted");
|
||||
assert!(!store.is_disabled("gone"));
|
||||
}
|
||||
}
|
||||
319
swarm-controller/src/secrets/agent_entity.rs
Normal file
319
swarm-controller/src/secrets/agent_entity.rs
Normal file
|
|
@ -0,0 +1,319 @@
|
|||
//! The identity entity an agent's login lands on, named after the agent.
|
||||
//!
|
||||
//! A cert login creates an entity with a generated name and an alias named for
|
||||
//! the certificate's common name, `hive-agent-<agent>`. The shared policy
|
||||
//! ([`policy::render_shared_agent`]) reads `{{identity.entity.name}}`, so the
|
||||
//! entity has to be called `<agent>`. This module makes it so, either by
|
||||
//! creating the entity and its alias before the first login or by renaming the
|
||||
//! entity a login already created. The alias is unique per auth mount and
|
||||
//! name, so there is never a second entity to pick between.
|
||||
//!
|
||||
//! An entity's name is its access under the shared policy, so only an entity
|
||||
//! the store named itself is ever renamed ([`is_generated_name`]) and no alias
|
||||
//! is ever moved. Any other arrangement is a [`Plan::Conflict`]: nothing is
|
||||
//! written and an operator decides.
|
||||
//!
|
||||
//! An agent whose entity is not named after it reads nothing under the shared
|
||||
//! policy, so what a failure costs depends on the caller. [`ensure_agent`],
|
||||
//! which runs before a cert-auth role is narrowed to that policy, returns the
|
||||
//! error and leaves the role as it was. [`ensure_agents`], the pass at every
|
||||
//! start, writes no role and so narrows nothing: it logs at `warn` and goes on.
|
||||
//! The grants are the `identity/` stanzas of `swarm-bao.nix`'s
|
||||
//! `controllerPolicyText`.
|
||||
|
||||
use anyhow::{Context, Result, bail};
|
||||
use swarm_secret_client::{
|
||||
client::{DEFAULT_CERT_MOUNT, EntityRef},
|
||||
policy,
|
||||
};
|
||||
|
||||
use crate::store::AccessStore;
|
||||
|
||||
/// What the store holds for one agent's entity.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Seen {
|
||||
/// The entity that owns the agent's alias on the cert mount.
|
||||
pub by_alias: Option<EntityRef>,
|
||||
/// The id of the entity named after the agent.
|
||||
pub by_name: Option<String>,
|
||||
}
|
||||
|
||||
/// What to do about it.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum Plan {
|
||||
/// The alias's entity is already named after the agent.
|
||||
Keep,
|
||||
/// A login created the entity under a generated name.
|
||||
Rename { id: String },
|
||||
/// An entity named after the agent exists, and the alias is on no entity.
|
||||
AddAlias { entity_id: String },
|
||||
/// Neither the entity nor the alias exists.
|
||||
CreateAndAlias,
|
||||
/// The alias sits on an entity that is not the agent's: one with a name of
|
||||
/// someone's choosing, or one while another entity already has the
|
||||
/// agent's name. Nothing is written.
|
||||
Conflict { alias: String, entity_name: String },
|
||||
}
|
||||
|
||||
/// Whether `name` is one the store gave an entity at login: `entity_`, eight
|
||||
/// lowercase hex digits, and the root namespace's `.root` suffix, which stores
|
||||
/// that predate namespaces leave off.
|
||||
///
|
||||
/// Exact on purpose. A name that is merely close, such as `entity_` followed
|
||||
/// by a word, is somebody's choice of name.
|
||||
#[must_use]
|
||||
pub fn is_generated_name(name: &str) -> bool {
|
||||
let Some(rest) = name.strip_prefix("entity_") else {
|
||||
return false;
|
||||
};
|
||||
let digits = rest.strip_suffix(".root").unwrap_or(rest);
|
||||
digits.len() == 8
|
||||
&& digits
|
||||
.bytes()
|
||||
.all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
|
||||
}
|
||||
|
||||
/// The plan that leaves the alias on an entity named `agent`.
|
||||
#[must_use]
|
||||
pub fn plan(agent: &str, seen: &Seen) -> Plan {
|
||||
match (&seen.by_alias, &seen.by_name) {
|
||||
(Some(entity), _) if entity.name == agent => Plan::Keep,
|
||||
(Some(entity), None) if is_generated_name(&entity.name) => Plan::Rename {
|
||||
id: entity.id.clone(),
|
||||
},
|
||||
(Some(entity), _) => Plan::Conflict {
|
||||
alias: format!("{}{agent}", policy::AGENT_PREFIX),
|
||||
entity_name: entity.name.clone(),
|
||||
},
|
||||
(None, Some(named)) => Plan::AddAlias {
|
||||
entity_id: named.clone(),
|
||||
},
|
||||
(None, None) => Plan::CreateAndAlias,
|
||||
}
|
||||
}
|
||||
|
||||
/// Make sure every agent in `agents` has its entity, logging what could not be
|
||||
/// done. Never fails: see the module header.
|
||||
pub async fn ensure_agents(store: &impl AccessStore, agents: &[String]) {
|
||||
let accessor = match store.auth_mount_accessor(DEFAULT_CERT_MOUNT).await {
|
||||
Ok(accessor) => accessor,
|
||||
Err(e) => {
|
||||
tracing::warn!(
|
||||
error = %e,
|
||||
"agent entities are not managed: the cert auth mount's accessor could not be read; an agent whose role attaches the shared policy alone reads nothing until its entity is named after it"
|
||||
);
|
||||
return;
|
||||
}
|
||||
};
|
||||
let mut changed = 0_usize;
|
||||
for agent in agents {
|
||||
match ensure_one(store, &accessor, agent).await {
|
||||
Ok(Plan::Keep | Plan::Conflict { .. }) => {}
|
||||
Ok(_) => changed += 1,
|
||||
Err(e) => {
|
||||
tracing::warn!(agent, error = %format!("{e:#}"), "this agent's identity entity could not be set up");
|
||||
}
|
||||
}
|
||||
}
|
||||
tracing::info!(
|
||||
changed,
|
||||
agents = agents.len(),
|
||||
"agent identity entities checked"
|
||||
);
|
||||
}
|
||||
|
||||
/// Make sure `agent` has its entity, or say why not.
|
||||
///
|
||||
/// For a caller that must not go on without it, such as the one that narrows a
|
||||
/// cert-auth role to the shared policy: an agent whose entity is not named after
|
||||
/// it reads nothing under that policy.
|
||||
///
|
||||
/// # Errors
|
||||
/// When the cert mount's accessor cannot be read, when a store call fails, and
|
||||
/// on a [`Plan::Conflict`], which [`ensure_agents`] only logs.
|
||||
pub async fn ensure_agent(store: &impl AccessStore, agent: &str) -> Result<()> {
|
||||
let accessor = store
|
||||
.auth_mount_accessor(DEFAULT_CERT_MOUNT)
|
||||
.await
|
||||
.context("reading the cert auth mount's accessor")?;
|
||||
match ensure_one(store, &accessor, agent).await? {
|
||||
Plan::Conflict { alias, entity_name } => bail!(
|
||||
"the alias {alias} is on the entity {entity_name}, which is not {agent}; nothing was changed"
|
||||
),
|
||||
_ => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Observe, plan and apply for one agent.
|
||||
async fn ensure_one(store: &impl AccessStore, accessor: &str, agent: &str) -> Result<Plan> {
|
||||
let alias = policy::agent_object_name(agent)?;
|
||||
let seen = Seen {
|
||||
by_alias: store
|
||||
.entity_by_alias(&alias, accessor)
|
||||
.await
|
||||
.with_context(|| format!("looking up the entity owning alias {alias}"))?,
|
||||
by_name: store
|
||||
.entity_id_by_name(agent)
|
||||
.await
|
||||
.with_context(|| format!("looking up the entity named {agent}"))?,
|
||||
};
|
||||
let plan = plan(agent, &seen);
|
||||
match &plan {
|
||||
Plan::Keep => {}
|
||||
Plan::Rename { id } => {
|
||||
store
|
||||
.rename_entity(id, agent)
|
||||
.await
|
||||
.with_context(|| format!("renaming entity {id} to {agent}"))?;
|
||||
tracing::info!(agent, entity = %id, "agent identity entity renamed");
|
||||
}
|
||||
Plan::AddAlias { entity_id } => {
|
||||
store
|
||||
.create_entity_alias(&alias, accessor, entity_id)
|
||||
.await
|
||||
.with_context(|| format!("adding alias {alias} to entity {entity_id}"))?;
|
||||
tracing::info!(agent, entity = %entity_id, "agent identity alias added");
|
||||
}
|
||||
Plan::CreateAndAlias => {
|
||||
store
|
||||
.create_entity(agent)
|
||||
.await
|
||||
.with_context(|| format!("creating the entity {agent}"))?;
|
||||
let Some(entity_id) = store.entity_id_by_name(agent).await? else {
|
||||
bail!("the entity {agent} was created and is not there to read back");
|
||||
};
|
||||
store
|
||||
.create_entity_alias(&alias, accessor, &entity_id)
|
||||
.await
|
||||
.with_context(|| format!("adding alias {alias} to entity {entity_id}"))?;
|
||||
tracing::info!(agent, entity = %entity_id, "agent identity entity created");
|
||||
}
|
||||
Plan::Conflict { alias, entity_name } => {
|
||||
tracing::error!(
|
||||
agent,
|
||||
alias,
|
||||
entity_name,
|
||||
"the agent's alias is on an entity that is not the agent's; nothing was changed; under the shared policy alone the agent reads nothing until an operator resolves it"
|
||||
);
|
||||
}
|
||||
}
|
||||
Ok(plan)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn entity(id: &str, name: &str) -> EntityRef {
|
||||
EntityRef {
|
||||
id: id.to_owned(),
|
||||
name: name.to_owned(),
|
||||
}
|
||||
}
|
||||
|
||||
fn conflict(entity_name: &str) -> Plan {
|
||||
Plan::Conflict {
|
||||
alias: "hive-agent-atlas".to_owned(),
|
||||
entity_name: entity_name.to_owned(),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_entity_already_named_after_the_agent_is_kept() {
|
||||
let seen = Seen {
|
||||
by_alias: Some(entity("e1", "atlas")),
|
||||
by_name: Some("e1".to_owned()),
|
||||
};
|
||||
assert_eq!(plan("atlas", &seen), Plan::Keep);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nothing_at_all_is_created_with_its_alias() {
|
||||
let seen = Seen {
|
||||
by_alias: None,
|
||||
by_name: None,
|
||||
};
|
||||
assert_eq!(plan("atlas", &seen), Plan::CreateAndAlias);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_entity_a_login_named_is_renamed() {
|
||||
for generated in ["entity_1a2b3c4d.root", "entity_1a2b3c4d"] {
|
||||
let seen = Seen {
|
||||
by_alias: Some(entity("e1", generated)),
|
||||
by_name: None,
|
||||
};
|
||||
assert_eq!(
|
||||
plan("atlas", &seen),
|
||||
Plan::Rename {
|
||||
id: "e1".to_owned()
|
||||
},
|
||||
"{generated}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_entity_somebody_named_is_never_renamed() {
|
||||
let seen = Seen {
|
||||
by_alias: Some(entity("e1", "bob")),
|
||||
by_name: None,
|
||||
};
|
||||
assert_eq!(plan("atlas", &seen), conflict("bob"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_name_only_close_to_the_generated_shape_is_somebodys_choice() {
|
||||
for name in [
|
||||
"entity_",
|
||||
"entity_backup",
|
||||
"entity_1a2b3c4",
|
||||
"entity_1a2b3c4d5",
|
||||
"entity_1A2B3C4D",
|
||||
"entity_1a2b3c4g",
|
||||
"entity_1a2b3c4d.root2",
|
||||
"entity_1a2b3c4d.other",
|
||||
"entity_1a2b3c4d.root.root",
|
||||
"xentity_1a2b3c4d",
|
||||
"entity-1a2b3c4d",
|
||||
] {
|
||||
let seen = Seen {
|
||||
by_alias: Some(entity("e1", name)),
|
||||
by_name: None,
|
||||
};
|
||||
assert_eq!(plan("atlas", &seen), conflict(name), "{name}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_entity_without_the_alias_gets_it() {
|
||||
let seen = Seen {
|
||||
by_alias: None,
|
||||
by_name: Some("e1".to_owned()),
|
||||
};
|
||||
assert_eq!(
|
||||
plan("atlas", &seen),
|
||||
Plan::AddAlias {
|
||||
entity_id: "e1".to_owned()
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_alias_on_another_entity_while_the_agents_name_is_taken_is_a_conflict() {
|
||||
let seen = Seen {
|
||||
by_alias: Some(entity("e1", "entity_1a2b3c4d.root")),
|
||||
by_name: Some("e2".to_owned()),
|
||||
};
|
||||
assert_eq!(plan("atlas", &seen), conflict("entity_1a2b3c4d.root"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_alias_on_a_foreign_entity_is_not_moved_to_the_agents() {
|
||||
let seen = Seen {
|
||||
by_alias: Some(entity("e1", "bob")),
|
||||
by_name: Some("e2".to_owned()),
|
||||
};
|
||||
assert_eq!(plan("atlas", &seen), conflict("bob"));
|
||||
}
|
||||
}
|
||||
797
swarm-controller/src/secrets/agent_identity.rs
Normal file
797
swarm-controller/src/secrets/agent_identity.rs
Normal file
|
|
@ -0,0 +1,797 @@
|
|||
//! One agent's own identity at the swarm's secret store: issued by the store,
|
||||
//! published here, granted here — and, before the job node reports success,
|
||||
//! **used** here.
|
||||
//!
|
||||
//! The swarm obtains the agent's certificate so that no hive ever needs the
|
||||
//! capability to obtain one; the hive only carries it down. The controller is
|
||||
//! the swarm-level service that asks because it already logs in to the store,
|
||||
//! and its grant covers exactly the calls made here (`swarm-bao.nix`'s
|
||||
//! `controllerPolicyText`: `update` on the agent PKI role's `issue` path, and
|
||||
//! `create/update` on `secret/data/swarm/agents/*`, on
|
||||
//! `sys/policies/acl/hive-*`, and on `auth/cert/certs/hive-*` (`delete` too), plus the
|
||||
//! `identity/` and `sys/auth/cert` stanzas [`crate::agent_entity`] and [`crate::agent_cutoff`] use).
|
||||
//!
|
||||
//! **Two credentials, deliberately unrelated.** The certificate reaches the
|
||||
//! store; the queue secret identifies the agent to the swarm queue. Both sit
|
||||
//! under `swarm/agents/<agent>`, so neither costs a grant — but the second is
|
||||
//! not derived from the first, so either renews without reference to the other.
|
||||
//!
|
||||
//! Four separate strings have to agree before an agent can authenticate: the
|
||||
//! identity entity's name, the cert-auth role's name, the certificate's common
|
||||
//! name, and the authority the role pins. That is the kind of agreement that
|
||||
//! holds in review and fails in production — a mismatch is a 403 naming none
|
||||
//! of the four — so [`mint_and_verify`] does not finish on a write. See
|
||||
//! [`read_back_as_agent`].
|
||||
//!
|
||||
//! The authority is the store's own agent CA, generated inside its agent PKI
|
||||
//! mount; its key never leaves the store. It signs no host leaf, and no host
|
||||
//! role pins it, so an agent's certificate satisfies only that agent's role.
|
||||
//! [`crate::agent_renewal`] re-issues a live agent's leaf once it is past half
|
||||
//! its validity (the role's `ttl`) or missing, by queueing the same node as creation.
|
||||
|
||||
use crate::store::AccessStore;
|
||||
use anyhow::{Context, Result, bail};
|
||||
use swarm_secret_client::{
|
||||
SecretStore,
|
||||
client::{DEFAULT_CERT_MOUNT, Settings},
|
||||
mtls, policy, queue,
|
||||
};
|
||||
|
||||
/// The PKI mount agent leaves are issued from, as `swarm-controller.nix` sets
|
||||
/// it from `deploy.bao.agentPkiMountPath`.
|
||||
pub const ENV_AGENT_PKI_MOUNT: &str = "SWARM_CONTROLLER_AGENT_PKI_MOUNT";
|
||||
|
||||
/// The role on [`ENV_AGENT_PKI_MOUNT`] agent leaves are issued through, as
|
||||
/// `swarm-controller.nix` sets it from `deploy.bao.agentPkiRoleName`.
|
||||
pub const ENV_AGENT_PKI_ROLE: &str = "SWARM_CONTROLLER_AGENT_PKI_ROLE";
|
||||
|
||||
/// Where agent leaves are issued: `(mount, role)`, read from `get`.
|
||||
///
|
||||
/// # Errors
|
||||
/// Naming the first of the two variables that is unset or empty.
|
||||
fn agent_pki(get: impl Fn(&str) -> Option<String>) -> Result<(String, String)> {
|
||||
let required = |var: &str| -> Result<String> {
|
||||
get(var)
|
||||
.filter(|v| !v.is_empty())
|
||||
.with_context(|| format!("{var} is unset or empty, so no agent leaf can be issued"))
|
||||
};
|
||||
Ok((
|
||||
required(ENV_AGENT_PKI_MOUNT)?,
|
||||
required(ENV_AGENT_PKI_ROLE)?,
|
||||
))
|
||||
}
|
||||
|
||||
/// What the cert-auth role for `agent` is written from.
|
||||
struct RoleInputs<'a> {
|
||||
/// Role name and the common name the role matches: one string.
|
||||
name: String,
|
||||
/// The authority the role pins: the one that signed this very leaf.
|
||||
ca: &'a str,
|
||||
/// The policies the role attaches by name: the one every agent shares.
|
||||
attached: Vec<String>,
|
||||
}
|
||||
|
||||
fn role_inputs<'a>(
|
||||
agent: &str,
|
||||
credential: &'a mtls::Credential,
|
||||
ssh: bool,
|
||||
) -> Result<RoleInputs<'a>> {
|
||||
let name = policy::agent_object_name(agent)?;
|
||||
Ok(RoleInputs {
|
||||
name: name.clone(),
|
||||
ca: &credential.ca,
|
||||
attached: crate::agent_ssh::attached(ssh),
|
||||
})
|
||||
}
|
||||
|
||||
/// The inputs for `agent`'s role, with the signing policy attached when the role
|
||||
/// it replaces has it. The role is where the agent's SSH switch lives, so a
|
||||
/// rewrite for a new certificate keeps what it has (`crate::agent_ssh`).
|
||||
async fn inputs_keeping_ssh<'a>(
|
||||
store: &impl AccessStore,
|
||||
agent: &str,
|
||||
credential: &'a mtls::Credential,
|
||||
) -> Result<RoleInputs<'a>> {
|
||||
let name = policy::agent_object_name(agent).at(MintStep::Role)?;
|
||||
let ssh = crate::agent_ssh::role_has_ssh(store, &name)
|
||||
.await
|
||||
.with_context(|| format!("reading the policies of the cert-auth role {name}"))
|
||||
.at(MintStep::Role)?;
|
||||
role_inputs(agent, credential, ssh).at(MintStep::Role)
|
||||
}
|
||||
|
||||
/// Write the shared policy, name the agent's entity and enable it, then write
|
||||
/// the cert-auth role that attaches the policy.
|
||||
///
|
||||
/// Enabling clears the flag [`crate::agent_cutoff::cut_off`] set when an agent
|
||||
/// of this name was destroyed, so a new agent of that name can log in.
|
||||
///
|
||||
/// The entity comes before the role and is a precondition for it. The role
|
||||
/// attaches the shared policy alone, so an agent whose entity is not named after
|
||||
/// it reads nothing under it. This also runs for a live agent's renewal, which
|
||||
/// rewrites the role its current leaf logs in under: when the entity step
|
||||
/// fails, or finds the alias on another entity, the role is left as it was and
|
||||
/// the renewal fails while the agent keeps working.
|
||||
async fn publish_access(
|
||||
store: &impl AccessStore,
|
||||
agent: &str,
|
||||
inputs: &RoleInputs<'_>,
|
||||
) -> Result<()> {
|
||||
store
|
||||
.write_policy(policy::SHARED_AGENT_POLICY, &policy::render_shared_agent())
|
||||
.await
|
||||
.with_context(|| {
|
||||
format!(
|
||||
"writing the shared agent policy {}",
|
||||
policy::SHARED_AGENT_POLICY
|
||||
)
|
||||
})
|
||||
.at(MintStep::Policy)?;
|
||||
store
|
||||
.write_policy(policy::SSH_POLICY, &policy::render_ssh_signer())
|
||||
.await
|
||||
.with_context(|| format!("writing the SSH signing policy {}", policy::SSH_POLICY))
|
||||
.at(MintStep::Policy)?;
|
||||
crate::agent_entity::ensure_agent(store, agent)
|
||||
.await
|
||||
.with_context(|| format!("naming {agent}'s identity entity; the role is not changed"))
|
||||
.at(MintStep::Entity)?;
|
||||
crate::agent_cutoff::restore(store, agent)
|
||||
.await
|
||||
.with_context(|| format!("enabling {agent}'s identity entity; the role is not changed"))
|
||||
.at(MintStep::Entity)?;
|
||||
store
|
||||
.write_cert_role(
|
||||
DEFAULT_CERT_MOUNT,
|
||||
&inputs.name,
|
||||
inputs.ca,
|
||||
&inputs.name,
|
||||
&inputs
|
||||
.attached
|
||||
.iter()
|
||||
.map(String::as_str)
|
||||
.collect::<Vec<_>>(),
|
||||
)
|
||||
.await
|
||||
.with_context(|| format!("writing the cert-auth role {}", inputs.name))
|
||||
.at(MintStep::Role)
|
||||
}
|
||||
|
||||
/// How many bytes of kernel randomness a queue secret is before encoding.
|
||||
///
|
||||
/// Thirty-two because the secret is a bearer token compared for equality and
|
||||
/// nothing else — there is no work factor and no rate limit behind it, so the
|
||||
/// only defence is that guessing is not worth attempting. Encoded it is 43
|
||||
/// characters.
|
||||
const QUEUE_SECRET_BYTES: usize = 32;
|
||||
|
||||
/// Generate a queue secret: [`QUEUE_SECRET_BYTES`] from the kernel's CSPRNG,
|
||||
/// base64url without padding.
|
||||
///
|
||||
/// The alphabet matters and is the reason for `URL_SAFE_NO_PAD` rather than
|
||||
/// the standard engine: the secret is destined to be carried in a token the
|
||||
/// verifying end splits on `.`, so it must not be able to contain one. This
|
||||
/// alphabet is `[A-Za-z0-9_-]`, and `=` padding is dropped as well so the
|
||||
/// value survives anything that treats it as a word.
|
||||
///
|
||||
/// # Errors
|
||||
/// When the kernel will not supply randomness. Bubbled rather than panicked
|
||||
/// on: the caller is a job node that reports a named failure, and a secret
|
||||
/// from a degraded source is worse than no secret.
|
||||
pub(crate) fn generate_queue_secret() -> Result<String> {
|
||||
let mut bytes = [0u8; QUEUE_SECRET_BYTES];
|
||||
getrandom::fill(&mut bytes).context("drawing a queue secret from the kernel's CSPRNG")?;
|
||||
Ok(base64::Engine::encode(
|
||||
&base64::engine::general_purpose::URL_SAFE_NO_PAD,
|
||||
bytes,
|
||||
))
|
||||
}
|
||||
|
||||
/// The part of [`mint_and_verify`] a failure came from.
|
||||
///
|
||||
/// Attached to the error as its outermost context, so the
|
||||
/// message leads with it and [`failed_step`] reads it back as a value.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum MintStep {
|
||||
/// Reading the environment and the agent's name, before any store call.
|
||||
Setup,
|
||||
/// Logging in to the store as the controller.
|
||||
StoreLogin,
|
||||
/// Issuing the leaf from the agent PKI role.
|
||||
IssueLeaf,
|
||||
/// Publishing the leaf at [`mtls::identity_path`].
|
||||
WriteBaoMtls,
|
||||
/// Reading or publishing the queue secret at [`queue::agent_queue_path`].
|
||||
Queue,
|
||||
/// Writing the shared ACL document.
|
||||
Policy,
|
||||
/// Naming the agent's identity entity.
|
||||
Entity,
|
||||
/// Deriving or writing the cert-auth role.
|
||||
Role,
|
||||
/// The login as the agent and the reads after it.
|
||||
ReadBack,
|
||||
}
|
||||
|
||||
impl MintStep {
|
||||
/// The step as it reads in a log line.
|
||||
#[must_use]
|
||||
pub const fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
MintStep::Setup => "setup",
|
||||
MintStep::StoreLogin => "store login",
|
||||
MintStep::IssueLeaf => "issue leaf",
|
||||
MintStep::WriteBaoMtls => "write bao-mtls",
|
||||
MintStep::Queue => "queue",
|
||||
MintStep::Policy => "policy",
|
||||
MintStep::Entity => "entity",
|
||||
MintStep::Role => "role",
|
||||
MintStep::ReadBack => "read back",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Display for MintStep {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.write_str(self.as_str())
|
||||
}
|
||||
}
|
||||
|
||||
/// The [`MintStep`] `error` was attached to, if [`mint_and_verify`] raised it.
|
||||
#[must_use]
|
||||
pub fn failed_step(error: &anyhow::Error) -> Option<MintStep> {
|
||||
error.downcast_ref::<MintStep>().copied()
|
||||
}
|
||||
|
||||
/// Names the [`MintStep`] a failing result belongs to.
|
||||
trait AtStep<T> {
|
||||
fn at(self, step: MintStep) -> Result<T>;
|
||||
}
|
||||
|
||||
impl<T, E: Into<anyhow::Error>> AtStep<T> for Result<T, E> {
|
||||
fn at(self, step: MintStep) -> Result<T> {
|
||||
self.map_err(|e| e.into().context(step))
|
||||
}
|
||||
}
|
||||
|
||||
/// Give `agent` an identity at the store, and prove it works.
|
||||
///
|
||||
/// Six store calls' worth of agreement, then the login that checks it:
|
||||
///
|
||||
/// 1. have the agent PKI role issue a leaf whose common name is
|
||||
/// [`policy::agent_object_name`]; the store generates its key;
|
||||
/// 2. publish it at [`mtls::identity_path`], where the agent's hive collects
|
||||
/// it under the hive's own certificate;
|
||||
/// 3. publish a queue secret at [`queue::agent_queue_path`] — the agent's own
|
||||
/// identity at the swarm queue, minted here so that the credential an agent
|
||||
/// presents names *it* rather than its hive;
|
||||
/// 4. write the shared ACL document [`policy::render_shared_agent`] renders;
|
||||
/// 5. name the agent's identity entity after the agent ([`crate::agent_entity`]),
|
||||
/// which the policy reads, and enable it ([`crate::agent_cutoff::restore`]);
|
||||
/// 6. write the cert-auth role that ties the three together, attaching that
|
||||
/// policy and pinning the CA the store named as this leaf's issuer.
|
||||
///
|
||||
/// Policy and entity before role: see [`publish_access`].
|
||||
///
|
||||
/// ⚠️ **Step 3 is idempotent and steps 1–2 are not.** Re-running issues a
|
||||
/// fresh leaf, picked up on the agent's next boot, but leaves an existing
|
||||
/// queue secret alone: this is re-run against running agents, which hold that
|
||||
/// secret in a live connection. Revoking one means deleting the path;
|
||||
/// replacing one by age is [`crate::agent_renewal`]'s.
|
||||
///
|
||||
/// # Errors
|
||||
/// Anything that stops one of those six steps, or the read-back login, with the
|
||||
/// [`MintStep`] ([`failed_step`]) leading the message. A failure here fails the
|
||||
/// job node and nothing else — a new agent is still created, without a store
|
||||
/// identity, and a live agent keeps the role it had.
|
||||
pub async fn mint_and_verify(agent: &str) -> Result<()> {
|
||||
let (mount, pki_role) = agent_pki(|k| std::env::var(k).ok()).at(MintStep::Setup)?;
|
||||
let name = policy::agent_object_name(agent).at(MintStep::Setup)?;
|
||||
let path = mtls::identity_path(agent).at(MintStep::Setup)?;
|
||||
let queue_path = queue::agent_queue_path(agent).at(MintStep::Setup)?;
|
||||
|
||||
let store = crate::store::connect()
|
||||
.await
|
||||
.context("logging in to the swarm secret store")
|
||||
.at(MintStep::StoreLogin)?;
|
||||
let credential = store
|
||||
.issue_client_certificate(&mount, &pki_role, &name)
|
||||
.await
|
||||
.with_context(|| format!("issuing {name}'s certificate from {mount}/issue/{pki_role}"))
|
||||
.at(MintStep::IssueLeaf)?;
|
||||
store
|
||||
.write(&path, &credential)
|
||||
.await
|
||||
.with_context(|| format!("publishing the agent identity at {path}"))
|
||||
.at(MintStep::WriteBaoMtls)?;
|
||||
|
||||
// Read before write, and `read_optional` rather than `read`, so that only
|
||||
// a genuine 404 leads to a new secret — see that method for why every
|
||||
// other failure has to stay a failure here.
|
||||
let existing: Option<queue::AgentCredential> = store
|
||||
.read_optional(&queue_path)
|
||||
.await
|
||||
.with_context(|| format!("checking whether {queue_path} already holds a credential"))
|
||||
.at(MintStep::Queue)?;
|
||||
// The secret and its mint time survive a re-run. An object naming a
|
||||
// different agent is corrected by rewriting the name around the *same*
|
||||
// `value`, which no live connection notices.
|
||||
let wanted = match &existing {
|
||||
Some(existing) => queue::AgentCredential {
|
||||
agent: agent.to_owned(),
|
||||
..existing.clone()
|
||||
},
|
||||
None => crate::agent_renewal::fresh(agent, crate::agent_renewal::unix_now())
|
||||
.at(MintStep::Queue)?,
|
||||
};
|
||||
if existing.as_ref() == Some(&wanted) {
|
||||
tracing::info!(
|
||||
agent,
|
||||
%queue_path,
|
||||
"agent queue credential already published; left as it is"
|
||||
);
|
||||
} else {
|
||||
store
|
||||
.write(&queue_path, &wanted)
|
||||
.await
|
||||
.with_context(|| format!("publishing the agent queue credential at {queue_path}"))
|
||||
.at(MintStep::Queue)?;
|
||||
tracing::info!(
|
||||
agent,
|
||||
%queue_path,
|
||||
// Never "rotated": the secret is the same one, only the name
|
||||
// around it moved.
|
||||
corrected = existing.is_some(),
|
||||
"agent queue credential published"
|
||||
);
|
||||
}
|
||||
let queue_credential = wanted;
|
||||
|
||||
let inputs = inputs_keeping_ssh(&store, agent, &credential).await?;
|
||||
publish_access(&store, agent, &inputs).await?;
|
||||
tracing::info!(agent, %path, role = %name, "agent store identity published");
|
||||
|
||||
read_back_as_agent(&credential, &name, &path, &queue_path, &queue_credential)
|
||||
.await
|
||||
.at(MintStep::ReadBack)?;
|
||||
tracing::info!(
|
||||
agent,
|
||||
role = %name,
|
||||
"agent store identity verified: the issued leaf logged in and read both its own paths"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Revoke `agent`'s queue credential: delete the path
|
||||
/// [`mint_and_verify`]'s step 3 published, and everything ever written at it.
|
||||
///
|
||||
/// The undo of that one step and of no other. The leaf, the ACL document and
|
||||
/// the cert-auth role that make up the rest of an agent's identity stay where
|
||||
/// they are — they are what a *hive* uses to collect an agent's secrets, they
|
||||
/// are minted afresh on every run of the mint, and tearing them down is not
|
||||
/// what the queue credential outliving its holder is about.
|
||||
///
|
||||
/// **Deletes every version, not the newest one.** The mint rewrites this path
|
||||
/// whenever the principal it names has to be corrected, so a soft delete would
|
||||
/// leave the identical secret sitting in version history, readable at
|
||||
/// `?version=N` by anything that can read the path at all — a value still
|
||||
/// recoverable has not been revoked. See
|
||||
/// [`SecretStore::delete_all_versions`][swarm_secret_client::SecretStore::delete_all_versions].
|
||||
///
|
||||
/// **Idempotent**: revoking an agent that never had a credential, or one
|
||||
/// already revoked, succeeds and says so. A teardown that runs twice is
|
||||
/// ordinary, and a second run that failed would be a worse fault than the one
|
||||
/// this exists to fix.
|
||||
///
|
||||
/// # Errors
|
||||
/// When the store cannot be reached or refuses the delete. The caller decides
|
||||
/// what that costs — `set_agent_state` logs it and lets the destroy proceed,
|
||||
/// since a credential that is still live is a smaller harm than an agent that
|
||||
/// cannot be torn down.
|
||||
pub async fn revoke_queue_credential(agent: &str) -> Result<()> {
|
||||
let queue_path = queue::agent_queue_path(agent)?;
|
||||
let store = crate::store::connect()
|
||||
.await
|
||||
.context("logging in to the swarm secret store")?;
|
||||
store
|
||||
.delete_all_versions(&queue_path)
|
||||
.await
|
||||
.with_context(|| format!("revoking the agent queue credential at {queue_path}"))?;
|
||||
// At `info` and unconditional: an unlogged revocation is indistinguishable
|
||||
// from a leak, and this line is the only record an operator has that the
|
||||
// credential stopped being usable. It cannot say whether one was there —
|
||||
// the controller's grant on these paths is write-only by design, so it
|
||||
// deletes blind.
|
||||
tracing::info!(
|
||||
agent,
|
||||
%queue_path,
|
||||
"agent queue credential revoked: every version of the path deleted"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The consumer of everything [`mint_and_verify`] wrote: log in **as the
|
||||
/// agent**, with the leaf just issued, and read back both paths just
|
||||
/// published.
|
||||
///
|
||||
/// The address and the store's CA come from this process's own `BAO_*`
|
||||
/// environment; the *identity* deliberately does not — see
|
||||
/// [`SecretStore::connect_with_identity`]. The freshly issued private key
|
||||
/// never touches a filesystem.
|
||||
///
|
||||
/// Both paths, not just the certificate's, for the reason this function
|
||||
/// exists at all: the queue credential is readable only because it sits inside
|
||||
/// the stanza [`policy::render_shared_agent`] grants, and a policy that
|
||||
/// drifted from that path would otherwise fail at the agent's first connection
|
||||
/// — far from here, as a denial naming neither the policy nor the path.
|
||||
///
|
||||
/// # Errors
|
||||
/// When the store refuses the login (the role, the authority or the common
|
||||
/// name disagree), when either read is denied (the policy does not cover the
|
||||
/// path, or the role attached the wrong policy), or when what comes back is
|
||||
/// not what went in.
|
||||
async fn read_back_as_agent(
|
||||
credential: &mtls::Credential,
|
||||
role: &str,
|
||||
path: &str,
|
||||
queue_path: &str,
|
||||
queue_credential: &queue::AgentCredential,
|
||||
) -> Result<()> {
|
||||
let settings = Settings::from_env()
|
||||
.context("reading this daemon's own store settings for the read-back")?;
|
||||
|
||||
// The concatenated blob `connect_with_identity` takes, built in memory.
|
||||
let mut identity = credential.cert.clone().into_bytes();
|
||||
identity.push(b'\n');
|
||||
identity.extend_from_slice(credential.key.as_bytes());
|
||||
|
||||
let as_agent =
|
||||
SecretStore::connect_with_identity(&settings, &identity, role, DEFAULT_CERT_MOUNT)
|
||||
.await
|
||||
.with_context(|| {
|
||||
format!("logging in to the store as {role} with the leaf just issued")
|
||||
})?;
|
||||
let read_back: mtls::Credential = as_agent
|
||||
.read(path)
|
||||
.await
|
||||
.with_context(|| format!("reading {path} back under {role}'s own token"))?;
|
||||
|
||||
// Compared, not merely decoded: a successful read of an object written by
|
||||
// some earlier run would otherwise pass this check while this run's leaf
|
||||
// was the one nobody could use. Nothing about either value is printed.
|
||||
if read_back != *credential {
|
||||
bail!("the store returned a different object at {path} than the one just published");
|
||||
}
|
||||
|
||||
let read_back: queue::AgentCredential = as_agent
|
||||
.read(queue_path)
|
||||
.await
|
||||
.with_context(|| format!("reading {queue_path} back under {role}'s own token"))?;
|
||||
// The agent is compared as well as the secret: the verifying end refuses
|
||||
// an object naming a different agent than the path, so a mismatch here is
|
||||
// the same class of fault as an unreadable path.
|
||||
if read_back != *queue_credential {
|
||||
bail!("the store returned a different object at {queue_path} than the one just published");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{
|
||||
ENV_AGENT_PKI_MOUNT, ENV_AGENT_PKI_ROLE, MintStep, QUEUE_SECRET_BYTES, agent_pki,
|
||||
failed_step, generate_queue_secret, inputs_keeping_ssh, publish_access, role_inputs,
|
||||
};
|
||||
use crate::store::fake::FakeAccess;
|
||||
use swarm_secret_client::{mtls, policy};
|
||||
|
||||
/// The alphabet claim the token format rests on: the secret is carried in
|
||||
/// a composite the verifying end splits on `.`, so a secret that could
|
||||
/// contain one would make that split ambiguous. Also the entropy claim —
|
||||
/// a generator that silently returned a short or constant value would pass
|
||||
/// every other test in this file.
|
||||
#[test]
|
||||
fn a_queue_secret_is_high_entropy_and_carries_no_separator() {
|
||||
let a = generate_queue_secret().expect("the kernel supplies randomness");
|
||||
let b = generate_queue_secret().expect("twice");
|
||||
assert_ne!(a, b, "two draws must not agree");
|
||||
|
||||
// base64 without padding: one character per six bits, rounded up.
|
||||
assert_eq!(a.len(), (QUEUE_SECRET_BYTES * 8).div_ceil(6));
|
||||
assert!(
|
||||
a.chars()
|
||||
.all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_'),
|
||||
"{a}"
|
||||
);
|
||||
assert!(!a.contains('.'), "{a}");
|
||||
assert!(!a.contains('='), "{a}");
|
||||
}
|
||||
|
||||
/// Revocation undoes step 3 of the mint and nothing else, and both ends
|
||||
/// spell the path through one function — the property that keeps a
|
||||
/// revocation from missing the object it is meant to remove.
|
||||
///
|
||||
/// The second half is what stops this being a tautology: the agent's
|
||||
/// other published object, the mTLS leaf, is at a different path and is
|
||||
/// deliberately left alone. Revoking both would take away the identity a
|
||||
/// re-created agent is re-minted under, for a credential problem that is
|
||||
/// only about the queue.
|
||||
#[test]
|
||||
fn revocation_names_the_path_the_mint_published_and_not_the_leaf_beside_it() {
|
||||
use swarm_secret_client::{mtls, queue};
|
||||
|
||||
assert_eq!(
|
||||
queue::agent_queue_path("atlas").expect("a plain name is legal"),
|
||||
"swarm/agents/atlas/queue"
|
||||
);
|
||||
assert_ne!(
|
||||
queue::agent_queue_path("atlas").expect("legal"),
|
||||
mtls::identity_path("atlas").expect("legal"),
|
||||
);
|
||||
}
|
||||
|
||||
/// A name the store must never be asked to delete under. `revoke_queue_credential`
|
||||
/// builds its path with the same validating function the mint does, so a
|
||||
/// traversal is refused before a request is made rather than addressing
|
||||
/// some other principal's secret.
|
||||
#[test]
|
||||
fn a_traversal_never_becomes_a_revocation() {
|
||||
swarm_secret_client::queue::agent_queue_path("../pr1ma")
|
||||
.expect_err("a traversal is not a legal agent name");
|
||||
}
|
||||
|
||||
fn both(k: &str) -> Option<String> {
|
||||
match k {
|
||||
ENV_AGENT_PKI_MOUNT => Some("pki-agents".to_owned()),
|
||||
ENV_AGENT_PKI_ROLE => Some("swarm-agent".to_owned()),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_issue_path_comes_from_the_two_variables_the_module_sets() {
|
||||
assert_eq!(
|
||||
agent_pki(both).expect("both set"),
|
||||
("pki-agents".to_owned(), "swarm-agent".to_owned())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_missing_or_empty_pki_variable_is_named() {
|
||||
for var in [ENV_AGENT_PKI_MOUNT, ENV_AGENT_PKI_ROLE] {
|
||||
let unset = agent_pki(|k| if k == var { None } else { both(k) })
|
||||
.expect_err("one variable is unset");
|
||||
assert!(format!("{unset:#}").contains(var), "{unset:#}");
|
||||
let empty = agent_pki(|k| {
|
||||
if k == var {
|
||||
Some(String::new())
|
||||
} else {
|
||||
both(k)
|
||||
}
|
||||
})
|
||||
.expect_err("one variable is empty");
|
||||
assert!(format!("{empty:#}").contains(var), "{empty:#}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Three of the four strings that must agree, checked where this process
|
||||
/// sets them: role and matched CN are one name; the pinned CA is the issuer
|
||||
/// the store reported for this leaf; the role attaches the shared policy
|
||||
/// and no policy of the agent's own.
|
||||
#[test]
|
||||
fn the_role_pins_the_leafs_own_issuer_under_the_agents_name() {
|
||||
let credential = mtls::Credential {
|
||||
cert: "LEAF".to_owned(),
|
||||
key: "KEY".to_owned(),
|
||||
ca: "AGENT-CA".to_owned(),
|
||||
};
|
||||
let inputs = role_inputs("atlas", &credential, false).expect("legal");
|
||||
assert_eq!(inputs.name, "hive-agent-atlas");
|
||||
assert_eq!(
|
||||
inputs.name,
|
||||
policy::agent_object_name("atlas").expect("legal"),
|
||||
"the CN the leaf is issued for"
|
||||
);
|
||||
assert_eq!(inputs.ca, "AGENT-CA");
|
||||
// Only the shared policy: a policy named for the agent is not attached.
|
||||
assert_eq!(
|
||||
inputs.attached,
|
||||
[policy::SHARED_AGENT_POLICY],
|
||||
"the role attaches the shared policy and nothing else"
|
||||
);
|
||||
assert!(
|
||||
!inputs.attached.contains(&inputs.name),
|
||||
"the role must not attach a policy named for the agent"
|
||||
);
|
||||
|
||||
// The control: another agent's inputs differ in name, and attach the
|
||||
// same shared policy, so the check above can see a policy that is there.
|
||||
let other = role_inputs("argus", &credential, false).expect("legal");
|
||||
assert_ne!(other.name, inputs.name);
|
||||
assert_eq!(other.attached, inputs.attached);
|
||||
}
|
||||
|
||||
fn credential() -> mtls::Credential {
|
||||
mtls::Credential {
|
||||
cert: "LEAF".to_owned(),
|
||||
key: "KEY".to_owned(),
|
||||
ca: "AGENT-CA".to_owned(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The control: with a working entity step the role is narrowed, after the
|
||||
/// entity is named, so the absence checks below can see a role write.
|
||||
#[tokio::test]
|
||||
async fn the_role_is_narrowed_after_the_entity_is_named() {
|
||||
let store = FakeAccess::default();
|
||||
let credential = credential();
|
||||
let inputs = role_inputs("atlas", &credential, false).expect("legal");
|
||||
publish_access(&store, "atlas", &inputs)
|
||||
.await
|
||||
.expect("a store that accepts everything");
|
||||
assert_eq!(
|
||||
store.roles_written(),
|
||||
["write_cert_role hive-agent-atlas hive-agent"]
|
||||
);
|
||||
let calls = store.calls();
|
||||
let at = |call: &str| calls.iter().position(|c| c == call).expect(call);
|
||||
assert!(
|
||||
at("create_entity_alias hive-agent-atlas")
|
||||
< at("write_cert_role hive-agent-atlas hive-agent"),
|
||||
"the entity is named before the role is written: {calls:?}"
|
||||
);
|
||||
}
|
||||
|
||||
/// Switch on: the role attaches the signing policy as well, and the policy
|
||||
/// itself is written before the role names it. Off: the shared policy alone.
|
||||
/// A rewrite for a new certificate keeps what the role had.
|
||||
#[tokio::test]
|
||||
async fn the_signing_policy_is_attached_only_when_ssh_is_on_and_a_rewrite_keeps_it() {
|
||||
let credential = credential();
|
||||
let on = FakeAccess::default();
|
||||
let inputs = role_inputs("atlas", &credential, true).expect("legal");
|
||||
publish_access(&on, "atlas", &inputs)
|
||||
.await
|
||||
.expect("accepted");
|
||||
assert_eq!(
|
||||
on.roles_written(),
|
||||
["write_cert_role hive-agent-atlas hive-agent,hive-agent-ssh"]
|
||||
);
|
||||
let calls = on.calls();
|
||||
let at = |call: &str| calls.iter().position(|c| c == call).expect(call);
|
||||
assert!(
|
||||
at("write_policy hive-agent-ssh")
|
||||
< at("write_cert_role hive-agent-atlas hive-agent,hive-agent-ssh"),
|
||||
"the policy exists before the role names it: {calls:?}"
|
||||
);
|
||||
|
||||
// The rewrite reads the role it replaces, and keeps the grant.
|
||||
let again = inputs_keeping_ssh(&on, "atlas", &credential)
|
||||
.await
|
||||
.expect("reads");
|
||||
assert_eq!(again.attached, ["hive-agent", "hive-agent-ssh"]);
|
||||
|
||||
// The control: a role that never had it does not gain it.
|
||||
let fresh = inputs_keeping_ssh(&FakeAccess::default(), "atlas", &credential)
|
||||
.await
|
||||
.expect("reads");
|
||||
assert_eq!(fresh.attached, ["hive-agent"]);
|
||||
let off = FakeAccess::default();
|
||||
let inputs = role_inputs("atlas", &credential, false).expect("legal");
|
||||
publish_access(&off, "atlas", &inputs)
|
||||
.await
|
||||
.expect("accepted");
|
||||
assert_eq!(
|
||||
off.roles_written(),
|
||||
["write_cert_role hive-agent-atlas hive-agent"]
|
||||
);
|
||||
assert!(
|
||||
!crate::agent_ssh::role_has_ssh(&off, "hive-agent-atlas")
|
||||
.await
|
||||
.expect("reads")
|
||||
);
|
||||
}
|
||||
|
||||
/// An agent created under the name of a destroyed one gets its entity
|
||||
/// enabled and its role back, the enable first.
|
||||
#[tokio::test]
|
||||
async fn re_creating_a_cut_off_agent_enables_its_entity_and_writes_its_role() {
|
||||
let store = FakeAccess::default().with_entity("atlas");
|
||||
crate::agent_cutoff::cut_off(&store, "atlas")
|
||||
.await
|
||||
.expect("accepted");
|
||||
assert!(store.is_disabled("atlas"), "the control: it was cut off");
|
||||
assert_eq!(store.role("hive-agent-atlas"), None);
|
||||
|
||||
let credential = credential();
|
||||
let inputs = role_inputs("atlas", &credential, false).expect("legal");
|
||||
publish_access(&store, "atlas", &inputs)
|
||||
.await
|
||||
.expect("a store that accepts everything");
|
||||
assert!(!store.is_disabled("atlas"), "{:?}", store.calls());
|
||||
assert!(store.role("hive-agent-atlas").is_some());
|
||||
let calls = store.calls();
|
||||
let at = |call: &str| calls.iter().position(|c| c == call).expect(call);
|
||||
assert!(
|
||||
at("set_entity_disabled atlas false")
|
||||
< at("write_cert_role hive-agent-atlas hive-agent"),
|
||||
"the entity is enabled before the role is written: {calls:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_mint_whose_enable_is_refused_leaves_the_role_alone() {
|
||||
let store = FakeAccess::default().refusing_disable();
|
||||
let credential = credential();
|
||||
let inputs = role_inputs("atlas", &credential, false).expect("legal");
|
||||
let err = publish_access(&store, "atlas", &inputs)
|
||||
.await
|
||||
.expect_err("the enable is refused");
|
||||
assert_eq!(failed_step(&err), Some(MintStep::Entity), "{err:#}");
|
||||
assert!(store.roles_written().is_empty(), "{:?}", store.calls());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_renewal_whose_entity_step_fails_leaves_the_role_alone() {
|
||||
let store = FakeAccess::without_accessor();
|
||||
let credential = credential();
|
||||
let inputs = role_inputs("atlas", &credential, false).expect("legal");
|
||||
let err = publish_access(&store, "atlas", &inputs)
|
||||
.await
|
||||
.expect_err("the entity step failed");
|
||||
assert!(
|
||||
format!("{err:#}").contains("the role is not changed"),
|
||||
"{err:#}"
|
||||
);
|
||||
assert!(store.roles_written().is_empty(), "{:?}", store.calls());
|
||||
// The control: the call log sees writes, and the shared policy was one.
|
||||
assert!(
|
||||
store
|
||||
.calls()
|
||||
.contains(&"write_policy hive-agent".to_owned())
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_renewal_whose_alias_is_on_another_entity_leaves_the_role_alone() {
|
||||
let store = FakeAccess::with_alias_on("id-1", "somebody");
|
||||
let credential = credential();
|
||||
let inputs = role_inputs("atlas", &credential, false).expect("legal");
|
||||
let err = publish_access(&store, "atlas", &inputs)
|
||||
.await
|
||||
.expect_err("a conflict is an error");
|
||||
assert!(format!("{err:#}").contains("somebody"), "{err:#}");
|
||||
assert!(store.roles_written().is_empty(), "{:?}", store.calls());
|
||||
assert!(
|
||||
store
|
||||
.calls()
|
||||
.contains(&"entity_by_alias hive-agent-atlas".to_owned())
|
||||
);
|
||||
}
|
||||
|
||||
/// Each refusal names the step it came from, in the message and as a value
|
||||
/// the job runner logs. Two different steps, so a tag that named every
|
||||
/// failure alike would fail one of them.
|
||||
#[tokio::test]
|
||||
async fn a_refused_step_is_named_in_the_message_and_by_failed_step() {
|
||||
let credential = credential();
|
||||
let inputs = role_inputs("atlas", &credential, false).expect("legal");
|
||||
|
||||
let err = publish_access(&FakeAccess::refusing_policies(), "atlas", &inputs)
|
||||
.await
|
||||
.expect_err("the policy write is refused");
|
||||
assert_eq!(failed_step(&err), Some(MintStep::Policy), "{err:#}");
|
||||
assert!(format!("{err:#}").starts_with("policy: "), "{err:#}");
|
||||
|
||||
let err = publish_access(&FakeAccess::without_accessor(), "atlas", &inputs)
|
||||
.await
|
||||
.expect_err("the entity step fails");
|
||||
assert_eq!(failed_step(&err), Some(MintStep::Entity), "{err:#}");
|
||||
assert!(format!("{err:#}").starts_with("entity: "), "{err:#}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_error_from_outside_the_mint_has_no_step() {
|
||||
assert_eq!(failed_step(&anyhow::anyhow!("elsewhere")), None);
|
||||
}
|
||||
}
|
||||
741
swarm-controller/src/secrets/agent_renewal.rs
Normal file
741
swarm-controller/src/secrets/agent_renewal.rs
Normal file
|
|
@ -0,0 +1,741 @@
|
|||
//! Renewing each live agent's two store credentials by age: its mTLS
|
||||
//! certificate (`swarm/agents/<agent>/bao-mtls`) once it is past half its
|
||||
//! validity, and its queue secret (`swarm/agents/<agent>/queue`) once it is
|
||||
//! [`SECRET_RENEW_AFTER`] old.
|
||||
//!
|
||||
//! The certificate's age is its own `notBefore`/`notAfter`. The queue secret
|
||||
//! has no expiry and `swarm-nats-auth` checks nothing about time, so its age is
|
||||
//! the controller's own record, [`queue::AgentCredential::minted_at`]; a secret
|
||||
//! without one is stamped, value unchanged ([`SecretStep::Backfill`]).
|
||||
//!
|
||||
//! A running agent re-reads its certificate every ten minutes under the one it
|
||||
//! holds (`nix/agent-modules/bao.nix`); the old one stays valid until it
|
||||
//! expires. The old queue secret stops working at once, but the queue checks it
|
||||
//! only at `CONNECT`, so an open connection is unaffected. The agent reads its
|
||||
//! secret from the store on every connection attempt after its first
|
||||
//! (`hive-agent/src/swarm_queue.rs`), so a reconnect presents the new one.
|
||||
//!
|
||||
//! [`spawn`]'s pass, once the queue is up and every [`RECONCILE_INTERVAL`],
|
||||
//! inserts a job per agent with anything due: `MintAgentIdentity` for the
|
||||
//! certificate ([`crate::agent_identity::mint_and_verify`], which keeps the
|
||||
//! queue secret as it is) and `RenewAgentQueueCredential` ([`renew`]) for the
|
||||
//! secret, the second after the first when both are due. The decisions are
|
||||
//! pure ([`live_agents`], [`cert_is_due`], [`secret_step`], [`plan`]) so the
|
||||
//! tests pin them; the IO on either side only reads or acts.
|
||||
//!
|
||||
//! **Only agents some hive is declared to run are renewed** ([`live_agents`]):
|
||||
//! a destroy is recorded in the wanted-state declarations, and an agent declared
|
||||
//! nowhere, or only as `Destroyed`, is skipped. A live agent with no stored
|
||||
//! certificate, or a current one with no listed cert-auth role, gets one minted
|
||||
//! unless its mint is in flight. A missing queue secret stays missing.
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
use std::sync::Arc;
|
||||
|
||||
use anyhow::{Context, Result, bail};
|
||||
use swarm_secret_client::{SecretStore, cert, client::DEFAULT_CERT_MOUNT, mtls, policy, queue};
|
||||
use swarm_wire::wanted::{AgentState, HiveWanted};
|
||||
|
||||
use crate::wanted::WantedWriter;
|
||||
|
||||
/// Age at which a queue secret is re-minted. Independent of the agent
|
||||
/// certificate's life (`agentPkiLeafTtl` in `swarm-bao.nix`), which renews at
|
||||
/// half its own validity.
|
||||
pub const SECRET_RENEW_AFTER: std::time::Duration = std::time::Duration::from_hours(45 * 24);
|
||||
|
||||
/// How often [`spawn`] re-checks every agent. Also the longest it waits for
|
||||
/// the queue connection before its first pass.
|
||||
const RECONCILE_INTERVAL: std::time::Duration = std::time::Duration::from_mins(5);
|
||||
|
||||
/// How often [`spawn`] checks the queue connection before its first pass.
|
||||
const CONNECT_POLL: std::time::Duration = std::time::Duration::from_secs(5);
|
||||
|
||||
/// Now, in the unix seconds [`queue::AgentCredential::minted_at`] holds.
|
||||
pub fn unix_now() -> i64 {
|
||||
std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.map_or(0, |d| i64::try_from(d.as_secs()).unwrap_or(i64::MAX))
|
||||
}
|
||||
|
||||
/// What a stored queue secret needs at `now`.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum SecretStep {
|
||||
/// Younger than [`SECRET_RENEW_AFTER`].
|
||||
Keep,
|
||||
/// No mint time recorded: stamp `now` beside the unchanged value, so its
|
||||
/// clock starts here and no holder of it is cut off.
|
||||
Backfill,
|
||||
/// At least [`SECRET_RENEW_AFTER`] old: replace the value.
|
||||
Remint,
|
||||
}
|
||||
|
||||
/// Decide [`SecretStep`] for `stored` at `now`.
|
||||
pub fn secret_step(stored: &queue::AgentCredential, now: i64) -> SecretStep {
|
||||
let renew_after = i64::try_from(SECRET_RENEW_AFTER.as_secs()).unwrap_or(i64::MAX);
|
||||
match stored.minted_at {
|
||||
None => SecretStep::Backfill,
|
||||
Some(at) if now.saturating_sub(at) >= renew_after => SecretStep::Remint,
|
||||
Some(_) => SecretStep::Keep,
|
||||
}
|
||||
}
|
||||
|
||||
/// The object `step` writes for `agent` at `now`, or `None` for
|
||||
/// [`SecretStep::Keep`].
|
||||
///
|
||||
/// # Errors
|
||||
/// When a re-mint cannot draw randomness from the kernel.
|
||||
pub fn apply_secret_step(
|
||||
step: SecretStep,
|
||||
stored: &queue::AgentCredential,
|
||||
agent: &str,
|
||||
now: i64,
|
||||
) -> Result<Option<queue::AgentCredential>> {
|
||||
Ok(match step {
|
||||
SecretStep::Keep => None,
|
||||
SecretStep::Backfill => Some(queue::AgentCredential {
|
||||
minted_at: Some(now),
|
||||
..stored.clone()
|
||||
}),
|
||||
SecretStep::Remint => Some(fresh(agent, now)?),
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether a certificate valid from `not_before` to `not_after` is past half
|
||||
/// its life at `now`.
|
||||
pub fn cert_is_due(not_before: i64, not_after: i64, now: i64) -> bool {
|
||||
let half = not_after.saturating_sub(not_before) / 2;
|
||||
now >= not_before.saturating_add(half)
|
||||
}
|
||||
|
||||
/// A new queue credential for `agent`, minted at `now`. Shared with agent
|
||||
/// creation, so every secret this daemon writes carries a mint time.
|
||||
///
|
||||
/// # Errors
|
||||
/// When the kernel will not supply randomness.
|
||||
pub fn fresh(agent: &str, now: i64) -> Result<queue::AgentCredential> {
|
||||
Ok(queue::AgentCredential {
|
||||
value: crate::agent_identity::generate_queue_secret()?,
|
||||
agent: agent.to_owned(),
|
||||
minted_at: Some(now),
|
||||
})
|
||||
}
|
||||
|
||||
/// Every agent declared on at least one hive in a state other than
|
||||
/// `Destroyed`.
|
||||
pub fn live_agents(declarations: &[HiveWanted]) -> BTreeSet<String> {
|
||||
declarations
|
||||
.iter()
|
||||
.flat_map(|d| &d.agents)
|
||||
.filter(|(_, wanted)| wanted.state != AgentState::Destroyed)
|
||||
.map(|(agent, _)| agent.clone())
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// What one pass found for one credential of one live agent.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Observed {
|
||||
/// Stored and due for replacement, with its age in seconds.
|
||||
Due(i64),
|
||||
/// A queue secret stored with no mint time: due for
|
||||
/// [`SecretStep::Backfill`], never for a new value.
|
||||
Unstamped,
|
||||
/// Stored and not yet due.
|
||||
Current,
|
||||
/// Nothing stored (a certificate: or stored with no cert-auth role, see
|
||||
/// [`cert_needing_role`]). A certificate is minted for a live agent; a queue
|
||||
/// secret is left alone (see the module doc).
|
||||
Absent,
|
||||
/// The read or the decode failed. Nothing is known, so nothing is done.
|
||||
Unknown,
|
||||
}
|
||||
|
||||
/// What one pass found for one live agent.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct AgentObserved {
|
||||
pub cert: Observed,
|
||||
pub secret: Observed,
|
||||
}
|
||||
|
||||
/// One agent's share of a pass: which of its credentials to renew.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Renewal {
|
||||
pub agent: String,
|
||||
pub cert: bool,
|
||||
pub secret: bool,
|
||||
}
|
||||
|
||||
/// The renewals a pass queues: one per agent with a certificate that is
|
||||
/// [`Observed::Due`] or [`Observed::Absent`], or a queue secret that is
|
||||
/// [`Observed::Due`] or [`Observed::Unstamped`].
|
||||
pub fn plan(observed: &[(String, AgentObserved)]) -> Vec<Renewal> {
|
||||
observed
|
||||
.iter()
|
||||
.map(|(agent, o)| Renewal {
|
||||
agent: agent.clone(),
|
||||
cert: matches!(o.cert, Observed::Due(_) | Observed::Absent),
|
||||
secret: matches!(o.secret, Observed::Due(_) | Observed::Unstamped),
|
||||
})
|
||||
.filter(|r| r.cert || r.secret)
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// An age in seconds, for a log line: whole days.
|
||||
struct Age(i64);
|
||||
|
||||
impl std::fmt::Display for Age {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(f, "{}d", self.0 / 86_400)
|
||||
}
|
||||
}
|
||||
|
||||
/// Backfill or re-mint `agent`'s queue secret if it is still stored and still
|
||||
/// needs it ([`secret_step`]). The whole job of the `RenewAgentQueueCredential`
|
||||
/// node.
|
||||
///
|
||||
/// Re-decides rather than trusting the pass that queued it, so a node queued
|
||||
/// twice acts once. Reads the write back before reporting success.
|
||||
///
|
||||
/// # Errors
|
||||
/// When the store refuses a step, or returns a different object than the one
|
||||
/// just written.
|
||||
pub async fn renew(agent: &str) -> Result<()> {
|
||||
let path = queue::agent_queue_path(agent)?;
|
||||
let store = crate::store::connect()
|
||||
.await
|
||||
.context("logging in to the swarm secret store")?;
|
||||
let Some(stored) = store
|
||||
.read_optional::<queue::AgentCredential>(&path)
|
||||
.await
|
||||
.with_context(|| format!("reading {path}"))?
|
||||
else {
|
||||
tracing::info!(agent, %path, "agent queue credential: nothing stored, nothing to renew");
|
||||
return Ok(());
|
||||
};
|
||||
let now = unix_now();
|
||||
let step = secret_step(&stored, now);
|
||||
let Some(written) = apply_secret_step(step, &stored, agent, now)? else {
|
||||
tracing::debug!(agent, "agent queue credential is current; left as it is");
|
||||
return Ok(());
|
||||
};
|
||||
store
|
||||
.write(&path, &written)
|
||||
.await
|
||||
.with_context(|| format!("writing the agent queue credential at {path}"))?;
|
||||
let read_back: queue::AgentCredential = store
|
||||
.read(&path)
|
||||
.await
|
||||
.with_context(|| format!("reading {path} back"))?;
|
||||
if read_back != written {
|
||||
bail!("the store returned a different object at {path} than the one just written");
|
||||
}
|
||||
if let Some(at) = stored.minted_at {
|
||||
tracing::info!(
|
||||
agent,
|
||||
%path,
|
||||
old_age = %Age(now.saturating_sub(at)),
|
||||
"agent queue credential re-minted; the agent presents it from its next restart"
|
||||
);
|
||||
} else {
|
||||
tracing::info!(
|
||||
agent,
|
||||
%path,
|
||||
"agent queue credential had no mint time; stamped now, value unchanged"
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// What the store says about `agent`'s certificate.
|
||||
async fn observe_cert(store: &SecretStore, agent: &str, now: i64) -> Observed {
|
||||
let stored = match mtls::identity_path(agent) {
|
||||
Ok(path) => store.read_optional::<mtls::Credential>(&path).await,
|
||||
Err(e) => Err(e),
|
||||
};
|
||||
let credential = match stored {
|
||||
Ok(Some(credential)) => credential,
|
||||
Ok(None) => return Observed::Absent,
|
||||
Err(e) => {
|
||||
tracing::warn!(agent, error = %e, "agent certificate: store read failed");
|
||||
return Observed::Unknown;
|
||||
}
|
||||
};
|
||||
match cert::validity(&credential.cert) {
|
||||
Ok((not_before, not_after)) if cert_is_due(not_before, not_after, now) => {
|
||||
Observed::Due(now.saturating_sub(not_before))
|
||||
}
|
||||
Ok(_) => Observed::Current,
|
||||
Err(e) => {
|
||||
tracing::warn!(agent, error = %format!("{e:#}"), "agent certificate: unreadable");
|
||||
Observed::Unknown
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What the store says about `agent`'s queue secret.
|
||||
async fn observe_secret(store: &SecretStore, agent: &str, now: i64) -> Observed {
|
||||
let stored = match queue::agent_queue_path(agent) {
|
||||
Ok(path) => store.read_optional::<queue::AgentCredential>(&path).await,
|
||||
Err(e) => Err(e),
|
||||
};
|
||||
match stored {
|
||||
Ok(Some(stored)) => match (secret_step(&stored, now), stored.minted_at) {
|
||||
(SecretStep::Remint, Some(at)) => Observed::Due(now.saturating_sub(at)),
|
||||
(SecretStep::Backfill, _) => Observed::Unstamped,
|
||||
_ => Observed::Current,
|
||||
},
|
||||
Ok(None) => Observed::Absent,
|
||||
Err(e) => {
|
||||
tracing::warn!(agent, error = %e, "agent queue credential: store read failed");
|
||||
Observed::Unknown
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Every readable wanted-state declaration of `hives`. Fails as a whole when
|
||||
/// one cannot be read, since that hive may be the one declaring an agent
|
||||
/// destroyed.
|
||||
pub(crate) async fn read_declarations(
|
||||
wanted: &WantedWriter,
|
||||
hives: &[String],
|
||||
) -> Result<Vec<HiveWanted>> {
|
||||
let mut declarations = Vec::with_capacity(hives.len());
|
||||
for hive in hives {
|
||||
if let Some(d) = wanted
|
||||
.view(hive)
|
||||
.await
|
||||
.with_context(|| format!("reading {hive}'s wanted-state declaration"))?
|
||||
{
|
||||
declarations.push(d);
|
||||
}
|
||||
}
|
||||
Ok(declarations)
|
||||
}
|
||||
|
||||
/// A stored, current certificate whose cert-auth role is not in `roles` is as
|
||||
/// good as absent: the agent cannot log in with it, and the mint is the only
|
||||
/// thing that writes the role. `None` (the role listing failed) and every
|
||||
/// other observation come back unchanged.
|
||||
pub fn cert_needing_role(
|
||||
cert: Observed,
|
||||
roles: Option<&BTreeSet<String>>,
|
||||
agent: &str,
|
||||
) -> Observed {
|
||||
match (cert, roles) {
|
||||
(Observed::Current, Some(roles)) if !roles.contains(agent) => Observed::Absent,
|
||||
_ => cert,
|
||||
}
|
||||
}
|
||||
|
||||
/// One pass: every live agent, observed. Fails as a whole when any hive's
|
||||
/// declaration cannot be read.
|
||||
async fn observe_all(
|
||||
wanted: &WantedWriter,
|
||||
hives: &[String],
|
||||
) -> Result<Vec<(String, AgentObserved)>> {
|
||||
let declarations = read_declarations(wanted, hives).await?;
|
||||
let store = crate::store::connect()
|
||||
.await
|
||||
.context("logging in to the swarm secret store")?;
|
||||
let now = unix_now();
|
||||
let roles = match store.list_cert_roles(DEFAULT_CERT_MOUNT).await {
|
||||
Ok(names) => Some(
|
||||
policy::agents_from_role_names(&names)
|
||||
.into_iter()
|
||||
.collect::<BTreeSet<_>>(),
|
||||
),
|
||||
Err(e) => {
|
||||
tracing::warn!(error = %e, "agent certificate: listing the cert-auth roles failed");
|
||||
None
|
||||
}
|
||||
};
|
||||
// Destroyed agents that still have a role are cut off here, each pass until
|
||||
// it succeeds.
|
||||
if let Some(with_role) = &roles {
|
||||
crate::agent_cutoff::cut_off_destroyed(&store, with_role, &declarations).await;
|
||||
}
|
||||
let mut observed = Vec::new();
|
||||
for agent in live_agents(&declarations) {
|
||||
let o = AgentObserved {
|
||||
cert: cert_needing_role(
|
||||
observe_cert(&store, &agent, now).await,
|
||||
roles.as_ref(),
|
||||
&agent,
|
||||
),
|
||||
secret: observe_secret(&store, &agent, now).await,
|
||||
};
|
||||
if let Observed::Due(age) = o.cert {
|
||||
tracing::info!(agent, age = %Age(age), "agent certificate past half its life; re-issuing");
|
||||
}
|
||||
if o.cert == Observed::Absent {
|
||||
tracing::info!(
|
||||
agent,
|
||||
"agent has no usable certificate (none stored, or no cert-auth role); minting its store identity"
|
||||
);
|
||||
}
|
||||
if let Observed::Due(age) = o.secret {
|
||||
tracing::info!(agent, age = %Age(age), "agent queue credential due; re-minting");
|
||||
}
|
||||
if o.secret == Observed::Unstamped {
|
||||
tracing::info!(
|
||||
agent,
|
||||
"agent queue credential has no mint time; stamping it"
|
||||
);
|
||||
}
|
||||
observed.push((agent, o));
|
||||
}
|
||||
Ok(observed)
|
||||
}
|
||||
|
||||
/// Wait until `connected` holds, checking every [`CONNECT_POLL`] for at most
|
||||
/// `bound`. Returns whether it held.
|
||||
pub(crate) async fn wait_for_queue(
|
||||
connected: impl Fn() -> bool,
|
||||
bound: std::time::Duration,
|
||||
) -> bool {
|
||||
let deadline = tokio::time::Instant::now() + bound;
|
||||
loop {
|
||||
if connected() {
|
||||
return true;
|
||||
}
|
||||
if tokio::time::Instant::now() >= deadline {
|
||||
return false;
|
||||
}
|
||||
tokio::time::sleep(CONNECT_POLL).await;
|
||||
}
|
||||
}
|
||||
|
||||
/// [`spawn`]'s loop, with the connection check and the pass handed in.
|
||||
async fn run<P, F>(connected: impl Fn() -> bool, mut pass: P, enqueue: impl Fn(Vec<Renewal>))
|
||||
where
|
||||
P: FnMut() -> F,
|
||||
F: std::future::Future<Output = Result<Vec<(String, AgentObserved)>>>,
|
||||
{
|
||||
if !wait_for_queue(connected, RECONCILE_INTERVAL).await {
|
||||
tracing::warn!(
|
||||
waited_s = RECONCILE_INTERVAL.as_secs(),
|
||||
"agent credential renewal: queue still not connected; running the first pass anyway"
|
||||
);
|
||||
}
|
||||
let mut ticker = tokio::time::interval(RECONCILE_INTERVAL);
|
||||
loop {
|
||||
ticker.tick().await;
|
||||
match pass().await {
|
||||
Ok(observed) => {
|
||||
let renewals = plan(&observed);
|
||||
if renewals.is_empty() {
|
||||
tracing::debug!(
|
||||
checked = observed.len(),
|
||||
"agent credential renewal: none due"
|
||||
);
|
||||
} else {
|
||||
tracing::info!(
|
||||
checked = observed.len(),
|
||||
renewing = renewals.len(),
|
||||
"agent credential renewal: queueing"
|
||||
);
|
||||
enqueue(renewals);
|
||||
}
|
||||
}
|
||||
Err(e) => tracing::warn!(
|
||||
error = %format!("{e:#}"),
|
||||
retry_in_s = RECONCILE_INTERVAL.as_secs(),
|
||||
"agent credential renewal: pass failed; retrying next tick"
|
||||
),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Check every live agent once the queue is connected and every
|
||||
/// [`RECONCILE_INTERVAL`] after, and hand the renewals due to `enqueue`, which
|
||||
/// inserts a job for each.
|
||||
///
|
||||
/// Only the first pass waits for the connection, and for at most one
|
||||
/// [`RECONCILE_INTERVAL`]. A pass that fails is logged and retried on the next
|
||||
/// tick; it never stops the daemon.
|
||||
pub fn spawn(
|
||||
wanted: Arc<WantedWriter>,
|
||||
hives: Vec<String>,
|
||||
enqueue: impl Fn(Vec<Renewal>) + Send + 'static,
|
||||
) {
|
||||
tokio::spawn(async move {
|
||||
run(
|
||||
|| wanted.is_connected(),
|
||||
|| observe_all(&wanted, &hives),
|
||||
enqueue,
|
||||
)
|
||||
.await;
|
||||
});
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use swarm_wire::wanted::AgentWanted;
|
||||
|
||||
const NOW: i64 = 1_790_000_000;
|
||||
const DAY: i64 = 86_400;
|
||||
|
||||
/// A 90-day window, 2026-01-01T00:00:00Z to 2026-04-01T00:00:00Z.
|
||||
const CERT_NOT_BEFORE: i64 = 1_767_225_600;
|
||||
const CERT_NOT_AFTER: i64 = 1_775_001_600;
|
||||
|
||||
fn minted(at: Option<i64>) -> queue::AgentCredential {
|
||||
queue::AgentCredential {
|
||||
value: "Ab9_-zSECRET".to_owned(),
|
||||
agent: "atlas".to_owned(),
|
||||
minted_at: at,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_secret_without_a_mint_time_is_backfilled_with_its_value_unchanged() {
|
||||
let stored = minted(None);
|
||||
assert_eq!(secret_step(&stored, NOW), SecretStep::Backfill);
|
||||
let written = apply_secret_step(SecretStep::Backfill, &stored, "atlas", NOW)
|
||||
.expect("no randomness needed")
|
||||
.expect("a backfill writes");
|
||||
assert_eq!(written.value, stored.value, "no holder of it is cut off");
|
||||
assert_eq!(written.agent, stored.agent);
|
||||
assert_eq!(written.minted_at, Some(NOW), "its clock starts now");
|
||||
assert_eq!(secret_step(&written, NOW), SecretStep::Keep);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_secret_is_re_minted_from_forty_five_days_with_a_new_value_and_mint_time() {
|
||||
for age in [45 * DAY, 90 * DAY] {
|
||||
let stored = minted(Some(NOW - age));
|
||||
assert_eq!(secret_step(&stored, NOW), SecretStep::Remint, "{age}");
|
||||
let written = apply_secret_step(SecretStep::Remint, &stored, "atlas", NOW)
|
||||
.expect("the kernel supplies randomness")
|
||||
.expect("a re-mint writes");
|
||||
assert_ne!(written.value, stored.value);
|
||||
assert_eq!(written.minted_at, Some(NOW));
|
||||
assert_eq!(written.agent, "atlas");
|
||||
assert_eq!(secret_step(&written, NOW), SecretStep::Keep);
|
||||
}
|
||||
let a = fresh("atlas", NOW).expect("randomness");
|
||||
let b = fresh("atlas", NOW).expect("randomness");
|
||||
assert_ne!(a.value, b.value, "two re-mints must not agree");
|
||||
}
|
||||
|
||||
/// Includes a mint time ahead of the clock, which must not overflow into a
|
||||
/// large age.
|
||||
#[test]
|
||||
fn a_secret_younger_than_forty_five_days_is_left_alone() {
|
||||
for at in [NOW, NOW - 45 * DAY + 1, NOW + DAY] {
|
||||
let stored = minted(Some(at));
|
||||
assert_eq!(secret_step(&stored, NOW), SecretStep::Keep, "{at}");
|
||||
assert_eq!(
|
||||
apply_secret_step(SecretStep::Keep, &stored, "atlas", NOW).expect("no IO"),
|
||||
None
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_ninety_day_certificate_is_due_from_day_forty_five() {
|
||||
let (nb, na) = (CERT_NOT_BEFORE, CERT_NOT_AFTER);
|
||||
assert!(!cert_is_due(nb, na, nb));
|
||||
assert!(!cert_is_due(nb, na, nb + 45 * DAY - 1));
|
||||
assert!(cert_is_due(nb, na, nb + 45 * DAY));
|
||||
assert!(cert_is_due(nb, na, na + DAY), "an expired one too");
|
||||
}
|
||||
|
||||
fn declared(agents: &[(&str, AgentState)]) -> HiveWanted {
|
||||
let mut d = HiveWanted::default();
|
||||
for (agent, state) in agents {
|
||||
d.agents
|
||||
.insert((*agent).to_owned(), AgentWanted { state: *state });
|
||||
}
|
||||
d
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_destroyed_agent_is_not_live_and_every_other_state_is() {
|
||||
let live = live_agents(&[declared(&[
|
||||
("up", AgentState::Up),
|
||||
("offline", AgentState::Offline),
|
||||
("paused", AgentState::Paused),
|
||||
("gone", AgentState::Destroyed),
|
||||
])]);
|
||||
assert_eq!(
|
||||
live.into_iter().collect::<Vec<_>>(),
|
||||
["offline", "paused", "up"]
|
||||
);
|
||||
}
|
||||
|
||||
/// An agent destroyed on one hive and declared on another is live: it
|
||||
/// still runs somewhere.
|
||||
#[test]
|
||||
fn an_agent_live_on_any_hive_is_live() {
|
||||
let live = live_agents(&[
|
||||
declared(&[("atlas", AgentState::Destroyed)]),
|
||||
declared(&[("atlas", AgentState::Up)]),
|
||||
]);
|
||||
assert!(live.contains("atlas"), "{live:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_declaration_is_no_live_agent() {
|
||||
assert!(live_agents(&[]).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn due_and_missing_certificates_and_due_secrets_are_planned() {
|
||||
use Observed::{Absent, Current, Due, Unknown, Unstamped};
|
||||
let o = |cert, secret| AgentObserved { cert, secret };
|
||||
let observed = [
|
||||
("both".to_owned(), o(Due(46 * DAY), Due(45 * DAY))),
|
||||
("cert".to_owned(), o(Due(46 * DAY), Current)),
|
||||
("secret".to_owned(), o(Current, Due(45 * DAY))),
|
||||
("unstamped".to_owned(), o(Current, Unstamped)),
|
||||
("neither".to_owned(), o(Current, Absent)),
|
||||
("unknown".to_owned(), o(Unknown, Unknown)),
|
||||
("no identity".to_owned(), o(Absent, Absent)),
|
||||
("no cert, old secret".to_owned(), o(Absent, Due(45 * DAY))),
|
||||
("unreadable cert".to_owned(), o(Unknown, Absent)),
|
||||
];
|
||||
let r = |agent: &str, cert, secret| Renewal {
|
||||
agent: agent.to_owned(),
|
||||
cert,
|
||||
secret,
|
||||
};
|
||||
assert_eq!(
|
||||
plan(&observed),
|
||||
[
|
||||
r("both", true, true),
|
||||
r("cert", true, false),
|
||||
r("secret", false, true),
|
||||
r("unstamped", false, true),
|
||||
r("no identity", true, false),
|
||||
r("no cert, old secret", true, true),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
/// A pass over declarations: the agent with no stored identity is minted
|
||||
/// for when it is live and not when it is destroyed. The destroyed agent is
|
||||
/// never observed, which is what [`live_agents`] does before the store is
|
||||
/// read.
|
||||
#[test]
|
||||
fn a_missing_identity_is_minted_for_a_live_agent_and_not_a_destroyed_one() {
|
||||
let declarations = [declared(&[
|
||||
("sock", AgentState::Up),
|
||||
("paused", AgentState::Paused),
|
||||
("gone", AgentState::Destroyed),
|
||||
])];
|
||||
let nothing_stored = AgentObserved {
|
||||
cert: Observed::Absent,
|
||||
secret: Observed::Absent,
|
||||
};
|
||||
let observed: Vec<_> = live_agents(&declarations)
|
||||
.into_iter()
|
||||
.map(|agent| (agent, nothing_stored))
|
||||
.collect();
|
||||
let planned: Vec<_> = plan(&observed)
|
||||
.into_iter()
|
||||
.map(|r| (r.agent, r.cert, r.secret))
|
||||
.collect();
|
||||
assert_eq!(
|
||||
planned,
|
||||
[
|
||||
("paused".to_owned(), true, false),
|
||||
("sock".to_owned(), true, false)
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
/// A current certificate with no cert-auth role listed is minted for; the
|
||||
/// controls are the same certificate with its role listed, a failed role
|
||||
/// listing, and a certificate that is not `Current` anyway.
|
||||
#[test]
|
||||
fn a_current_certificate_without_its_role_is_minted_for() {
|
||||
let roles: BTreeSet<String> = ["sock".to_owned()].into();
|
||||
let planned = |cert: Observed, roles: Option<&BTreeSet<String>>, agent: &str| {
|
||||
let observed = [(
|
||||
agent.to_owned(),
|
||||
AgentObserved {
|
||||
cert: cert_needing_role(cert, roles, agent),
|
||||
secret: Observed::Current,
|
||||
},
|
||||
)];
|
||||
plan(&observed).iter().map(|r| r.cert).collect::<Vec<_>>()
|
||||
};
|
||||
assert_eq!(planned(Observed::Current, Some(&roles), "paused"), [true]);
|
||||
assert_eq!(
|
||||
planned(Observed::Current, Some(&roles), "sock"),
|
||||
[] as [bool; 0]
|
||||
);
|
||||
assert_eq!(planned(Observed::Current, None, "paused"), [] as [bool; 0]);
|
||||
assert_eq!(
|
||||
planned(Observed::Unknown, Some(&roles), "paused"),
|
||||
[] as [bool; 0]
|
||||
);
|
||||
assert_eq!(planned(Observed::Due(1), Some(&roles), "sock"), [true]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_age_logged_is_whole_days() {
|
||||
assert_eq!(Age(46 * DAY + 5).to_string(), "46d");
|
||||
}
|
||||
|
||||
/// [`run`] over a connection the test flips and a pass that only counts
|
||||
/// itself.
|
||||
fn counting_run() -> (
|
||||
Arc<std::sync::atomic::AtomicBool>,
|
||||
Arc<std::sync::atomic::AtomicUsize>,
|
||||
tokio::task::JoinHandle<()>,
|
||||
) {
|
||||
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
|
||||
let connected = Arc::new(AtomicBool::new(false));
|
||||
let passes = Arc::new(AtomicUsize::new(0));
|
||||
let (c, p) = (Arc::clone(&connected), Arc::clone(&passes));
|
||||
let task = tokio::spawn(run(
|
||||
move || c.load(Ordering::SeqCst),
|
||||
move || {
|
||||
p.fetch_add(1, Ordering::SeqCst);
|
||||
std::future::ready(Ok(Vec::new()))
|
||||
},
|
||||
|_| {},
|
||||
));
|
||||
(connected, passes, task)
|
||||
}
|
||||
|
||||
/// The sleeps end between [`CONNECT_POLL`] boundaries, so a check and an
|
||||
/// assertion never fall on the same instant.
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn the_first_pass_waits_for_the_queue_and_later_passes_do_not() {
|
||||
use std::sync::atomic::Ordering;
|
||||
let (connected, passes, task) = counting_run();
|
||||
|
||||
tokio::time::sleep(std::time::Duration::from_secs(62)).await;
|
||||
assert_eq!(passes.load(Ordering::SeqCst), 0, "no pass while Pending");
|
||||
|
||||
connected.store(true, Ordering::SeqCst);
|
||||
tokio::time::sleep(CONNECT_POLL).await;
|
||||
assert_eq!(passes.load(Ordering::SeqCst), 1, "a pass once connected");
|
||||
|
||||
connected.store(false, Ordering::SeqCst);
|
||||
tokio::time::sleep(RECONCILE_INTERVAL).await;
|
||||
assert_eq!(
|
||||
passes.load(Ordering::SeqCst),
|
||||
2,
|
||||
"a later disconnect does not hold back the next pass"
|
||||
);
|
||||
task.abort();
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn a_queue_that_never_connects_gets_a_pass_after_one_interval() {
|
||||
use std::sync::atomic::Ordering;
|
||||
let (_connected, passes, task) = counting_run();
|
||||
|
||||
tokio::time::sleep(RECONCILE_INTERVAL.saturating_sub(std::time::Duration::from_secs(2)))
|
||||
.await;
|
||||
assert_eq!(passes.load(Ordering::SeqCst), 0);
|
||||
|
||||
tokio::time::sleep(std::time::Duration::from_secs(4)).await;
|
||||
assert_eq!(passes.load(Ordering::SeqCst), 1);
|
||||
task.abort();
|
||||
}
|
||||
}
|
||||
233
swarm-controller/src/secrets/agent_role_ttl.rs
Normal file
233
swarm-controller/src/secrets/agent_role_ttl.rs
Normal file
|
|
@ -0,0 +1,233 @@
|
|||
//! The token lifetime of the agents' cert-auth roles that already exist.
|
||||
//!
|
||||
//! A role is written with its lifetimes only when an agent's certificate is
|
||||
//! minted or renewed, and a role written before the lifetimes were set leaves
|
||||
//! every login at the mount's default of 32 days, one store lease each. The
|
||||
//! start pass in [`crate::read_policy`] calls [`bring_current`] so those roles
|
||||
//! take [`swarm_secret_client::client::CERT_ROLE_TOKEN_TTL`] without waiting for
|
||||
//! a renewal.
|
||||
//!
|
||||
//! Only the two lifetimes are written: the role's certificate, allowed names
|
||||
//! and policies stay as they are, and no token or lease is revoked. Tokens
|
||||
//! issued before expire on their own.
|
||||
|
||||
use swarm_secret_client::{client::DEFAULT_CERT_MOUNT, policy};
|
||||
|
||||
use crate::store::AccessStore;
|
||||
|
||||
/// What one pass did, one count per role.
|
||||
#[derive(Debug, Default, PartialEq, Eq)]
|
||||
pub struct Counts {
|
||||
pub rewritten: usize,
|
||||
pub already_current: usize,
|
||||
pub failed: usize,
|
||||
}
|
||||
|
||||
/// Give every agent role among `roles`, a listing of the cert mount's roles,
|
||||
/// the current token lifetimes, and log the counts once.
|
||||
///
|
||||
/// A role that cannot be read or written is named in a warning and skipped, so
|
||||
/// it never stops the rest or the start. A role gone since the listing is
|
||||
/// counted nowhere: there is nothing left to bring current.
|
||||
pub async fn bring_current(store: &impl AccessStore, roles: &[String]) -> Counts {
|
||||
let mut counts = Counts::default();
|
||||
for agent in policy::agents_from_role_names(roles) {
|
||||
let Ok(role) = policy::agent_object_name(&agent) else {
|
||||
continue;
|
||||
};
|
||||
match bring_one(store, &role).await {
|
||||
Ok(Outcome::Rewritten) => counts.rewritten += 1,
|
||||
Ok(Outcome::AlreadyCurrent) => counts.already_current += 1,
|
||||
Ok(Outcome::Gone) => {}
|
||||
Err(e) => {
|
||||
counts.failed += 1;
|
||||
tracing::warn!(role, error = %e, "this agent role's token lifetime could not be brought current");
|
||||
}
|
||||
}
|
||||
}
|
||||
tracing::info!(
|
||||
rewritten = counts.rewritten,
|
||||
already_current = counts.already_current,
|
||||
failed = counts.failed,
|
||||
"agent role token lifetimes checked"
|
||||
);
|
||||
counts
|
||||
}
|
||||
|
||||
enum Outcome {
|
||||
Rewritten,
|
||||
AlreadyCurrent,
|
||||
Gone,
|
||||
}
|
||||
|
||||
async fn bring_one(
|
||||
store: &impl AccessStore,
|
||||
role: &str,
|
||||
) -> Result<Outcome, swarm_secret_client::Error> {
|
||||
let Some(ttls) = store.cert_role_token_ttls(DEFAULT_CERT_MOUNT, role).await? else {
|
||||
return Ok(Outcome::Gone);
|
||||
};
|
||||
if ttls.is_current() {
|
||||
return Ok(Outcome::AlreadyCurrent);
|
||||
}
|
||||
store
|
||||
.set_cert_role_token_ttls(DEFAULT_CERT_MOUNT, role)
|
||||
.await?;
|
||||
Ok(Outcome::Rewritten)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use swarm_secret_client::client::{CERT_ROLE_TOKEN_TTL_SECS, CertRoleTokenTtls};
|
||||
|
||||
use crate::store::fake::{FakeAccess, FakeRole};
|
||||
|
||||
use super::{Counts, bring_current};
|
||||
|
||||
const CURRENT: CertRoleTokenTtls = CertRoleTokenTtls {
|
||||
token_ttl: CERT_ROLE_TOKEN_TTL_SECS,
|
||||
token_max_ttl: CERT_ROLE_TOKEN_TTL_SECS,
|
||||
};
|
||||
const STALE: CertRoleTokenTtls = CertRoleTokenTtls {
|
||||
token_ttl: 0,
|
||||
token_max_ttl: 0,
|
||||
};
|
||||
|
||||
fn role(agent: &str, ttls: CertRoleTokenTtls) -> FakeRole {
|
||||
FakeRole {
|
||||
certificate: format!("CA-{agent}"),
|
||||
common_name: format!("hive-agent-{agent}"),
|
||||
policies: vec!["hive-agent".to_owned()],
|
||||
ttls,
|
||||
}
|
||||
}
|
||||
|
||||
fn listing(agents: &[&str]) -> Vec<String> {
|
||||
agents.iter().map(|a| format!("hive-agent-{a}")).collect()
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_stale_role_takes_the_ttl_and_keeps_its_certificate_names_and_policies() {
|
||||
let before = role("a", STALE);
|
||||
let store = FakeAccess::default().with_role("hive-agent-a", before.clone());
|
||||
let counts = bring_current(&store, &listing(&["a"])).await;
|
||||
assert_eq!(
|
||||
counts,
|
||||
Counts {
|
||||
rewritten: 1,
|
||||
..Counts::default()
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
store.role("hive-agent-a"),
|
||||
Some(FakeRole {
|
||||
ttls: CURRENT,
|
||||
..before
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_role_with_a_lifetime_unset_or_different_is_rewritten() {
|
||||
let store = FakeAccess::default()
|
||||
.with_role(
|
||||
"hive-agent-a",
|
||||
role(
|
||||
"a",
|
||||
CertRoleTokenTtls {
|
||||
token_ttl: CERT_ROLE_TOKEN_TTL_SECS,
|
||||
token_max_ttl: 0,
|
||||
},
|
||||
),
|
||||
)
|
||||
.with_role(
|
||||
"hive-agent-b",
|
||||
role(
|
||||
"b",
|
||||
CertRoleTokenTtls {
|
||||
token_ttl: 900,
|
||||
token_max_ttl: 900,
|
||||
},
|
||||
),
|
||||
);
|
||||
let counts = bring_current(&store, &listing(&["a", "b"])).await;
|
||||
assert_eq!(counts.rewritten, 2);
|
||||
assert_eq!(store.role("hive-agent-a").expect("kept").ttls, CURRENT);
|
||||
assert_eq!(store.role("hive-agent-b").expect("kept").ttls, CURRENT);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_current_role_is_read_and_not_written() {
|
||||
let store = FakeAccess::default().with_role("hive-agent-a", role("a", CURRENT));
|
||||
let counts = bring_current(&store, &listing(&["a"])).await;
|
||||
assert_eq!(
|
||||
counts,
|
||||
Counts {
|
||||
already_current: 1,
|
||||
..Counts::default()
|
||||
}
|
||||
);
|
||||
assert_eq!(store.calls(), ["cert_role_token_ttls hive-agent-a"]);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_role_that_fails_does_not_stop_the_others() {
|
||||
let store = FakeAccess::default()
|
||||
.with_role("hive-agent-a", role("a", STALE))
|
||||
.with_role("hive-agent-b", role("b", STALE))
|
||||
.with_role("hive-agent-c", role("c", STALE))
|
||||
.with_role("hive-agent-d", role("d", CURRENT))
|
||||
.with_unreadable_role("hive-agent-a")
|
||||
.with_unwritable_role("hive-agent-b");
|
||||
let counts = bring_current(&store, &listing(&["a", "b", "c", "d"])).await;
|
||||
assert_eq!(
|
||||
counts,
|
||||
Counts {
|
||||
rewritten: 1,
|
||||
already_current: 1,
|
||||
failed: 2,
|
||||
}
|
||||
);
|
||||
// The ones after the failures were still handled.
|
||||
assert_eq!(store.role("hive-agent-c").expect("kept").ttls, CURRENT);
|
||||
// The failed ones were left as they were.
|
||||
assert_eq!(store.role("hive-agent-a").expect("kept").ttls, STALE);
|
||||
assert_eq!(store.role("hive-agent-b").expect("kept").ttls, STALE);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn only_agent_roles_are_touched() {
|
||||
let store = FakeAccess::default()
|
||||
.with_role("hive-agent-a", role("a", STALE))
|
||||
.with_role("hive-pr1ma", role("pr1ma", STALE))
|
||||
.with_role("swarm-controller", role("c", STALE));
|
||||
let roles = vec![
|
||||
"hive-agent-a".to_owned(),
|
||||
"hive-pr1ma".to_owned(),
|
||||
"swarm-controller".to_owned(),
|
||||
];
|
||||
let counts = bring_current(&store, &roles).await;
|
||||
assert_eq!(counts.rewritten, 1);
|
||||
assert_eq!(store.role("hive-agent-a").expect("kept").ttls, CURRENT);
|
||||
assert_eq!(store.role("hive-pr1ma").expect("kept").ttls, STALE);
|
||||
assert_eq!(store.role("swarm-controller").expect("kept").ttls, STALE);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_role_gone_since_the_listing_is_counted_nowhere() {
|
||||
let store = FakeAccess::default().with_role("hive-agent-b", role("b", STALE));
|
||||
let counts = bring_current(&store, &listing(&["a", "b"])).await;
|
||||
assert_eq!(
|
||||
counts,
|
||||
Counts {
|
||||
rewritten: 1,
|
||||
..Counts::default()
|
||||
}
|
||||
);
|
||||
assert!(
|
||||
!store
|
||||
.calls()
|
||||
.contains(&"set_cert_role_token_ttls hive-agent-a".to_owned())
|
||||
);
|
||||
}
|
||||
}
|
||||
682
swarm-controller/src/secrets/archive_access.rs
Normal file
682
swarm-controller/src/secrets/archive_access.rs
Normal file
|
|
@ -0,0 +1,682 @@
|
|||
//! Each placed agent's archive credentials, and their revocation.
|
||||
//!
|
||||
//! The archive (`swarm-archive.nix`) keeps one restic repository per agent and
|
||||
//! lets a user reach only its own. Every [`RECONCILE_INTERVAL`] this makes the
|
||||
//! store hold, per `(hive, agent)` that [`crate::jobq::placements`] reports:
|
||||
//!
|
||||
//! - the REST password and the restic password at
|
||||
//! [`archive::grant_path`], which that hive's store identity reads;
|
||||
//! - the htpasswd line, a hash of the REST password, at [`archive::user_path`],
|
||||
//! which the archive host renders its users file from;
|
||||
//! - the restic password at [`archive::restic_path`], created once and never
|
||||
//! replaced: it opens the agent's repository wherever the agent runs, and the
|
||||
//! archive host prunes with it.
|
||||
//!
|
||||
//! A pass is level-triggered and idempotent. A move to another hive mints a new
|
||||
//! REST password, which replaces the htpasswd line, so the old hive's password
|
||||
//! stops working once the archive host re-renders; the old hive's copy is
|
||||
//! deleted in the same pass. An agent no hive places loses its htpasswd line and
|
||||
//! every hive's copy. Its restic password stays, so what was backed up can still
|
||||
//! be read.
|
||||
//!
|
||||
//! An agent that two hives place is left as it is: either grant would replace
|
||||
//! the other's every pass.
|
||||
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
use base64::Engine as _;
|
||||
use sha1::{Digest as _, Sha1};
|
||||
use swarm_secret_client::SecretStore;
|
||||
use swarm_secret_client::archive::{self, HTPASSWD, PASSWORD, REST_PASSWORD, RESTIC_PASSWORD};
|
||||
|
||||
use crate::wanted::WantedWriter;
|
||||
|
||||
/// How often [`spawn`] reconciles.
|
||||
const RECONCILE_INTERVAL: Duration = Duration::from_mins(5);
|
||||
|
||||
/// A pass that has not finished by now is given up on; the next tick retries.
|
||||
const PASS_DEADLINE: Duration = Duration::from_mins(2);
|
||||
|
||||
/// An object in the store: field name to value.
|
||||
type Fields = BTreeMap<String, String>;
|
||||
|
||||
/// The store calls a pass makes, so a test can stand in for the store.
|
||||
pub(crate) trait ArchiveStore {
|
||||
/// The object at `path`; `None` when nothing is stored there.
|
||||
async fn read(&self, path: &str) -> Result<Option<Fields>>;
|
||||
/// Store `fields` at `path`, replacing what is there.
|
||||
async fn write(&self, path: &str, fields: &Fields) -> Result<()>;
|
||||
/// Store `fields` at `path` only while nothing is there.
|
||||
async fn create(&self, path: &str, fields: &Fields) -> Result<()>;
|
||||
/// The names stored directly under `path`.
|
||||
async fn list(&self, path: &str) -> Result<Vec<String>>;
|
||||
/// Remove `path` with every version of it; nothing there is not an error.
|
||||
async fn delete(&self, path: &str) -> Result<()>;
|
||||
}
|
||||
|
||||
impl ArchiveStore for SecretStore {
|
||||
async fn read(&self, path: &str) -> Result<Option<Fields>> {
|
||||
Ok(self.read_optional(path).await?)
|
||||
}
|
||||
|
||||
async fn write(&self, path: &str, fields: &Fields) -> Result<()> {
|
||||
Ok(SecretStore::write(self, path, fields).await?)
|
||||
}
|
||||
|
||||
async fn create(&self, path: &str, fields: &Fields) -> Result<()> {
|
||||
Ok(SecretStore::create(self, path, fields).await?)
|
||||
}
|
||||
|
||||
async fn list(&self, path: &str) -> Result<Vec<String>> {
|
||||
Ok(SecretStore::list(self, path).await?)
|
||||
}
|
||||
|
||||
async fn delete(&self, path: &str) -> Result<()> {
|
||||
Ok(self.delete_all_versions(path).await?)
|
||||
}
|
||||
}
|
||||
|
||||
/// What one pass did.
|
||||
#[derive(Debug, Default, PartialEq, Eq)]
|
||||
pub(crate) struct Done {
|
||||
/// Agents whose credentials were written or replaced.
|
||||
pub granted: usize,
|
||||
/// Credentials removed: a hive's copy or an htpasswd line.
|
||||
pub revoked: usize,
|
||||
/// Agents or hives whose credentials could not all be checked or written.
|
||||
pub failed: usize,
|
||||
}
|
||||
|
||||
fn fields(pairs: &[(&str, &str)]) -> Fields {
|
||||
pairs
|
||||
.iter()
|
||||
.map(|(k, v)| ((*k).to_owned(), (*v).to_owned()))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The non-empty field `name` of `object`.
|
||||
fn field<'a>(object: Option<&'a Fields>, name: &str) -> Option<&'a str> {
|
||||
object
|
||||
.and_then(|o| o.get(name))
|
||||
.map(String::as_str)
|
||||
.filter(|v| !v.is_empty())
|
||||
}
|
||||
|
||||
/// The htpasswd line that accepts `password` for `agent`: apache's `{SHA}`
|
||||
/// form, which the password's 256 random bits make as strong as a slower hash.
|
||||
fn htpasswd_line(agent: &str, password: &str) -> String {
|
||||
let digest = Sha1::digest(password.as_bytes());
|
||||
format!(
|
||||
"{agent}:{{SHA}}{}",
|
||||
base64::engine::general_purpose::STANDARD.encode(digest)
|
||||
)
|
||||
}
|
||||
|
||||
/// `agent`'s restic password: the stored one, else a new one created at
|
||||
/// [`archive::restic_path`]. A create that fails is read back, in case another
|
||||
/// writer's landed first.
|
||||
async fn ensure_restic(store: &impl ArchiveStore, agent: &str) -> Result<String> {
|
||||
let path = archive::restic_path(agent)?;
|
||||
let stored = store
|
||||
.read(&path)
|
||||
.await
|
||||
.with_context(|| format!("reading {path}"))?;
|
||||
if let Some(password) = field(stored.as_ref(), PASSWORD) {
|
||||
return Ok(password.to_owned());
|
||||
}
|
||||
let minted = crate::agent_identity::generate_queue_secret()?;
|
||||
if let Err(e) = store.create(&path, &fields(&[(PASSWORD, &minted)])).await {
|
||||
let winner = store
|
||||
.read(&path)
|
||||
.await
|
||||
.with_context(|| format!("reading {path} back after a failed create"))?;
|
||||
return field(winner.as_ref(), PASSWORD)
|
||||
.map(str::to_owned)
|
||||
.ok_or_else(|| e.context(format!("creating {path}")));
|
||||
}
|
||||
Ok(minted)
|
||||
}
|
||||
|
||||
/// Bring `agent`'s credentials on `hive` and at the archive up to date; whether
|
||||
/// anything was written.
|
||||
async fn grant(store: &impl ArchiveStore, hive: &str, agent: &str) -> Result<bool> {
|
||||
let restic = ensure_restic(store, agent).await?;
|
||||
let grant_path = archive::grant_path(hive, agent)?;
|
||||
let held = store
|
||||
.read(&grant_path)
|
||||
.await
|
||||
.with_context(|| format!("reading {grant_path}"))?;
|
||||
|
||||
let mut written = false;
|
||||
let rest = match field(held.as_ref(), REST_PASSWORD) {
|
||||
Some(rest) if field(held.as_ref(), RESTIC_PASSWORD) == Some(restic.as_str()) => {
|
||||
rest.to_owned()
|
||||
}
|
||||
_ => {
|
||||
let rest = crate::agent_identity::generate_queue_secret()?;
|
||||
store
|
||||
.write(
|
||||
&grant_path,
|
||||
&fields(&[(REST_PASSWORD, &rest), (RESTIC_PASSWORD, &restic)]),
|
||||
)
|
||||
.await
|
||||
.with_context(|| format!("writing {grant_path}"))?;
|
||||
written = true;
|
||||
rest
|
||||
}
|
||||
};
|
||||
|
||||
let user_path = archive::user_path(agent)?;
|
||||
let line = htpasswd_line(agent, &rest);
|
||||
let user = store
|
||||
.read(&user_path)
|
||||
.await
|
||||
.with_context(|| format!("reading {user_path}"))?;
|
||||
if field(user.as_ref(), HTPASSWD) != Some(line.as_str()) {
|
||||
store
|
||||
.write(&user_path, &fields(&[(HTPASSWD, &line)]))
|
||||
.await
|
||||
.with_context(|| format!("writing {user_path}"))?;
|
||||
written = true;
|
||||
}
|
||||
Ok(written)
|
||||
}
|
||||
|
||||
/// The entries under `prefix` that are single leaves.
|
||||
async fn leaves(store: &impl ArchiveStore, prefix: &str) -> Result<Vec<String>> {
|
||||
Ok(store
|
||||
.list(prefix)
|
||||
.await
|
||||
.with_context(|| format!("listing {prefix}"))?
|
||||
.into_iter()
|
||||
.filter(|name| !name.ends_with('/'))
|
||||
.collect())
|
||||
}
|
||||
|
||||
/// One pass: grant every agent in `placed`, then revoke what no placement
|
||||
/// justifies. `hives` is every hive of the swarm, whose copies are checked.
|
||||
///
|
||||
/// Nothing happens until the archive has announced itself at
|
||||
/// [`archive::ready_path`]: a swarm without one gets no credentials. A hive in
|
||||
/// `undeclared` has no declaration to read, which does not show it places
|
||||
/// nothing, so its copies, and the user lines of the agents they name, stay.
|
||||
///
|
||||
/// # Errors
|
||||
/// Never: a failure is counted in [`Done::failed`] and logged, and the rest of
|
||||
/// the pass still runs.
|
||||
pub(crate) async fn reconcile(
|
||||
store: &impl ArchiveStore,
|
||||
placed: &BTreeSet<(String, String)>,
|
||||
undeclared: &BTreeSet<String>,
|
||||
hives: &[String],
|
||||
) -> Done {
|
||||
let mut done = Done::default();
|
||||
match store.read(&archive::ready_path().unwrap_or_default()).await {
|
||||
Ok(Some(_)) => {}
|
||||
Ok(None) => return done,
|
||||
Err(e) => {
|
||||
tracing::warn!(error = %format!("{e:#}"), "archive: reading whether the archive is up failed");
|
||||
done.failed += 1;
|
||||
return done;
|
||||
}
|
||||
}
|
||||
let mut holders: BTreeMap<&str, Vec<&str>> = BTreeMap::new();
|
||||
for (hive, agent) in placed {
|
||||
holders.entry(agent).or_default().push(hive);
|
||||
}
|
||||
|
||||
let mut ambiguous = BTreeSet::new();
|
||||
let mut unconfirmed = BTreeSet::new();
|
||||
for (agent, on) in &holders {
|
||||
if let [hive] = on.as_slice() {
|
||||
match grant(store, hive, agent).await {
|
||||
Ok(true) => done.granted += 1,
|
||||
Ok(false) => {}
|
||||
Err(e) => {
|
||||
tracing::warn!(hive, agent, error = %format!("{e:#}"), "archive: granting failed");
|
||||
done.failed += 1;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
tracing::warn!(agent, hives = ?on, "archive: placed on more than one hive; credentials left as they are");
|
||||
ambiguous.insert(*agent);
|
||||
}
|
||||
}
|
||||
|
||||
for hive in hives {
|
||||
let copies = match archive::grants_prefix(hive) {
|
||||
Ok(prefix) => leaves(store, &prefix).await,
|
||||
Err(e) => Err(e.into()),
|
||||
};
|
||||
let copies = match copies {
|
||||
Ok(copies) => copies,
|
||||
Err(e) => {
|
||||
tracing::warn!(hive, error = %format!("{e:#}"), "archive: listing the hive's copies failed");
|
||||
done.failed += 1;
|
||||
continue;
|
||||
}
|
||||
};
|
||||
if undeclared.contains(hive) {
|
||||
unconfirmed.extend(copies);
|
||||
continue;
|
||||
}
|
||||
for agent in copies {
|
||||
let keep = ambiguous.contains(agent.as_str())
|
||||
|| placed.contains(&(hive.clone(), agent.clone()));
|
||||
if !keep {
|
||||
revoke(store, archive::grant_path(hive, &agent), &mut done).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
match leaves(store, &archive::users_prefix().unwrap_or_default()).await {
|
||||
Ok(users) => {
|
||||
for agent in users {
|
||||
if !holders.contains_key(agent.as_str()) && !unconfirmed.contains(&agent) {
|
||||
revoke(store, archive::user_path(&agent), &mut done).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::warn!(error = %format!("{e:#}"), "archive: listing the users failed");
|
||||
done.failed += 1;
|
||||
}
|
||||
}
|
||||
done
|
||||
}
|
||||
|
||||
/// Delete the credential at `path`, counting the outcome in `done`.
|
||||
async fn revoke(
|
||||
store: &impl ArchiveStore,
|
||||
path: Result<String, swarm_secret_client::Error>,
|
||||
done: &mut Done,
|
||||
) {
|
||||
let path = match path {
|
||||
Ok(path) => path,
|
||||
Err(e) => {
|
||||
tracing::warn!(error = %e, "archive: a stored name is not a valid path segment");
|
||||
done.failed += 1;
|
||||
return;
|
||||
}
|
||||
};
|
||||
match store.delete(&path).await {
|
||||
Ok(()) => {
|
||||
tracing::info!(%path, "archive: credential revoked");
|
||||
done.revoked += 1;
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::warn!(%path, error = %format!("{e:#}"), "archive: revoking failed");
|
||||
done.failed += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Reconcile now and every [`RECONCILE_INTERVAL`] after. A pass that fails is
|
||||
/// logged and retried on the next tick; it never stops the daemon. Nothing is
|
||||
/// revoked on a pass that could not read where the hives place agents.
|
||||
pub fn spawn(wanted: Arc<WantedWriter>, hives: Vec<String>) {
|
||||
tokio::spawn(async move {
|
||||
let mut ticker = tokio::time::interval(RECONCILE_INTERVAL);
|
||||
loop {
|
||||
ticker.tick().await;
|
||||
let pass = async {
|
||||
let (placed, undeclared) =
|
||||
crate::jobq::placements_with_gaps(&wanted, &hives).await?;
|
||||
let store = crate::store::connect()
|
||||
.await
|
||||
.context("logging in to the swarm secret store")?;
|
||||
anyhow::Ok(reconcile(&store, &placed, &undeclared, &hives).await)
|
||||
};
|
||||
match tokio::time::timeout(PASS_DEADLINE, pass).await {
|
||||
Ok(Ok(done)) if done != Done::default() => tracing::info!(
|
||||
granted = done.granted,
|
||||
revoked = done.revoked,
|
||||
failed = done.failed,
|
||||
"archive: credentials reconciled"
|
||||
),
|
||||
Ok(Ok(_)) => tracing::debug!("archive: every credential is current"),
|
||||
Ok(Err(e)) => tracing::warn!(
|
||||
error = %format!("{e:#}"),
|
||||
retry_in_s = RECONCILE_INTERVAL.as_secs(),
|
||||
"archive: pass failed; retrying next tick"
|
||||
),
|
||||
Err(_) => tracing::warn!(
|
||||
deadline_s = PASS_DEADLINE.as_secs(),
|
||||
"archive: pass timed out; retrying next tick"
|
||||
),
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::sync::Mutex;
|
||||
|
||||
use super::*;
|
||||
|
||||
/// An in-memory store. `create` refuses a held path, `list` answers like
|
||||
/// the store's: the names directly under a prefix.
|
||||
#[derive(Default)]
|
||||
struct Memory {
|
||||
kv: Mutex<BTreeMap<String, Fields>>,
|
||||
/// Paths under this prefix refuse every write and delete.
|
||||
refuse: Option<&'static str>,
|
||||
}
|
||||
|
||||
impl Memory {
|
||||
/// A store whose archive has announced itself.
|
||||
fn up() -> Self {
|
||||
let store = Self::default();
|
||||
store.kv.lock().unwrap().insert(
|
||||
archive::ready_path().unwrap(),
|
||||
fields(&[(archive::READY, "1")]),
|
||||
);
|
||||
store
|
||||
}
|
||||
|
||||
fn get(&self, path: &str) -> Option<Fields> {
|
||||
self.kv.lock().unwrap().get(path).cloned()
|
||||
}
|
||||
|
||||
fn value(&self, path: &str, name: &str) -> Option<String> {
|
||||
self.get(path).and_then(|f| f.get(name).cloned())
|
||||
}
|
||||
|
||||
fn refused(&self, path: &str) -> bool {
|
||||
self.refuse.is_some_and(|p| path.starts_with(p))
|
||||
}
|
||||
}
|
||||
|
||||
impl ArchiveStore for Memory {
|
||||
async fn read(&self, path: &str) -> Result<Option<Fields>> {
|
||||
Ok(self.get(path))
|
||||
}
|
||||
|
||||
async fn write(&self, path: &str, fields: &Fields) -> Result<()> {
|
||||
if self.refused(path) {
|
||||
anyhow::bail!("denied");
|
||||
}
|
||||
self.kv
|
||||
.lock()
|
||||
.unwrap()
|
||||
.insert(path.to_owned(), fields.clone());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn create(&self, path: &str, fields: &Fields) -> Result<()> {
|
||||
if self.get(path).is_some() {
|
||||
anyhow::bail!("exists");
|
||||
}
|
||||
self.write(path, fields).await
|
||||
}
|
||||
|
||||
async fn list(&self, path: &str) -> Result<Vec<String>> {
|
||||
let prefix = format!("{path}/");
|
||||
Ok(self
|
||||
.kv
|
||||
.lock()
|
||||
.unwrap()
|
||||
.keys()
|
||||
.filter_map(|k| k.strip_prefix(&prefix))
|
||||
.map(|rest| match rest.split_once('/') {
|
||||
Some((dir, _)) => format!("{dir}/"),
|
||||
None => rest.to_owned(),
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
async fn delete(&self, path: &str) -> Result<()> {
|
||||
if self.refused(path) {
|
||||
anyhow::bail!("denied");
|
||||
}
|
||||
self.kv.lock().unwrap().remove(path);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn placed(pairs: &[(&str, &str)]) -> BTreeSet<(String, String)> {
|
||||
pairs
|
||||
.iter()
|
||||
.map(|(h, a)| ((*h).to_owned(), (*a).to_owned()))
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn none() -> BTreeSet<String> {
|
||||
BTreeSet::new()
|
||||
}
|
||||
|
||||
fn hives() -> Vec<String> {
|
||||
vec!["alpha".to_owned(), "beta".to_owned()]
|
||||
}
|
||||
|
||||
const ALPHA_ATLAS: &str = "swarm/hives/alpha/archive/atlas";
|
||||
const BETA_ATLAS: &str = "swarm/hives/beta/archive/atlas";
|
||||
const USER_ATLAS: &str = "swarm/services/archive/users/atlas";
|
||||
const RESTIC_ATLAS: &str = "swarm/services/archive/restic/atlas";
|
||||
|
||||
#[test]
|
||||
fn the_htpasswd_line_is_apaches_sha_form() {
|
||||
// `htpasswd -nbs atlas secret`
|
||||
assert_eq!(
|
||||
htpasswd_line("atlas", "secret"),
|
||||
"atlas:{SHA}5en6G6MezRroT3XKqkdPOmY/BfQ="
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_placed_agent_gets_its_hive_a_password_and_the_archive_its_hash() {
|
||||
let store = Memory::up();
|
||||
let done = reconcile(&store, &placed(&[("alpha", "atlas")]), &none(), &hives()).await;
|
||||
assert_eq!(
|
||||
done,
|
||||
Done {
|
||||
granted: 1,
|
||||
revoked: 0,
|
||||
failed: 0
|
||||
}
|
||||
);
|
||||
let rest = store.value(ALPHA_ATLAS, REST_PASSWORD).expect("a password");
|
||||
let restic = store.value(ALPHA_ATLAS, RESTIC_PASSWORD).expect("restic");
|
||||
assert_eq!(
|
||||
store.value(USER_ATLAS, HTPASSWD),
|
||||
Some(htpasswd_line("atlas", &rest))
|
||||
);
|
||||
assert_eq!(store.value(RESTIC_ATLAS, PASSWORD), Some(restic));
|
||||
assert_ne!(Some(rest), store.value(ALPHA_ATLAS, RESTIC_PASSWORD));
|
||||
// The hash line is all the archive's user leaf holds.
|
||||
assert!(!store.get(USER_ATLAS).unwrap().contains_key(REST_PASSWORD));
|
||||
// Presence control for the absence checks below: only the placed hive.
|
||||
assert!(store.get(BETA_ATLAS).is_none());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_current_grant_is_not_rewritten() {
|
||||
let store = Memory::up();
|
||||
let one = placed(&[("alpha", "atlas")]);
|
||||
reconcile(&store, &one, &none(), &hives()).await;
|
||||
let before = store.get(ALPHA_ATLAS);
|
||||
let done = reconcile(&store, &one, &none(), &hives()).await;
|
||||
assert_eq!(done, Done::default());
|
||||
assert_eq!(store.get(ALPHA_ATLAS), before);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_move_replaces_the_password_and_takes_the_old_hives_copy() {
|
||||
let store = Memory::up();
|
||||
reconcile(&store, &placed(&[("alpha", "atlas")]), &none(), &hives()).await;
|
||||
let old_rest = store.value(ALPHA_ATLAS, REST_PASSWORD).unwrap();
|
||||
let restic = store.value(RESTIC_ATLAS, PASSWORD).unwrap();
|
||||
|
||||
let done = reconcile(&store, &placed(&[("beta", "atlas")]), &none(), &hives()).await;
|
||||
assert_eq!(done.granted, 1);
|
||||
assert_eq!(done.revoked, 1);
|
||||
assert!(store.get(ALPHA_ATLAS).is_none(), "the old hive loses read");
|
||||
let new_rest = store.value(BETA_ATLAS, REST_PASSWORD).expect("new hive");
|
||||
assert_ne!(new_rest, old_rest, "the old password stops working");
|
||||
assert_eq!(
|
||||
store.value(USER_ATLAS, HTPASSWD),
|
||||
Some(htpasswd_line("atlas", &new_rest))
|
||||
);
|
||||
assert_ne!(
|
||||
store.value(USER_ATLAS, HTPASSWD),
|
||||
Some(htpasswd_line("atlas", &old_rest))
|
||||
);
|
||||
assert_eq!(
|
||||
store.value(BETA_ATLAS, RESTIC_PASSWORD).as_deref(),
|
||||
Some(restic.as_str()),
|
||||
"the repository stays readable on the new hive"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_destroyed_agent_loses_every_credential_but_the_restic_password() {
|
||||
let store = Memory::up();
|
||||
reconcile(
|
||||
&store,
|
||||
&placed(&[("alpha", "atlas"), ("beta", "argus")]),
|
||||
&none(),
|
||||
&hives(),
|
||||
)
|
||||
.await;
|
||||
let done = reconcile(&store, &placed(&[("beta", "argus")]), &none(), &hives()).await;
|
||||
assert_eq!(done.revoked, 2);
|
||||
assert!(store.get(ALPHA_ATLAS).is_none());
|
||||
assert!(store.get(USER_ATLAS).is_none());
|
||||
assert!(
|
||||
store.get(RESTIC_ATLAS).is_some(),
|
||||
"the backups stay readable"
|
||||
);
|
||||
// Control: the agent still placed keeps all of it.
|
||||
assert!(store.get("swarm/hives/beta/archive/argus").is_some());
|
||||
assert!(store.get("swarm/services/archive/users/argus").is_some());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn an_agent_two_hives_place_is_left_as_it_is() {
|
||||
let store = Memory::up();
|
||||
reconcile(&store, &placed(&[("alpha", "atlas")]), &none(), &hives()).await;
|
||||
let before = (store.get(ALPHA_ATLAS), store.get(USER_ATLAS));
|
||||
let both = placed(&[("alpha", "atlas"), ("beta", "atlas")]);
|
||||
let done = reconcile(&store, &both, &none(), &hives()).await;
|
||||
assert_eq!(done, Done::default());
|
||||
assert_eq!((store.get(ALPHA_ATLAS), store.get(USER_ATLAS)), before);
|
||||
assert!(store.get(BETA_ATLAS).is_none());
|
||||
|
||||
// Neither hive is granted when the agent is new and both place it.
|
||||
let fresh = Memory::up();
|
||||
let done = reconcile(&fresh, &both, &none(), &hives()).await;
|
||||
assert_eq!(done, Done::default());
|
||||
assert_eq!(
|
||||
fresh.kv.lock().unwrap().keys().collect::<Vec<_>>(),
|
||||
[&archive::ready_path().unwrap()],
|
||||
"only the archive's own marker is stored"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_lost_user_line_is_rewritten_from_the_hives_password() {
|
||||
let store = Memory::up();
|
||||
let one = placed(&[("alpha", "atlas")]);
|
||||
reconcile(&store, &one, &none(), &hives()).await;
|
||||
let line = store.value(USER_ATLAS, HTPASSWD);
|
||||
store.kv.lock().unwrap().remove(USER_ATLAS);
|
||||
let done = reconcile(&store, &one, &none(), &hives()).await;
|
||||
assert_eq!(done.granted, 1);
|
||||
assert_eq!(store.value(USER_ATLAS, HTPASSWD), line);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_refused_write_counts_as_failed_and_the_other_agents_still_get_theirs() {
|
||||
let store = Memory {
|
||||
refuse: Some("swarm/hives/alpha/"),
|
||||
..Memory::up()
|
||||
};
|
||||
let done = reconcile(
|
||||
&store,
|
||||
&placed(&[("alpha", "atlas"), ("beta", "argus")]),
|
||||
&none(),
|
||||
&hives(),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(done.failed, 1);
|
||||
assert_eq!(done.granted, 1);
|
||||
assert!(store.get("swarm/hives/beta/archive/argus").is_some());
|
||||
assert!(
|
||||
store.get(USER_ATLAS).is_none(),
|
||||
"no hash without the hive's copy"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn the_restic_password_survives_a_revoke_and_a_new_grant_and_a_move() {
|
||||
let store = Memory::up();
|
||||
let atlas = |hive: &str| placed(&[(hive, "atlas")]);
|
||||
reconcile(&store, &atlas("alpha"), &none(), &hives()).await;
|
||||
let restic = store.value(RESTIC_ATLAS, PASSWORD).expect("minted once");
|
||||
let rest = store.value(ALPHA_ATLAS, REST_PASSWORD).expect("granted");
|
||||
|
||||
// Nothing places the agent: every credential goes, the restic one stays.
|
||||
let nowhere = placed(&[]);
|
||||
reconcile(&store, &nowhere, &none(), &hives()).await;
|
||||
assert!(store.get(ALPHA_ATLAS).is_none() && store.get(USER_ATLAS).is_none());
|
||||
assert_eq!(store.value(RESTIC_ATLAS, PASSWORD).as_ref(), Some(&restic));
|
||||
|
||||
// Placed again: the login is new, the repository's password is the one it was created with.
|
||||
reconcile(&store, &atlas("alpha"), &none(), &hives()).await;
|
||||
assert_ne!(store.value(ALPHA_ATLAS, REST_PASSWORD), Some(rest));
|
||||
assert_eq!(
|
||||
store.value(ALPHA_ATLAS, RESTIC_PASSWORD).as_ref(),
|
||||
Some(&restic)
|
||||
);
|
||||
assert_eq!(store.value(RESTIC_ATLAS, PASSWORD).as_ref(), Some(&restic));
|
||||
|
||||
// And across a move.
|
||||
reconcile(&store, &atlas("beta"), &none(), &hives()).await;
|
||||
assert_eq!(
|
||||
store.value(BETA_ATLAS, RESTIC_PASSWORD).as_ref(),
|
||||
Some(&restic)
|
||||
);
|
||||
assert_eq!(store.value(RESTIC_ATLAS, PASSWORD).as_ref(), Some(&restic));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_hive_with_no_declaration_keeps_its_copies_and_its_agents_user_lines() {
|
||||
let store = Memory::up();
|
||||
reconcile(&store, &placed(&[("alpha", "atlas")]), &none(), &hives()).await;
|
||||
let (copy, line) = (store.get(ALPHA_ATLAS), store.get(USER_ATLAS));
|
||||
|
||||
// alpha's declaration is not there: it does not place atlas, and that proves nothing.
|
||||
let gap: BTreeSet<String> = ["alpha".to_owned()].into();
|
||||
let done = reconcile(&store, &placed(&[]), &gap, &hives()).await;
|
||||
assert_eq!(done, Done::default());
|
||||
assert_eq!(
|
||||
(store.get(ALPHA_ATLAS), store.get(USER_ATLAS)),
|
||||
(copy, line)
|
||||
);
|
||||
|
||||
// Control: with the declaration read, the same placements revoke.
|
||||
let done = reconcile(&store, &placed(&[]), &none(), &hives()).await;
|
||||
assert_eq!(done.revoked, 2);
|
||||
assert!(store.get(ALPHA_ATLAS).is_none() && store.get(USER_ATLAS).is_none());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_swarm_whose_archive_has_not_announced_itself_gets_nothing() {
|
||||
let store = Memory::default();
|
||||
let done = reconcile(&store, &placed(&[("alpha", "atlas")]), &none(), &hives()).await;
|
||||
assert_eq!(done, Done::default());
|
||||
assert!(store.kv.lock().unwrap().is_empty());
|
||||
|
||||
// Control: the same placements, once the archive is up.
|
||||
store.kv.lock().unwrap().insert(
|
||||
archive::ready_path().unwrap(),
|
||||
fields(&[(archive::READY, "1")]),
|
||||
);
|
||||
let done = reconcile(&store, &placed(&[("alpha", "atlas")]), &none(), &hives()).await;
|
||||
assert_eq!(done.granted, 1);
|
||||
}
|
||||
}
|
||||
898
swarm-controller/src/secrets/backend_egress.rs
Normal file
898
swarm-controller/src/secrets/backend_egress.rs
Normal file
|
|
@ -0,0 +1,898 @@
|
|||
//! The hosts an agent's backend environment names, kept as derived entries of
|
||||
//! the egress allow list (`crate::egress_allow`), so a restricted agent whose
|
||||
//! `ANTHROPIC_BASE_URL` points at a provider other than Anthropic reaches that
|
||||
//! provider through its hive's proxy.
|
||||
//!
|
||||
//! An entry is marked `derived` and a hive renders it like any other. Only the
|
||||
//! operator's save or delete of the environment through the controller creates
|
||||
//! one ([`follow_env`]): the agent can create its own `backend-env` leaf while
|
||||
//! it is empty, so what the store holds is not evidence that an operator chose
|
||||
//! it. [`spawn_backfill`] therefore only drops: it keeps a derived entry while
|
||||
//! the stored environment still names its exact host, and never adds one. Each
|
||||
//! host goes through `egress_allow::checked`, the check an operator's own
|
||||
//! entry gets.
|
||||
//!
|
||||
//! An agent still on the hand-placed `backendEnvironmentFile` alone has no
|
||||
//! derived entry, and neither does an environment saved before this existed
|
||||
//! until the operator saves it once more. The opencode preset's provider URL
|
||||
//! (`acp.opencode.provider.baseUrl`) is host configuration, not part of the
|
||||
//! environment, so it is never derived either.
|
||||
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use problem_details::ProblemDetails;
|
||||
use swarm_secret_client::backend_env::{self, BackendEnv};
|
||||
use swarm_wire::egress_allow::{AllowList, BACKEND_ENV_SOURCE, Entry, MAX_ENTRIES};
|
||||
|
||||
use crate::egress_allow::{base_domains, checked, modify};
|
||||
use crate::linked_accounts::AccountStore;
|
||||
use crate::routes::{AppState, error_problem, wanted_error_status};
|
||||
use crate::schedules::queue;
|
||||
use crate::wanted::WantedWriter;
|
||||
|
||||
/// `ANTHROPIC_BASE_URL` and every variable named `<PROVIDER>_BASE_URL`, which
|
||||
/// is where a provider's address sits for an ACP agent that loads the same
|
||||
/// file.
|
||||
fn is_url_variable(name: &str) -> bool {
|
||||
name == "ANTHROPIC_BASE_URL" || name.ends_with("_BASE_URL")
|
||||
}
|
||||
|
||||
/// The URL variables `env` assigns, as `(name, value)`. A later assignment of a
|
||||
/// name replaces an earlier one, as systemd's `EnvironmentFile=` does.
|
||||
fn url_assignments(env: &str) -> BTreeMap<&str, &str> {
|
||||
let mut found = BTreeMap::new();
|
||||
for line in env.lines().map(str::trim) {
|
||||
if line.is_empty() || line.starts_with(['#', ';']) {
|
||||
continue;
|
||||
}
|
||||
let Some((name, value)) = line.split_once('=') else {
|
||||
continue;
|
||||
};
|
||||
let name = name.trim();
|
||||
if is_url_variable(name) {
|
||||
found.insert(name, unquoted(value.trim()));
|
||||
}
|
||||
}
|
||||
found
|
||||
}
|
||||
|
||||
fn unquoted(value: &str) -> &str {
|
||||
for quote in ['"', '\''] {
|
||||
if let Some(inner) = value
|
||||
.strip_prefix(quote)
|
||||
.and_then(|v| v.strip_suffix(quote))
|
||||
{
|
||||
return inner;
|
||||
}
|
||||
}
|
||||
value
|
||||
}
|
||||
|
||||
/// The host of `url`, as written: its scheme (`http` or `https`, or none),
|
||||
/// user information, port, path, query and fragment are dropped. Nothing is
|
||||
/// validated; the result goes through `egress_allow::checked`.
|
||||
pub(crate) fn host_of(url: &str) -> Option<&str> {
|
||||
let rest = match url.split_once("://") {
|
||||
Some(("http" | "https", rest)) => rest,
|
||||
Some(_) => return None,
|
||||
None => url,
|
||||
};
|
||||
let authority = rest.split(['/', '?', '#']).next()?;
|
||||
let authority = authority.rsplit('@').next()?;
|
||||
Some(match authority.rsplit_once(':') {
|
||||
Some((host, port)) if port.bytes().all(|b| b.is_ascii_digit()) => host,
|
||||
_ => authority,
|
||||
})
|
||||
}
|
||||
|
||||
/// The derived entries for `agent`'s `env`: one per distinct host that passes
|
||||
/// `egress_allow::checked`. A host that does not (an IP address, `localhost`,
|
||||
/// a name the base list already allows) is logged by variable name and left
|
||||
/// out. The value is never logged: a URL can carry credentials.
|
||||
fn derive(agent: &str, env: &str, base: &[String]) -> Vec<Entry> {
|
||||
let mut entries: Vec<Entry> = derive_named(agent, env, base)
|
||||
.into_iter()
|
||||
.map(|(_, entry)| entry)
|
||||
.collect();
|
||||
entries.sort();
|
||||
entries.dedup();
|
||||
entries
|
||||
}
|
||||
|
||||
/// [`fn@derive`] with the variable each entry came from, one per variable.
|
||||
fn derive_named<'a>(agent: &str, env: &'a str, base: &[String]) -> Vec<(&'a str, Entry)> {
|
||||
let mut entries = Vec::new();
|
||||
for (name, value) in url_assignments(env) {
|
||||
let Some(host) = host_of(value) else {
|
||||
tracing::info!(%agent, variable = name, "backend 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((
|
||||
name,
|
||||
Entry {
|
||||
derived: true,
|
||||
source: Some(BACKEND_ENV_SOURCE.to_owned()),
|
||||
..entry
|
||||
},
|
||||
)),
|
||||
Err(why) => {
|
||||
tracing::info!(%agent, variable = name, %why, "backend egress: no entry for this host");
|
||||
}
|
||||
}
|
||||
}
|
||||
entries
|
||||
}
|
||||
|
||||
/// `list` with, for each agent in `desired`, its entries derived from the backend
|
||||
/// environment replaced by the given ones. Entries of other agents,
|
||||
/// operator-added entries and entries derived from linked accounts are
|
||||
/// untouched. A full list takes no more derived entries.
|
||||
fn replaced(mut list: AllowList, desired: &BTreeMap<String, Vec<Entry>>) -> AllowList {
|
||||
list.entries.retain(|e| {
|
||||
!(e.from_backend_env() && e.agent.as_ref().is_some_and(|a| desired.contains_key(a)))
|
||||
});
|
||||
for entry in desired.values().flatten() {
|
||||
if list.entries.len() >= MAX_ENTRIES {
|
||||
tracing::warn!(
|
||||
domain = %entry.domain,
|
||||
"backend egress: the allow list is full; no entry for this host"
|
||||
);
|
||||
break;
|
||||
}
|
||||
list.entries.push(entry.clone());
|
||||
}
|
||||
list
|
||||
}
|
||||
|
||||
/// Replace `agent`'s derived entries with those of `env`, or with none when
|
||||
/// `env` is `None` (the environment was deleted). A host without a queue
|
||||
/// (`state.status` unset) has no allow list, so nothing happens.
|
||||
///
|
||||
/// # Errors
|
||||
/// A problem naming that the environment is stored but the list was not
|
||||
/// updated; saving the environment again retries.
|
||||
pub(crate) async fn follow_env(
|
||||
state: &AppState,
|
||||
agent: &str,
|
||||
env: Option<&str>,
|
||||
) -> Result<(), ProblemDetails> {
|
||||
if state.status.is_none() {
|
||||
return Ok(());
|
||||
}
|
||||
let base = base_domains();
|
||||
let desired = BTreeMap::from([(
|
||||
agent.to_owned(),
|
||||
env.map(|text| derive(agent, text, &base))
|
||||
.unwrap_or_default(),
|
||||
)]);
|
||||
let updated = async {
|
||||
let client = queue(state).map_err(|(_, why)| anyhow::anyhow!(why))?;
|
||||
modify(&client, |list| replaced(list, &desired)).await
|
||||
}
|
||||
.await;
|
||||
match updated {
|
||||
Ok(true) => tracing::info!(%agent, "backend egress: derived entries updated"),
|
||||
Ok(false) => {}
|
||||
Err(e) => {
|
||||
tracing::warn!(%agent, error = %format!("{e:#}"), "backend egress: updating the allow list failed");
|
||||
return Err(error_problem(
|
||||
wanted_error_status(&e),
|
||||
&format!(
|
||||
"the backend environment is stored, but the allowed domains were not \
|
||||
updated ({e:#}); saving it again retries"
|
||||
),
|
||||
));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `list` without the backend-env entries of the agents in `still_named` whose
|
||||
/// host is not in that agent's set. Nothing is added; entries of agents not in
|
||||
/// the map, operator-added entries and link-derived entries are untouched.
|
||||
fn pruned(mut list: AllowList, still_named: &BTreeMap<String, BTreeSet<String>>) -> AllowList {
|
||||
list.entries.retain(|e| {
|
||||
let Some(hosts) = e.agent.as_ref().and_then(|a| still_named.get(a)) else {
|
||||
return true;
|
||||
};
|
||||
!e.from_backend_env() || hosts.contains(&e.domain)
|
||||
});
|
||||
list
|
||||
}
|
||||
|
||||
/// Drop the derived entries whose host the stored environment no longer names.
|
||||
///
|
||||
/// Only the agents that have a derived entry are looked at. An agent whose
|
||||
/// stored environment is gone loses all of them; one whose environment cannot
|
||||
/// be read keeps them. A host the stored environment names that is not
|
||||
/// already derived is left out and logged by variable name, since whoever
|
||||
/// wrote the store may be the agent itself.
|
||||
///
|
||||
/// Answers how many agents could not be read.
|
||||
///
|
||||
/// # Errors
|
||||
/// A queue failure reading or writing the list.
|
||||
pub(crate) async fn reconcile(
|
||||
client: &async_nats::Client,
|
||||
store: &impl AccountStore,
|
||||
) -> anyhow::Result<usize> {
|
||||
let Some(current) = crate::egress_allow::current(client).await? else {
|
||||
return Ok(0);
|
||||
};
|
||||
let mut derived: BTreeMap<String, BTreeSet<String>> = BTreeMap::new();
|
||||
for entry in current.entries.iter().filter(|e| e.from_backend_env()) {
|
||||
if let Some(agent) = &entry.agent {
|
||||
derived
|
||||
.entry(agent.clone())
|
||||
.or_default()
|
||||
.insert(entry.domain.clone());
|
||||
}
|
||||
}
|
||||
let base = base_domains();
|
||||
let mut still_named = BTreeMap::new();
|
||||
let mut unreadable = 0;
|
||||
for (agent, kept) in derived {
|
||||
let Ok(path) = backend_env::env_path(&agent) else {
|
||||
continue;
|
||||
};
|
||||
match store.read_optional::<BackendEnv>(&path).await {
|
||||
Ok(stored) => {
|
||||
let named = stored.map_or_else(Vec::new, |s| {
|
||||
derive_named(&agent, &s.env, &base)
|
||||
.into_iter()
|
||||
.map(|(variable, entry)| (variable.to_owned(), entry.domain))
|
||||
.collect()
|
||||
});
|
||||
for (variable, domain) in &named {
|
||||
if !kept.contains(domain) {
|
||||
tracing::warn!(
|
||||
%agent,
|
||||
%variable,
|
||||
"backend egress: the agent's stored env names a host not derived \
|
||||
(only an operator save derives)"
|
||||
);
|
||||
}
|
||||
}
|
||||
still_named.insert(agent, named.into_iter().map(|(_, d)| d).collect());
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::warn!(%agent, error = %e, "backend egress: reading the backend env failed; its entries stay");
|
||||
unreadable += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
if modify(client, |list| pruned(list, &still_named)).await? {
|
||||
tracing::info!(
|
||||
agents = still_named.len(),
|
||||
"backend egress: dropped derived entries the stored env no longer names"
|
||||
);
|
||||
}
|
||||
Ok(unreadable)
|
||||
}
|
||||
|
||||
/// Run [`reconcile`] and `link_egress::reconcile` once the queue and the store
|
||||
/// answer, retrying with a growing wait until a pass reads every agent that
|
||||
/// has an entry and some hive has declared an agent.
|
||||
pub(crate) fn spawn_backfill(
|
||||
client: async_nats::Client,
|
||||
wanted: Arc<WantedWriter>,
|
||||
hives: Vec<String>,
|
||||
) {
|
||||
tokio::spawn(async move {
|
||||
let mut wait = Duration::from_secs(5);
|
||||
loop {
|
||||
let pass = async {
|
||||
swarm_queue_client::ensure_connected(&client)?;
|
||||
let store = crate::store::connect().await?;
|
||||
let live = crate::subagent_term::live_agents(&wanted, &hives).await;
|
||||
let unreadable = reconcile(&client, &store).await?
|
||||
+ crate::link_egress::reconcile(&client, &store, &live).await?;
|
||||
Ok::<_, anyhow::Error>(unreadable + usize::from(live.is_empty()))
|
||||
}
|
||||
.await;
|
||||
match pass {
|
||||
Ok(0) => return,
|
||||
Ok(n) => tracing::warn!(
|
||||
unreadable = n,
|
||||
"backend egress: backfill incomplete; retrying"
|
||||
),
|
||||
Err(e) => {
|
||||
tracing::warn!(error = %format!("{e:#}"), "backend egress: backfill failed; retrying");
|
||||
}
|
||||
}
|
||||
tokio::time::sleep(wait).await;
|
||||
wait = (wait * 2).min(Duration::from_mins(5));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::sync::Arc;
|
||||
|
||||
use super::*;
|
||||
use crate::agent_limits::tests::declared;
|
||||
use crate::linked_accounts::tests::FakeStore;
|
||||
use crate::test_nats::TestNats;
|
||||
use serde_json::json;
|
||||
|
||||
fn base() -> Vec<String> {
|
||||
vec!["api.anthropic.com".to_owned(), ".claude.ai".to_owned()]
|
||||
}
|
||||
|
||||
fn hosts(env: &str) -> Vec<String> {
|
||||
derive("atlas", env, &base())
|
||||
.into_iter()
|
||||
.map(|e| e.domain)
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_url_is_reduced_to_its_host() {
|
||||
for (value, host) in [
|
||||
("https://openrouter.ai/api/v1", "openrouter.ai"),
|
||||
("http://llm.example.com", "llm.example.com"),
|
||||
("https://LLM.Example.com:8443/v1?x=1#f", "llm.example.com"),
|
||||
("llm.example.com/v1", "llm.example.com"),
|
||||
("llm.example.com:8080", "llm.example.com"),
|
||||
("\"https://llm.example.com/v1\"", "llm.example.com"),
|
||||
("'https://llm.example.com/v1'", "llm.example.com"),
|
||||
("https://user:pw@llm.example.com/v1", "llm.example.com"),
|
||||
] {
|
||||
assert_eq!(
|
||||
hosts(&format!("ANTHROPIC_BASE_URL={value}\n")),
|
||||
[host],
|
||||
"{value}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_host_the_swarm_would_refuse_gets_no_entry() {
|
||||
for value in [
|
||||
"http://10.0.0.5:8080/v1",
|
||||
"https://127.0.0.1",
|
||||
"http://[::1]:11434",
|
||||
"http://localhost:11434/v1",
|
||||
"https://metadata",
|
||||
"ftp://llm.example.com",
|
||||
"https://*.example.com",
|
||||
"",
|
||||
"https://",
|
||||
// The base list already allows it.
|
||||
"https://api.anthropic.com/v1",
|
||||
"https://a.claude.ai",
|
||||
] {
|
||||
assert_eq!(
|
||||
hosts(&format!("ANTHROPIC_BASE_URL={value}\n")),
|
||||
Vec::<String>::new(),
|
||||
"{value:?}"
|
||||
);
|
||||
}
|
||||
// Control: the same shape with a public name gets one.
|
||||
assert_eq!(
|
||||
hosts("ANTHROPIC_BASE_URL=https://llm.example.com\n"),
|
||||
["llm.example.com"]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_url_variables_count_and_the_last_assignment_wins() {
|
||||
let env = "# ANTHROPIC_BASE_URL=https://commented.example.com\n\
|
||||
ANTHROPIC_API_KEY=https://not-a-url-var.example.com\n\
|
||||
OPENAI_BASE_URL=https://acp.example.org/v1\n\
|
||||
ANTHROPIC_BASE_URL=https://first.example.com\n\
|
||||
ANTHROPIC_BASE_URL=https://second.example.com\n";
|
||||
assert_eq!(hosts(env), ["acp.example.org", "second.example.com"]);
|
||||
assert_eq!(hosts("ANTHROPIC_API_KEY=sk-x\n"), Vec::<String>::new());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_derived_entry_is_marked_and_scoped_to_the_agent() {
|
||||
let entries = derive(
|
||||
"atlas",
|
||||
"ANTHROPIC_BASE_URL=https://llm.example.com\n",
|
||||
&base(),
|
||||
);
|
||||
assert_eq!(
|
||||
entries,
|
||||
[Entry {
|
||||
domain: "llm.example.com".to_owned(),
|
||||
agent: Some("atlas".to_owned()),
|
||||
derived: true,
|
||||
source: Some(BACKEND_ENV_SOURCE.to_owned()),
|
||||
}]
|
||||
);
|
||||
}
|
||||
|
||||
fn manual(domain: &str, agent: &str) -> Entry {
|
||||
Entry {
|
||||
domain: domain.to_owned(),
|
||||
agent: Some(agent.to_owned()),
|
||||
derived: false,
|
||||
source: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn derived(domain: &str, agent: &str) -> Entry {
|
||||
Entry {
|
||||
derived: true,
|
||||
source: Some(BACKEND_ENV_SOURCE.to_owned()),
|
||||
..manual(domain, agent)
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn replacing_replaces_only_the_named_agents_derived_entries() {
|
||||
let list = AllowList {
|
||||
entries: vec![
|
||||
derived("old.example.com", "atlas"),
|
||||
manual("old.example.com", "atlas"),
|
||||
manual("github.com", "atlas"),
|
||||
derived("other.example.com", "iris"),
|
||||
],
|
||||
};
|
||||
let desired = BTreeMap::from([(
|
||||
"atlas".to_owned(),
|
||||
vec![derived("new.example.com", "atlas")],
|
||||
)]);
|
||||
let after = replaced(list, &desired);
|
||||
assert_eq!(
|
||||
after.entries,
|
||||
[
|
||||
manual("old.example.com", "atlas"),
|
||||
manual("github.com", "atlas"),
|
||||
derived("other.example.com", "iris"),
|
||||
derived("new.example.com", "atlas"),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
fn linked(domain: &str, agent: &str, source: &str) -> Entry {
|
||||
Entry {
|
||||
derived: true,
|
||||
source: Some(source.to_owned()),
|
||||
..manual(domain, agent)
|
||||
}
|
||||
}
|
||||
|
||||
/// A derived entry written before sources existed.
|
||||
fn untagged(domain: &str, agent: &str) -> Entry {
|
||||
Entry {
|
||||
source: None,
|
||||
..derived(domain, agent)
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_backend_env_save_leaves_link_entries_and_replaces_untagged_ones() {
|
||||
let list = AllowList {
|
||||
entries: vec![
|
||||
linked("github.com", "atlas", "link:github"),
|
||||
linked("hs.example.org", "atlas", "link:matrix:work"),
|
||||
untagged("old.example.com", "atlas"),
|
||||
],
|
||||
};
|
||||
let desired = BTreeMap::from([(
|
||||
"atlas".to_owned(),
|
||||
vec![derived("new.example.com", "atlas")],
|
||||
)]);
|
||||
let after = replaced(list, &desired);
|
||||
assert_eq!(
|
||||
after.entries,
|
||||
[
|
||||
linked("github.com", "atlas", "link:github"),
|
||||
linked("hs.example.org", "atlas", "link:matrix:work"),
|
||||
derived("new.example.com", "atlas"),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pruning_the_backend_env_leaves_link_entries_and_drops_untagged_ones() {
|
||||
let list = AllowList {
|
||||
entries: vec![
|
||||
linked("github.com", "atlas", "link:github"),
|
||||
untagged("old.example.com", "atlas"),
|
||||
derived("kept.example.com", "atlas"),
|
||||
],
|
||||
};
|
||||
let still_named = BTreeMap::from([(
|
||||
"atlas".to_owned(),
|
||||
BTreeSet::from(["kept.example.com".to_owned()]),
|
||||
)]);
|
||||
assert_eq!(
|
||||
pruned(list, &still_named).entries,
|
||||
[
|
||||
linked("github.com", "atlas", "link:github"),
|
||||
derived("kept.example.com", "atlas"),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
/// 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> {
|
||||
crate::egress_allow::current(client)
|
||||
.await
|
||||
.expect("the queue answers")
|
||||
.map(|l| {
|
||||
let mut e = l.entries;
|
||||
e.sort();
|
||||
e
|
||||
})
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
async fn put(state: &AppState, agent: &str, env: &str) {
|
||||
crate::backend_env::put_backend_env(
|
||||
axum::extract::State(state.clone()),
|
||||
axum::extract::Path(("pr1ma".to_owned(), agent.to_owned())),
|
||||
axum::Json(serde_json::from_value(json!({"env": env})).expect("a request body")),
|
||||
)
|
||||
.await
|
||||
.expect("stored");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn saving_changing_and_deleting_the_env_moves_the_derived_entries() {
|
||||
let nats = TestNats::start();
|
||||
let client = nats.client().await;
|
||||
let store = Arc::default();
|
||||
let state = swarm(&client, &store).await;
|
||||
|
||||
put(
|
||||
&state,
|
||||
"atlas",
|
||||
"ANTHROPIC_BASE_URL=https://one.example.com/v1\n",
|
||||
)
|
||||
.await;
|
||||
assert_eq!(
|
||||
list_of(&client).await,
|
||||
[derived("one.example.com", "atlas")]
|
||||
);
|
||||
|
||||
// A change replaces the host, an operator's own entry stays.
|
||||
let _ = crate::egress_allow::add_allowed_domain(
|
||||
axum::extract::State(state.clone()),
|
||||
axum::Json(swarm_controller_api::egress::AllowedDomain {
|
||||
domain: "github.com".to_owned(),
|
||||
agent: Some("atlas".to_owned()),
|
||||
derived: false,
|
||||
}),
|
||||
)
|
||||
.await
|
||||
.expect("manual entry");
|
||||
put(
|
||||
&state,
|
||||
"atlas",
|
||||
"ANTHROPIC_BASE_URL=https://two.example.com/v1\n",
|
||||
)
|
||||
.await;
|
||||
assert_eq!(
|
||||
list_of(&client).await,
|
||||
[
|
||||
manual("github.com", "atlas"),
|
||||
derived("two.example.com", "atlas")
|
||||
]
|
||||
);
|
||||
|
||||
// Removing the variable removes the entry.
|
||||
put(&state, "atlas", "ANTHROPIC_API_KEY=sk-live\n").await;
|
||||
assert_eq!(list_of(&client).await, [manual("github.com", "atlas")]);
|
||||
|
||||
// Deleting the env takes the entries of the env it held.
|
||||
put(
|
||||
&state,
|
||||
"atlas",
|
||||
"ANTHROPIC_BASE_URL=https://three.example.com\n",
|
||||
)
|
||||
.await;
|
||||
crate::linked_accounts::delete_backend_env(
|
||||
axum::extract::State(state.clone()),
|
||||
axum::extract::Path(("pr1ma".to_owned(), "atlas".to_owned())),
|
||||
)
|
||||
.await
|
||||
.expect("deleted");
|
||||
assert_eq!(list_of(&client).await, [manual("github.com", "atlas")]);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn an_env_with_no_host_never_creates_the_list() {
|
||||
let nats = TestNats::start();
|
||||
let client = nats.client().await;
|
||||
let store = Arc::default();
|
||||
let state = swarm(&client, &store).await;
|
||||
|
||||
put(&state, "atlas", "ANTHROPIC_API_KEY=sk-live\n").await;
|
||||
assert!(
|
||||
swarm_queue_client::egress_allow::open(&client)
|
||||
.await
|
||||
.expect("the queue answers")
|
||||
.is_none(),
|
||||
"no bucket: nothing was written"
|
||||
);
|
||||
// Control: a host does create it.
|
||||
put(
|
||||
&state,
|
||||
"atlas",
|
||||
"ANTHROPIC_BASE_URL=https://llm.example.com\n",
|
||||
)
|
||||
.await;
|
||||
assert_eq!(list_of(&client).await.len(), 1);
|
||||
}
|
||||
|
||||
const OPERATOR: &str = "ANTHROPIC_BASE_URL=https://llm.example.com/v1\n";
|
||||
|
||||
fn leaf(agent: &str) -> String {
|
||||
format!("swarm/agents/{agent}/backend-env")
|
||||
}
|
||||
|
||||
async fn write_leaf(store: &FakeStore, agent: &str, env: &str) {
|
||||
store
|
||||
.write(
|
||||
&leaf(agent),
|
||||
&BackendEnv {
|
||||
env: env.to_owned(),
|
||||
},
|
||||
)
|
||||
.await
|
||||
.expect("written");
|
||||
}
|
||||
|
||||
/// The agent creates its own leaf while it is empty, so a stored value is
|
||||
/// not evidence of an operator's choice: the backfill adds nothing for it.
|
||||
#[tokio::test]
|
||||
async fn a_leaf_created_outside_the_route_yields_no_entry() {
|
||||
let nats = TestNats::start();
|
||||
let client = nats.client().await;
|
||||
let store = Arc::new(FakeStore::default());
|
||||
let state = swarm(&client, &store).await;
|
||||
write_leaf(
|
||||
&store,
|
||||
"atlas",
|
||||
"ANTHROPIC_BASE_URL=https://evil.example.net\n",
|
||||
)
|
||||
.await;
|
||||
|
||||
// With no list at all, the pass creates nothing.
|
||||
assert_eq!(reconcile(&client, &*store).await.expect("pass"), 0);
|
||||
assert!(
|
||||
swarm_queue_client::egress_allow::open(&client)
|
||||
.await
|
||||
.expect("the queue answers")
|
||||
.is_none()
|
||||
);
|
||||
|
||||
// With a list that holds only an operator's entry, nothing is added.
|
||||
modify(&client, |mut list| {
|
||||
list.entries.push(manual("github.com", "atlas"));
|
||||
list
|
||||
})
|
||||
.await
|
||||
.expect("seed");
|
||||
assert_eq!(reconcile(&client, &*store).await.expect("pass"), 0);
|
||||
assert_eq!(list_of(&client).await, [manual("github.com", "atlas")]);
|
||||
|
||||
// Control: the operator's save of the same text derives the host.
|
||||
put(
|
||||
&state,
|
||||
"atlas",
|
||||
"ANTHROPIC_BASE_URL=https://evil.example.net\n",
|
||||
)
|
||||
.await;
|
||||
assert_eq!(
|
||||
list_of(&client).await,
|
||||
[
|
||||
derived("evil.example.net", "atlas"),
|
||||
manual("github.com", "atlas")
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
/// A pass keeps an entry whose exact host the stored env still names,
|
||||
/// drops one it no longer names, and never adds the new host.
|
||||
#[tokio::test]
|
||||
async fn the_backfill_keeps_a_named_host_drops_a_stale_one_and_adds_nothing() {
|
||||
let nats = TestNats::start();
|
||||
let client = nats.client().await;
|
||||
let store = Arc::new(FakeStore::default());
|
||||
let state = swarm(&client, &store).await;
|
||||
put(&state, "atlas", OPERATOR).await;
|
||||
let entry = derived("llm.example.com", "atlas");
|
||||
|
||||
// Control: unchanged content keeps the entry, and a second pass writes
|
||||
// nothing.
|
||||
assert_eq!(reconcile(&client, &*store).await.expect("pass"), 0);
|
||||
assert_eq!(list_of(&client).await, [entry]);
|
||||
let before = published(&client).await;
|
||||
reconcile(&client, &*store).await.expect("again");
|
||||
assert_eq!(published(&client).await, before);
|
||||
|
||||
// The stored text changed outside the route: the old host goes, the
|
||||
// new one does not come.
|
||||
write_leaf(
|
||||
&store,
|
||||
"atlas",
|
||||
"ANTHROPIC_BASE_URL=https://other.example.net\n",
|
||||
)
|
||||
.await;
|
||||
reconcile(&client, &*store).await.expect("pass");
|
||||
assert_eq!(list_of(&client).await, []);
|
||||
}
|
||||
|
||||
/// The leaf is deleted outside the controller and created again by the
|
||||
/// agent with another host before the pass: the old entry goes and the new
|
||||
/// host is not derived. A leaf that is simply gone drops its entries too.
|
||||
#[tokio::test]
|
||||
async fn a_leaf_deleted_and_recreated_by_the_agent_loses_the_entry_and_gains_none() {
|
||||
let nats = TestNats::start();
|
||||
let client = nats.client().await;
|
||||
let state = swarm(&client, &Arc::default()).await;
|
||||
put(&state, "atlas", OPERATOR).await;
|
||||
put(&state, "iris", OPERATOR).await;
|
||||
assert_eq!(list_of(&client).await.len(), 2, "control: both derived");
|
||||
|
||||
let recreated = FakeStore::default();
|
||||
write_leaf(
|
||||
&recreated,
|
||||
"atlas",
|
||||
"ANTHROPIC_BASE_URL=https://evil.example.net\n",
|
||||
)
|
||||
.await;
|
||||
// iris's leaf is gone, atlas's was created again by atlas.
|
||||
reconcile(&client, &recreated).await.expect("pass");
|
||||
assert_eq!(list_of(&client).await, []);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn an_unreadable_env_keeps_its_entries() {
|
||||
let nats = TestNats::start();
|
||||
let client = nats.client().await;
|
||||
let state = swarm(&client, &Arc::default()).await;
|
||||
put(
|
||||
&state,
|
||||
"atlas",
|
||||
"ANTHROPIC_BASE_URL=https://llm.example.com\n",
|
||||
)
|
||||
.await;
|
||||
|
||||
let unreadable = reconcile(&client, &FakeStore::denying())
|
||||
.await
|
||||
.expect("pass");
|
||||
assert_eq!(unreadable, 1);
|
||||
assert_eq!(
|
||||
list_of(&client).await,
|
||||
[derived("llm.example.com", "atlas")]
|
||||
);
|
||||
}
|
||||
|
||||
async fn published(client: &async_nats::Client) -> Option<String> {
|
||||
swarm_queue_client::egress_allow::open_or_create(client)
|
||||
.await
|
||||
.expect("bucket")
|
||||
.get(swarm_wire::egress_allow::KEY)
|
||||
.await
|
||||
.expect("read")
|
||||
.map(|v| String::from_utf8(v.to_vec()).expect("utf-8"))
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn an_operator_cannot_add_or_remove_a_derived_entry() {
|
||||
let nats = TestNats::start();
|
||||
let client = nats.client().await;
|
||||
let store = Arc::default();
|
||||
let state = swarm(&client, &store).await;
|
||||
put(
|
||||
&state,
|
||||
"atlas",
|
||||
"ANTHROPIC_BASE_URL=https://llm.example.com\n",
|
||||
)
|
||||
.await;
|
||||
|
||||
let request = |derived: bool| swarm_controller_api::egress::AllowedDomain {
|
||||
domain: "llm.example.com".to_owned(),
|
||||
agent: Some("atlas".to_owned()),
|
||||
derived,
|
||||
};
|
||||
for flagged in [true, false] {
|
||||
let problem = crate::egress_allow::remove_allowed_domain(
|
||||
axum::extract::State(state.clone()),
|
||||
axum::Json(request(flagged)),
|
||||
)
|
||||
.await
|
||||
.expect_err("refused");
|
||||
assert_eq!(
|
||||
problem.status,
|
||||
Some(axum::http::StatusCode::CONFLICT),
|
||||
"{problem:?}"
|
||||
);
|
||||
}
|
||||
let problem = crate::egress_allow::add_allowed_domain(
|
||||
axum::extract::State(state.clone()),
|
||||
axum::Json(request(true)),
|
||||
)
|
||||
.await
|
||||
.expect_err("refused");
|
||||
assert_eq!(problem.status, Some(axum::http::StatusCode::BAD_REQUEST));
|
||||
assert_eq!(
|
||||
list_of(&client).await,
|
||||
[derived("llm.example.com", "atlas")]
|
||||
);
|
||||
|
||||
// Control: the same name added by the operator is a separate entry that
|
||||
// the operator can remove, and the derived one stays.
|
||||
let manual_request = request(false);
|
||||
let _ = crate::egress_allow::add_allowed_domain(
|
||||
axum::extract::State(state.clone()),
|
||||
axum::Json(manual_request.clone()),
|
||||
)
|
||||
.await
|
||||
.expect("a manual entry");
|
||||
let _ = crate::egress_allow::remove_allowed_domain(
|
||||
axum::extract::State(state.clone()),
|
||||
axum::Json(manual_request),
|
||||
)
|
||||
.await
|
||||
.expect("removes the manual one");
|
||||
assert_eq!(
|
||||
list_of(&client).await,
|
||||
[derived("llm.example.com", "atlas")]
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn destroying_an_agent_drops_all_its_entries_and_only_its_own() {
|
||||
let nats = TestNats::start();
|
||||
let client = nats.client().await;
|
||||
let state = swarm(&client, &Arc::default()).await;
|
||||
put(
|
||||
&state,
|
||||
"atlas",
|
||||
"ANTHROPIC_BASE_URL=https://llm.example.com\n",
|
||||
)
|
||||
.await;
|
||||
modify(&client, |mut list| {
|
||||
list.entries.push(manual("github.com", "atlas"));
|
||||
list.entries.push(manual("crates.io", "iris"));
|
||||
list
|
||||
})
|
||||
.await
|
||||
.expect("seed");
|
||||
|
||||
crate::egress_allow::clear_on_destroy(&state, "pr1ma", "atlas").await;
|
||||
assert_eq!(list_of(&client).await, [manual("crates.io", "iris")]);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_host_without_a_queue_stores_the_env_and_skips_the_list() {
|
||||
let nats = TestNats::start();
|
||||
let client = nats.client().await;
|
||||
let store = Arc::new(FakeStore::default());
|
||||
let mut state = swarm(&client, &store).await;
|
||||
state.status = None;
|
||||
put(
|
||||
&state,
|
||||
"atlas",
|
||||
"ANTHROPIC_BASE_URL=https://llm.example.com\n",
|
||||
)
|
||||
.await;
|
||||
assert_eq!(store.written(), ["swarm/agents/atlas/backend-env"]);
|
||||
assert_eq!(list_of(&client).await, []);
|
||||
}
|
||||
}
|
||||
372
swarm-controller/src/secrets/backend_env.rs
Normal file
372
swarm-controller/src/secrets/backend_env.rs
Normal file
|
|
@ -0,0 +1,372 @@
|
|||
//! An agent's backend environment: an operator hands us the text of a systemd
|
||||
//! `EnvironmentFile`, and we put it in the swarm's secret store.
|
||||
//!
|
||||
//! The agent end is `nix/agent-modules/backend-env.nix`, which reads it under
|
||||
//! the agent's own certificate into the file its harness and subagent daemon
|
||||
//! load as `EnvironmentFile=`. This is the operator's path: it replaces
|
||||
//! whatever the leaf holds, including a value the agent wrote itself while the
|
||||
//! leaf was empty, and the store's value wins over the agent's
|
||||
//! `backendEnvironmentFile`.
|
||||
//!
|
||||
//! This is the agent's *configuration* (the provider's base URL, a model name),
|
||||
//! and it reads back as stored. Credentials belong in the write-only
|
||||
//! [`crate::backend_secrets`] leaf, which the agent's unit loads after this one.
|
||||
|
||||
use axum::Json;
|
||||
use axum::extract::State;
|
||||
use axum::http::StatusCode;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use swarm_secret_client::backend_env::{self, BackendEnv};
|
||||
use utoipa::ToSchema;
|
||||
|
||||
use crate::linked_accounts::AccountStore;
|
||||
use crate::routes::agents::swarm_hive;
|
||||
use crate::routes::{AppState, error_problem};
|
||||
|
||||
/// The most text one agent's environment may hold.
|
||||
const MAX_BYTES: usize = 16 * 1024;
|
||||
|
||||
/// The text to store for one agent.
|
||||
///
|
||||
/// No `Debug` derive: this carries live credentials.
|
||||
#[derive(Deserialize, ToSchema)]
|
||||
pub struct PutBackendEnvRequest {
|
||||
/// The file text, `NAME=VALUE` per line; blank lines and lines starting
|
||||
/// with `#` or `;` are allowed. Never logged, and never returned by this
|
||||
/// route.
|
||||
env: String,
|
||||
}
|
||||
|
||||
/// An agent's stored backend environment.
|
||||
#[derive(Serialize, ToSchema)]
|
||||
pub struct BackendEnvText {
|
||||
/// The file text, as stored.
|
||||
env: String,
|
||||
}
|
||||
|
||||
/// Read an agent's backend environment as stored.
|
||||
#[utoipa::path(
|
||||
get,
|
||||
path = "/api/hives/{hive}/agents/{agent}/backend-env",
|
||||
params(
|
||||
("hive" = String, Path, description = "hive the agent runs on"),
|
||||
("agent" = String, Path, description = "agent the environment belongs to"),
|
||||
),
|
||||
responses(
|
||||
(status = 200, description = "the stored text", body = BackendEnvText),
|
||||
(status = 400, description = "the agent is not an identifier, or the hive is not in this swarm (problem+json)", body = String),
|
||||
(status = 404, description = "no backend environment is stored (problem+json)", body = String),
|
||||
(status = 500, description = "the store could not be read (problem+json)", body = String),
|
||||
),
|
||||
tag = "agents"
|
||||
)]
|
||||
pub async fn get_backend_env(
|
||||
State(state): State<AppState>,
|
||||
axum::extract::Path((hive, agent)): axum::extract::Path<(String, String)>,
|
||||
) -> Result<Json<BackendEnvText>, 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 path = backend_env::env_path(&agent)
|
||||
.map_err(|e| error_problem(StatusCode::BAD_REQUEST, &e.to_string()))?;
|
||||
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 stored = store
|
||||
.read_optional::<BackendEnv>(&path)
|
||||
.await
|
||||
.map_err(|e| {
|
||||
tracing::warn!(%hive, %agent, error = %e, "reading the backend env failed");
|
||||
error_problem(StatusCode::INTERNAL_SERVER_ERROR, &e.to_string())
|
||||
})?;
|
||||
stored
|
||||
.map(|b| Json(BackendEnvText { env: b.env }))
|
||||
.ok_or_else(|| error_problem(StatusCode::NOT_FOUND, "no backend environment is stored"))
|
||||
}
|
||||
|
||||
/// Store an agent's backend environment, replacing any stored one.
|
||||
#[utoipa::path(
|
||||
put,
|
||||
path = "/api/hives/{hive}/agents/{agent}/backend-env",
|
||||
params(
|
||||
("hive" = String, Path, description = "hive the agent runs on"),
|
||||
("agent" = String, Path, description = "agent the environment belongs to"),
|
||||
),
|
||||
request_body = PutBackendEnvRequest,
|
||||
responses(
|
||||
(status = 204, description = "stored"),
|
||||
(status = 400, description = "the agent is not an identifier, the text is empty, too large or not `NAME=VALUE` lines, or the hive is not in this swarm (problem+json)", body = String),
|
||||
(status = 500, description = "the store could not be written (problem+json)", body = String),
|
||||
),
|
||||
tag = "agents"
|
||||
)]
|
||||
pub async fn put_backend_env(
|
||||
State(state): State<AppState>,
|
||||
axum::extract::Path((hive, agent)): axum::extract::Path<(String, String)>,
|
||||
Json(req): Json<PutBackendEnvRequest>,
|
||||
) -> 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 path = backend_env::env_path(&agent)
|
||||
.map_err(|e| error_problem(StatusCode::BAD_REQUEST, &e.to_string()))?;
|
||||
let stored = BackendEnv {
|
||||
env: validated(&req.env).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())
|
||||
})?;
|
||||
// A plain write, not a create: the operator is authoritative over a value
|
||||
// the agent planted in the empty leaf.
|
||||
store.write(&path, &stored).await.map_err(|e| {
|
||||
// The path names the agent; the value is not in it.
|
||||
tracing::warn!(%path, error = %e, "storing the backend env failed");
|
||||
error_problem(StatusCode::INTERNAL_SERVER_ERROR, &e.to_string())
|
||||
})?;
|
||||
|
||||
crate::backend_egress::follow_env(&state, &agent, Some(&stored.env)).await?;
|
||||
|
||||
tracing::info!(%hive, %agent, "backend env stored");
|
||||
Ok(StatusCode::NO_CONTENT)
|
||||
}
|
||||
|
||||
/// The text as it is stored, or why it cannot be.
|
||||
///
|
||||
/// Shared with [`crate::backend_secrets`], whose text has the same shape.
|
||||
///
|
||||
/// systemd skips a line it cannot parse and goes on, so a typo would load as
|
||||
/// a missing key. A quote that is not closed would swallow the lines after it
|
||||
/// into one value. The reasons name a line number and never its text.
|
||||
pub(crate) fn validated(text: &str) -> Result<String, String> {
|
||||
let text = text.trim();
|
||||
if text.is_empty() {
|
||||
return Err("env is required".to_owned());
|
||||
}
|
||||
if text.len() > MAX_BYTES {
|
||||
return Err(format!("env is over {MAX_BYTES} bytes"));
|
||||
}
|
||||
if text
|
||||
.chars()
|
||||
.any(|c| c.is_control() && !matches!(c, '\n' | '\r' | '\t'))
|
||||
{
|
||||
return Err("env holds a control character".to_owned());
|
||||
}
|
||||
for (n, line) in text.lines().enumerate() {
|
||||
if !valid_line(line.trim()) {
|
||||
return Err(format!("line {} is not NAME=VALUE", n + 1));
|
||||
}
|
||||
}
|
||||
Ok(format!("{text}\n"))
|
||||
}
|
||||
|
||||
/// A blank line, a comment, or `NAME=VALUE` with a closed quote and no
|
||||
/// trailing backslash.
|
||||
fn valid_line(line: &str) -> bool {
|
||||
if line.is_empty() || line.starts_with(['#', ';']) {
|
||||
return true;
|
||||
}
|
||||
let Some((name, value)) = line.split_once('=') else {
|
||||
return false;
|
||||
};
|
||||
let mut chars = name.chars();
|
||||
let name_ok = chars
|
||||
.next()
|
||||
.is_some_and(|c| c.is_ascii_alphabetic() || c == '_')
|
||||
&& chars.all(|c| c.is_ascii_alphanumeric() || c == '_');
|
||||
let value = value.trim();
|
||||
let closed = match value.chars().next() {
|
||||
Some(q @ ('"' | '\'')) => value.len() > 1 && value.ends_with(q),
|
||||
_ => true,
|
||||
};
|
||||
name_ok && closed && !value.ends_with('\\')
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) mod tests {
|
||||
use std::sync::Arc;
|
||||
|
||||
use axum::http::StatusCode;
|
||||
use serde_json::json;
|
||||
use swarm_secret_client::backend_env::BackendEnv;
|
||||
|
||||
use super::{MAX_BYTES, PutBackendEnvRequest, validated};
|
||||
use crate::linked_accounts::{AccountStore, Accounts, tests::FakeStore};
|
||||
|
||||
const SECRET: &str = "sk-live-0123";
|
||||
|
||||
/// Bare-minimum `AppState`, as `github_account`'s tests build it.
|
||||
pub(crate) 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,
|
||||
env: &str,
|
||||
) -> Result<StatusCode, problem_details::ProblemDetails> {
|
||||
super::put_backend_env(
|
||||
axum::extract::State(state(store)),
|
||||
axum::extract::Path(("pr1ma".to_owned(), agent.to_owned())),
|
||||
axum::Json(PutBackendEnvRequest {
|
||||
env: env.to_owned(),
|
||||
}),
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn stored(store: &FakeStore, agent: &str) -> Option<String> {
|
||||
store
|
||||
.read_optional::<BackendEnv>(&format!("swarm/agents/{agent}/backend-env"))
|
||||
.await
|
||||
.expect("store answers")
|
||||
.map(|b| b.env)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn plain_lines_comments_and_quoted_values_are_accepted() {
|
||||
let text = "# openrouter\nANTHROPIC_BASE_URL=https://openrouter.ai/api/v1\n\n\
|
||||
; key\n_K9=\"a b\"\nEMPTY=\nS='x'\n";
|
||||
let kept = validated(text).expect("valid");
|
||||
assert_eq!(kept, text.trim().to_owned() + "\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_systemd_would_skip_or_misread_is_refused() {
|
||||
for bad in [
|
||||
"",
|
||||
" \n ",
|
||||
"KEY",
|
||||
"=value",
|
||||
"1KEY=v",
|
||||
"KE Y=v",
|
||||
"KEY=\"open",
|
||||
"KEY='",
|
||||
"KEY=trailing\\",
|
||||
"A=1\nnot a line\nB=2",
|
||||
"A=b\0c",
|
||||
] {
|
||||
assert!(validated(bad).is_err(), "{bad:?}");
|
||||
}
|
||||
assert!(validated(&format!("A={}", "x".repeat(MAX_BYTES))).is_err());
|
||||
// The control: the size cap is the only difference.
|
||||
assert!(validated(&format!("A={}", "x".repeat(MAX_BYTES - 2))).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_refusal_names_the_line_and_not_its_text() {
|
||||
let reason = validated(&format!("A=1\n{SECRET}\n")).expect_err("no `=`");
|
||||
assert_eq!(reason, "line 2 is not NAME=VALUE");
|
||||
assert!(!reason.contains(SECRET), "{reason}");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_plain_request_is_stored_under_the_agent() {
|
||||
let store = Arc::default();
|
||||
let status = put(&store, "atlas", &format!("ANTHROPIC_API_KEY={SECRET}"))
|
||||
.await
|
||||
.expect("stored");
|
||||
assert_eq!(status, StatusCode::NO_CONTENT);
|
||||
assert_eq!(store.written(), ["swarm/agents/atlas/backend-env"]);
|
||||
assert_eq!(
|
||||
stored(&store, "atlas").await.as_deref(),
|
||||
Some("ANTHROPIC_API_KEY=sk-live-0123\n")
|
||||
);
|
||||
}
|
||||
|
||||
/// The operator's write replaces a value an agent planted in the leaf.
|
||||
#[tokio::test]
|
||||
async fn a_value_already_in_the_leaf_is_overwritten() {
|
||||
let store = Arc::new(FakeStore::default().with(
|
||||
"swarm/agents/atlas/backend-env",
|
||||
json!({"env": "PLANTED=1\n"}),
|
||||
));
|
||||
put(&store, "atlas", "ANTHROPIC_API_KEY=operator")
|
||||
.await
|
||||
.expect("overwritten");
|
||||
assert_eq!(
|
||||
stored(&store, "atlas").await.as_deref(),
|
||||
Some("ANTHROPIC_API_KEY=operator\n")
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_bad_agent_or_body_is_refused_before_the_store() {
|
||||
let store = Arc::default();
|
||||
let leaky = format!("{SECRET}-no-equals");
|
||||
for (agent, env) in [
|
||||
("Atlas", "A=1"),
|
||||
("../x", "A=1"),
|
||||
("atlas", " "),
|
||||
("atlas", leaky.as_str()),
|
||||
] {
|
||||
let problem = put(&store, agent, env).await.expect_err("refused");
|
||||
assert_eq!(problem.status, Some(StatusCode::BAD_REQUEST), "{problem:?}");
|
||||
assert!(!format!("{problem:?}").contains(SECRET), "{problem:?}");
|
||||
}
|
||||
assert!(store.written().is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_store_failure_does_not_echo_the_value() {
|
||||
let store = Arc::new(FakeStore::denying());
|
||||
let problem = put(&store, "atlas", &format!("ANTHROPIC_API_KEY={SECRET}"))
|
||||
.await
|
||||
.expect_err("the store refuses");
|
||||
assert_eq!(problem.status, Some(StatusCode::INTERNAL_SERVER_ERROR));
|
||||
assert!(!format!("{problem:?}").contains(SECRET), "{problem:?}");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn the_stored_text_reads_back_as_stored_and_nothing_stored_is_a_404() {
|
||||
let store = Arc::default();
|
||||
let get = |store: &Arc<FakeStore>| {
|
||||
super::get_backend_env(
|
||||
axum::extract::State(state(store)),
|
||||
axum::extract::Path(("pr1ma".to_owned(), "atlas".to_owned())),
|
||||
)
|
||||
};
|
||||
let problem = get(&store).await.err().expect("nothing stored");
|
||||
assert_eq!(problem.status, Some(StatusCode::NOT_FOUND));
|
||||
|
||||
put(&store, "atlas", "ANTHROPIC_BASE_URL=https://x.example")
|
||||
.await
|
||||
.expect("saved");
|
||||
let read = get(&store).await.expect("read");
|
||||
assert_eq!(read.0.env, "ANTHROPIC_BASE_URL=https://x.example\n");
|
||||
}
|
||||
}
|
||||
224
swarm-controller/src/secrets/backend_secrets.rs
Normal file
224
swarm-controller/src/secrets/backend_secrets.rs
Normal file
|
|
@ -0,0 +1,224 @@
|
|||
//! An agent's backend secrets: an operator hands us the text of a systemd
|
||||
//! `EnvironmentFile` that holds credentials (`ANTHROPIC_API_KEY=…`), and we put
|
||||
//! it in a leaf of its own in the swarm's secret store, apart from the
|
||||
//! configuration in [`crate::backend_env`].
|
||||
//!
|
||||
//! The agent end is `nix/agent-modules/backend-env.nix`, which reads both under
|
||||
//! the agent's own certificate into the file its harness loads as
|
||||
//! `EnvironmentFile=`, the configuration first and these secrets after it. An
|
||||
//! agent whose environment then holds `ANTHROPIC_API_KEY` bills the API and
|
||||
//! tries it instead of waiting for a Claude login. No route hands the text
|
||||
//! back; [`get_backend_secrets`] says only whether the leaf holds any.
|
||||
|
||||
use axum::Json;
|
||||
use axum::extract::State;
|
||||
use axum::http::StatusCode;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use swarm_secret_client::backend_secrets::{self, BackendSecrets};
|
||||
use utoipa::ToSchema;
|
||||
|
||||
use crate::backend_env::validated;
|
||||
use crate::linked_accounts::AccountStore;
|
||||
use crate::routes::agents::swarm_hive;
|
||||
use crate::routes::{AppState, error_problem};
|
||||
|
||||
/// The secrets to store for one agent.
|
||||
///
|
||||
/// No `Debug` derive: this carries live credentials.
|
||||
#[derive(Deserialize, ToSchema)]
|
||||
pub struct PutBackendSecretsRequest {
|
||||
/// The file text, `NAME=VALUE` per line, as for the backend environment.
|
||||
/// Never logged, and never returned by any route.
|
||||
env: String,
|
||||
}
|
||||
|
||||
/// Whether an agent has backend secrets stored.
|
||||
#[derive(Debug, Serialize, ToSchema)]
|
||||
pub struct BackendSecretsStatus {
|
||||
/// `true` when the leaf holds text; the text is never returned.
|
||||
stored: bool,
|
||||
}
|
||||
|
||||
/// Whether an agent has backend secrets stored.
|
||||
#[utoipa::path(
|
||||
get,
|
||||
path = "/api/hives/{hive}/agents/{agent}/backend-secrets",
|
||||
params(
|
||||
("hive" = String, Path, description = "hive the agent runs on"),
|
||||
("agent" = String, Path, description = "agent the secrets belong to"),
|
||||
),
|
||||
responses(
|
||||
(status = 200, description = "whether secrets are stored; never the secrets", body = BackendSecretsStatus),
|
||||
(status = 400, description = "the agent is not an identifier, or the hive is not in this swarm (problem+json)", body = String),
|
||||
(status = 500, description = "the store could not be read (problem+json)", body = String),
|
||||
),
|
||||
tag = "agents"
|
||||
)]
|
||||
pub async fn get_backend_secrets(
|
||||
State(state): State<AppState>,
|
||||
axum::extract::Path((hive, agent)): axum::extract::Path<(String, String)>,
|
||||
) -> Result<Json<BackendSecretsStatus>, 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 path = backend_secrets::secrets_path(&agent)
|
||||
.map_err(|e| error_problem(StatusCode::BAD_REQUEST, &e.to_string()))?;
|
||||
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 stored = store
|
||||
.read_optional::<BackendSecrets>(&path)
|
||||
.await
|
||||
.map_err(|e| {
|
||||
tracing::warn!(%hive, %agent, error = %e, "reading the backend secrets failed");
|
||||
error_problem(StatusCode::INTERNAL_SERVER_ERROR, &e.to_string())
|
||||
})?;
|
||||
Ok(Json(BackendSecretsStatus {
|
||||
stored: stored.is_some_and(|s| !s.env.trim().is_empty()),
|
||||
}))
|
||||
}
|
||||
|
||||
/// Store an agent's backend secrets, replacing any stored ones.
|
||||
#[utoipa::path(
|
||||
put,
|
||||
path = "/api/hives/{hive}/agents/{agent}/backend-secrets",
|
||||
params(
|
||||
("hive" = String, Path, description = "hive the agent runs on"),
|
||||
("agent" = String, Path, description = "agent the secrets belong to"),
|
||||
),
|
||||
request_body = PutBackendSecretsRequest,
|
||||
responses(
|
||||
(status = 204, description = "stored"),
|
||||
(status = 400, description = "the agent is not an identifier, the text is empty, too large or not `NAME=VALUE` lines, or the hive is not in this swarm (problem+json)", body = String),
|
||||
(status = 500, description = "the store could not be written (problem+json)", body = String),
|
||||
),
|
||||
tag = "agents"
|
||||
)]
|
||||
pub async fn put_backend_secrets(
|
||||
State(state): State<AppState>,
|
||||
axum::extract::Path((hive, agent)): axum::extract::Path<(String, String)>,
|
||||
Json(req): Json<PutBackendSecretsRequest>,
|
||||
) -> 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 path = backend_secrets::secrets_path(&agent)
|
||||
.map_err(|e| error_problem(StatusCode::BAD_REQUEST, &e.to_string()))?;
|
||||
let stored = BackendSecrets {
|
||||
env: validated(&req.env).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())
|
||||
})?;
|
||||
store.write(&path, &stored).await.map_err(|e| {
|
||||
// The path names the agent; the value is not in it.
|
||||
tracing::warn!(%path, error = %e, "storing the backend secrets failed");
|
||||
error_problem(StatusCode::INTERNAL_SERVER_ERROR, &e.to_string())
|
||||
})?;
|
||||
tracing::info!(%hive, %agent, "backend secrets stored");
|
||||
Ok(StatusCode::NO_CONTENT)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::sync::Arc;
|
||||
|
||||
use axum::http::StatusCode;
|
||||
use serde_json::json;
|
||||
use swarm_secret_client::backend_secrets::BackendSecrets;
|
||||
|
||||
use super::super::backend_env::tests::state;
|
||||
use super::PutBackendSecretsRequest;
|
||||
use crate::linked_accounts::{AccountStore, tests::FakeStore};
|
||||
|
||||
const SECRET: &str = "sk-ant-live-0123";
|
||||
|
||||
async fn put(
|
||||
store: &Arc<FakeStore>,
|
||||
agent: &str,
|
||||
env: &str,
|
||||
) -> Result<StatusCode, problem_details::ProblemDetails> {
|
||||
super::put_backend_secrets(
|
||||
axum::extract::State(state(store)),
|
||||
axum::extract::Path(("pr1ma".to_owned(), agent.to_owned())),
|
||||
axum::Json(PutBackendSecretsRequest {
|
||||
env: env.to_owned(),
|
||||
}),
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn stored(store: &FakeStore, agent: &str) -> Option<String> {
|
||||
store
|
||||
.read_optional::<BackendSecrets>(&format!("swarm/agents/{agent}/backend-secrets"))
|
||||
.await
|
||||
.expect("store answers")
|
||||
.map(|s| s.env)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn secrets_are_stored_under_the_agent_and_replace_earlier_ones() {
|
||||
let store = Arc::new(FakeStore::default().with(
|
||||
"swarm/agents/atlas/backend-secrets",
|
||||
json!({"env": "OLD=1\n"}),
|
||||
));
|
||||
let status = put(&store, "atlas", &format!("ANTHROPIC_API_KEY={SECRET}"))
|
||||
.await
|
||||
.expect("stored");
|
||||
assert_eq!(status, StatusCode::NO_CONTENT);
|
||||
assert_eq!(store.written(), ["swarm/agents/atlas/backend-secrets"]);
|
||||
assert_eq!(
|
||||
stored(&store, "atlas").await.as_deref(),
|
||||
Some("ANTHROPIC_API_KEY=sk-ant-live-0123\n")
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_bad_agent_or_text_is_refused_before_the_store_and_never_echoed() {
|
||||
let store = Arc::default();
|
||||
let leaky = format!("{SECRET}-no-equals");
|
||||
for (agent, env) in [
|
||||
("Atlas", "A=1"),
|
||||
("../x", "A=1"),
|
||||
("atlas", " "),
|
||||
("atlas", leaky.as_str()),
|
||||
] {
|
||||
let problem = put(&store, agent, env).await.expect_err("refused");
|
||||
assert_eq!(problem.status, Some(StatusCode::BAD_REQUEST), "{problem:?}");
|
||||
assert!(!format!("{problem:?}").contains(SECRET), "{problem:?}");
|
||||
}
|
||||
assert!(store.written().is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_store_failure_does_not_echo_the_secrets() {
|
||||
let store = Arc::new(FakeStore::denying());
|
||||
let problem = put(&store, "atlas", &format!("ANTHROPIC_API_KEY={SECRET}"))
|
||||
.await
|
||||
.expect_err("refused");
|
||||
assert_eq!(problem.status, Some(StatusCode::INTERNAL_SERVER_ERROR));
|
||||
assert!(!format!("{problem:?}").contains(SECRET), "{problem:?}");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn the_status_says_whether_secrets_are_stored_and_never_what_they_are() {
|
||||
let store = Arc::new(FakeStore::default().with(
|
||||
"swarm/agents/atlas/backend-secrets",
|
||||
json!({"env": format!("ANTHROPIC_API_KEY={SECRET}\n")}),
|
||||
));
|
||||
for (agent, want) in [("atlas", true), ("red", false)] {
|
||||
let got = super::get_backend_secrets(
|
||||
axum::extract::State(state(&store)),
|
||||
axum::extract::Path(("pr1ma".to_owned(), agent.to_owned())),
|
||||
)
|
||||
.await
|
||||
.expect("answers");
|
||||
assert_eq!(got.0.stored, want, "{agent}");
|
||||
assert!(!format!("{got:?}").contains(SECRET));
|
||||
}
|
||||
}
|
||||
}
|
||||
414
swarm-controller/src/secrets/claude_login.rs
Normal file
414
swarm-controller/src/secrets/claude_login.rs
Normal file
|
|
@ -0,0 +1,414 @@
|
|||
//! An agent's claude login, run from the swarm UI: the operator's two steps,
|
||||
//! relayed to the `swarm-claude-login` minter over the queue.
|
||||
//!
|
||||
//! - `POST /api/agents/{name}/claude-login` starts `claude auth login` for
|
||||
//! the agent and answers with the URL to open.
|
||||
//! - `POST /api/agents/{name}/claude-login/code` hands it the code that page
|
||||
//! shows; the minter stores the credentials at
|
||||
//! `swarm/agents/<agent>/claude-credentials` and the agent's harness
|
||||
//! installs them.
|
||||
//! - `DELETE /api/agents/{name}/claude-login` stops a login started and not
|
||||
//! finished.
|
||||
//! - `GET /api/agents/{name}/claude-login` says when the agent's stored login
|
||||
//! was written, and `DELETE /api/agents/{name}/claude-login/stored` deletes
|
||||
//! it.
|
||||
//!
|
||||
//! The operator is the `Remote-User` header the gateway sets, as for
|
||||
//! [`crate::agent_input`]. Nothing here touches the store: the minter holds
|
||||
//! the one grant that writes the credentials.
|
||||
|
||||
use std::future::Future;
|
||||
|
||||
use axum::Json;
|
||||
use axum::extract::{Path, State};
|
||||
use axum::http::{HeaderMap, StatusCode};
|
||||
use problem_details::ProblemDetails;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use swarm_wire::claude_login::{REPLY_DEADLINE, Reply, Request, SUBJECT};
|
||||
use utoipa::ToSchema;
|
||||
|
||||
use crate::routes::{AppState, error_problem};
|
||||
|
||||
/// The header the gateway names the session's user in.
|
||||
const OPERATOR_HEADER: &str = "remote-user";
|
||||
|
||||
/// Where a step is sent: the queue in production, a fake in the tests.
|
||||
/// `Err` is a step that never reached the minter or never came back.
|
||||
pub(crate) trait LoginSink {
|
||||
fn step(&self, request: Vec<u8>) -> impl Future<Output = Result<Reply, String>> + Send;
|
||||
}
|
||||
|
||||
impl LoginSink for async_nats::Client {
|
||||
async fn step(&self, request: Vec<u8>) -> Result<Reply, String> {
|
||||
use async_nats::RequestErrorKind;
|
||||
|
||||
let sent = async_nats::Request::new()
|
||||
.payload(request.into())
|
||||
.timeout(Some(REPLY_DEADLINE));
|
||||
match self.send_request(SUBJECT, sent).await {
|
||||
Ok(msg) => serde_json::from_slice(&msg.payload)
|
||||
.map_err(|e| format!("the claude login minter's reply did not decode: {e}")),
|
||||
Err(e) => Err(match e.kind() {
|
||||
RequestErrorKind::NoResponders => "no claude login minter is listening: \
|
||||
deploy.claude-login.enable is set on no host, or its service is not \
|
||||
connected to the swarm queue"
|
||||
.to_owned(),
|
||||
RequestErrorKind::TimedOut => format!(
|
||||
"the claude login minter sent no answer within {}s",
|
||||
REPLY_DEADLINE.as_secs()
|
||||
),
|
||||
_ => format!("sending the step to the claude login minter failed: {e}"),
|
||||
}),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The page the operator opens to log the agent in.
|
||||
#[derive(Serialize, ToSchema)]
|
||||
pub struct ClaudeLoginStarted {
|
||||
pub url: String,
|
||||
}
|
||||
|
||||
/// The code the login page showed. No `Debug`: it is a one-time credential.
|
||||
#[derive(Deserialize, ToSchema)]
|
||||
pub struct PostClaudeLoginCodeRequest {
|
||||
/// Not logged.
|
||||
code: String,
|
||||
}
|
||||
|
||||
/// Start a claude login for an agent.
|
||||
#[utoipa::path(
|
||||
post,
|
||||
path = "/api/agents/{name}/claude-login",
|
||||
params(("name" = String, Path, description = "agent to log in")),
|
||||
responses(
|
||||
(status = 200, description = "the login is running; open `url` and post the code it shows", body = ClaudeLoginStarted),
|
||||
(status = 400, description = "the agent name is not an identifier (problem+json)", body = String),
|
||||
(status = 401, description = "the request carries no `Remote-User` (problem+json)", body = String),
|
||||
(status = 502, description = "the minter could not start the login (problem+json)", body = String),
|
||||
(status = 503, description = "no swarm queue here, or no minter listening on it (problem+json)", body = String),
|
||||
),
|
||||
tag = "agents"
|
||||
)]
|
||||
pub(crate) async fn post_claude_login(
|
||||
State(state): State<AppState>,
|
||||
Path(agent): Path<String>,
|
||||
headers: HeaderMap,
|
||||
) -> Result<Json<ClaudeLoginStarted>, ProblemDetails> {
|
||||
let operator = operator(&headers).map_err(problem)?;
|
||||
let agent = agent_name(&agent).map_err(problem)?;
|
||||
let sink = queue(&state).map_err(problem)?;
|
||||
match relay(&sink, &Request::Start { agent, operator }).await? {
|
||||
Reply::Started { url } => Ok(Json(ClaudeLoginStarted { url })),
|
||||
other => Err(unexpected(&other)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Hand an agent's running claude login the code its page showed.
|
||||
#[utoipa::path(
|
||||
post,
|
||||
path = "/api/agents/{name}/claude-login/code",
|
||||
params(("name" = String, Path, description = "agent being logged in")),
|
||||
request_body = PostClaudeLoginCodeRequest,
|
||||
responses(
|
||||
(status = 204, description = "the credentials are stored; the agent installs them within a minute"),
|
||||
(status = 400, description = "the agent name is not an identifier, or the code is empty (problem+json)", body = String),
|
||||
(status = 401, description = "the request carries no `Remote-User` (problem+json)", body = String),
|
||||
(status = 502, description = "the login failed or its credentials could not be stored (problem+json)", body = String),
|
||||
(status = 503, description = "no swarm queue here, or no minter listening on it (problem+json)", body = String),
|
||||
),
|
||||
tag = "agents"
|
||||
)]
|
||||
pub(crate) async fn post_claude_login_code(
|
||||
State(state): State<AppState>,
|
||||
Path(agent): Path<String>,
|
||||
headers: HeaderMap,
|
||||
Json(req): Json<PostClaudeLoginCodeRequest>,
|
||||
) -> Result<StatusCode, ProblemDetails> {
|
||||
let operator = operator(&headers).map_err(problem)?;
|
||||
let agent = agent_name(&agent).map_err(problem)?;
|
||||
let code = req.code.trim();
|
||||
if code.is_empty() {
|
||||
return Err(error_problem(StatusCode::BAD_REQUEST, "code is empty"));
|
||||
}
|
||||
let sink = queue(&state).map_err(problem)?;
|
||||
let request = Request::Code {
|
||||
agent: agent.clone(),
|
||||
code: code.to_owned(),
|
||||
};
|
||||
match relay(&sink, &request).await? {
|
||||
Reply::Stored => {
|
||||
tracing::info!(%agent, %operator, "claude credentials stored for the agent");
|
||||
Ok(StatusCode::NO_CONTENT)
|
||||
}
|
||||
other => Err(unexpected(&other)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Stop an agent's running claude login.
|
||||
#[utoipa::path(
|
||||
delete,
|
||||
path = "/api/agents/{name}/claude-login",
|
||||
params(("name" = String, Path, description = "agent being logged in")),
|
||||
responses(
|
||||
(status = 204, description = "no login is running for the agent now"),
|
||||
(status = 400, description = "the agent name is not an identifier (problem+json)", body = String),
|
||||
(status = 401, description = "the request carries no `Remote-User` (problem+json)", body = String),
|
||||
(status = 503, description = "no swarm queue here, or no minter listening on it (problem+json)", body = String),
|
||||
),
|
||||
tag = "agents"
|
||||
)]
|
||||
pub(crate) async fn delete_claude_login(
|
||||
State(state): State<AppState>,
|
||||
Path(agent): Path<String>,
|
||||
headers: HeaderMap,
|
||||
) -> Result<StatusCode, ProblemDetails> {
|
||||
operator(&headers).map_err(problem)?;
|
||||
let agent = agent_name(&agent).map_err(problem)?;
|
||||
let sink = queue(&state).map_err(problem)?;
|
||||
match relay(&sink, &Request::Cancel { agent }).await? {
|
||||
Reply::Cancelled => Ok(StatusCode::NO_CONTENT),
|
||||
other => Err(unexpected(&other)),
|
||||
}
|
||||
}
|
||||
|
||||
/// When the swarm's stored claude login for an agent was written.
|
||||
#[derive(Serialize, ToSchema)]
|
||||
pub struct ClaudeLoginStatus {
|
||||
/// RFC 3339, as the secret store spells it; `null` when nothing is stored.
|
||||
pub stored_at: Option<String>,
|
||||
}
|
||||
|
||||
/// When an agent's stored claude login was written.
|
||||
#[utoipa::path(
|
||||
get,
|
||||
path = "/api/agents/{name}/claude-login",
|
||||
params(("name" = String, Path, description = "agent whose login to look up")),
|
||||
responses(
|
||||
(status = 200, description = "the time the login was stored, or null", body = ClaudeLoginStatus),
|
||||
(status = 400, description = "the agent name is not an identifier (problem+json)", body = String),
|
||||
(status = 401, description = "the request carries no `Remote-User` (problem+json)", body = String),
|
||||
(status = 502, description = "the minter could not read the store (problem+json)", body = String),
|
||||
(status = 503, description = "no swarm queue here, or no minter listening on it (problem+json)", body = String),
|
||||
),
|
||||
tag = "agents"
|
||||
)]
|
||||
pub(crate) async fn get_claude_login(
|
||||
State(state): State<AppState>,
|
||||
Path(agent): Path<String>,
|
||||
headers: HeaderMap,
|
||||
) -> Result<Json<ClaudeLoginStatus>, ProblemDetails> {
|
||||
operator(&headers).map_err(problem)?;
|
||||
let agent = agent_name(&agent).map_err(problem)?;
|
||||
let sink = queue(&state).map_err(problem)?;
|
||||
match relay(&sink, &Request::Status { agent }).await? {
|
||||
Reply::Login { stored_at } => Ok(Json(ClaudeLoginStatus { stored_at })),
|
||||
other => Err(unexpected(&other)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Delete an agent's stored claude login, every version of it.
|
||||
#[utoipa::path(
|
||||
delete,
|
||||
path = "/api/agents/{name}/claude-login/stored",
|
||||
params(("name" = String, Path, description = "agent whose stored login to delete")),
|
||||
responses(
|
||||
(status = 204, description = "nothing is stored for the agent now"),
|
||||
(status = 400, description = "the agent name is not an identifier (problem+json)", body = String),
|
||||
(status = 401, description = "the request carries no `Remote-User` (problem+json)", body = String),
|
||||
(status = 502, description = "the minter could not delete it (problem+json)", body = String),
|
||||
(status = 503, description = "no swarm queue here, or no minter listening on it (problem+json)", body = String),
|
||||
),
|
||||
tag = "agents"
|
||||
)]
|
||||
pub(crate) async fn delete_stored_claude_login(
|
||||
State(state): State<AppState>,
|
||||
Path(agent): Path<String>,
|
||||
headers: HeaderMap,
|
||||
) -> Result<StatusCode, ProblemDetails> {
|
||||
let operator = operator(&headers).map_err(problem)?;
|
||||
let agent = agent_name(&agent).map_err(problem)?;
|
||||
let sink = queue(&state).map_err(problem)?;
|
||||
match relay(
|
||||
&sink,
|
||||
&Request::Delete {
|
||||
agent: agent.clone(),
|
||||
},
|
||||
)
|
||||
.await?
|
||||
{
|
||||
Reply::Deleted => {
|
||||
tracing::info!(%agent, %operator, "claude credentials deleted for the agent");
|
||||
Ok(StatusCode::NO_CONTENT)
|
||||
}
|
||||
other => Err(unexpected(&other)),
|
||||
}
|
||||
}
|
||||
|
||||
/// A refusal decided before the queue is touched.
|
||||
type Refusal = (StatusCode, String);
|
||||
|
||||
fn problem((status, detail): Refusal) -> ProblemDetails {
|
||||
error_problem(status, &detail)
|
||||
}
|
||||
|
||||
fn operator(headers: &HeaderMap) -> Result<String, Refusal> {
|
||||
headers
|
||||
.get(OPERATOR_HEADER)
|
||||
.and_then(|v| v.to_str().ok())
|
||||
.map(str::trim)
|
||||
.filter(|s| !s.is_empty())
|
||||
.map(str::to_owned)
|
||||
.ok_or_else(|| {
|
||||
(
|
||||
StatusCode::UNAUTHORIZED,
|
||||
"no Remote-User header: the gateway names the operator, and this request did \
|
||||
not come through it"
|
||||
.to_owned(),
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
fn agent_name(agent: &str) -> Result<String, Refusal> {
|
||||
Ok(hive_types::Ident::parse(agent)
|
||||
.map_err(|reason| (StatusCode::BAD_REQUEST, reason.to_owned()))?
|
||||
.into_string())
|
||||
}
|
||||
|
||||
fn queue(state: &AppState) -> Result<async_nats::Client, Refusal> {
|
||||
let Some(status) = state.status.as_ref() else {
|
||||
return Err((
|
||||
StatusCode::SERVICE_UNAVAILABLE,
|
||||
"no swarm queue is configured on this host".to_owned(),
|
||||
));
|
||||
};
|
||||
let client = status.queue_client();
|
||||
swarm_queue_client::ensure_connected(&client).map_err(|e| {
|
||||
(
|
||||
StatusCode::SERVICE_UNAVAILABLE,
|
||||
swarm_queue_client::chain(&e),
|
||||
)
|
||||
})?;
|
||||
Ok(client)
|
||||
}
|
||||
|
||||
/// Send `request` and return the minter's reply, a `Failed` one as a 502.
|
||||
async fn relay(sink: &impl LoginSink, request: &Request) -> Result<Reply, ProblemDetails> {
|
||||
let payload = serde_json::to_vec(request).map_err(|e| {
|
||||
error_problem(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
&format!("encoding the step failed: {e}"),
|
||||
)
|
||||
})?;
|
||||
match sink.step(payload).await {
|
||||
Ok(Reply::Failed { error }) => Err(error_problem(StatusCode::BAD_GATEWAY, &error)),
|
||||
Ok(reply) => Ok(reply),
|
||||
Err(e) => Err(error_problem(StatusCode::SERVICE_UNAVAILABLE, &e)),
|
||||
}
|
||||
}
|
||||
|
||||
fn unexpected(reply: &Reply) -> ProblemDetails {
|
||||
error_problem(
|
||||
StatusCode::BAD_GATEWAY,
|
||||
&format!("the claude login minter answered out of step: {reply:?}"),
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::sync::Mutex;
|
||||
|
||||
use axum::http::StatusCode;
|
||||
use swarm_wire::claude_login::{Reply, Request};
|
||||
|
||||
use super::{LoginSink, relay};
|
||||
|
||||
/// Answers every step with one fixed outcome and records what it got.
|
||||
struct FakeSink {
|
||||
answer: Result<Reply, String>,
|
||||
got: Mutex<Vec<Vec<u8>>>,
|
||||
}
|
||||
|
||||
impl LoginSink for FakeSink {
|
||||
async fn step(&self, request: Vec<u8>) -> Result<Reply, String> {
|
||||
self.got.lock().expect("lock").push(request);
|
||||
self.answer.clone()
|
||||
}
|
||||
}
|
||||
|
||||
fn sink(answer: Result<Reply, String>) -> FakeSink {
|
||||
FakeSink {
|
||||
answer,
|
||||
got: Mutex::default(),
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn the_code_reaches_the_minter_as_sent() {
|
||||
let s = sink(Ok(Reply::Stored));
|
||||
let request = Request::Code {
|
||||
agent: "atlas".to_owned(),
|
||||
code: "Abc_9.x-Q".to_owned(),
|
||||
};
|
||||
assert!(matches!(relay(&s, &request).await, Ok(Reply::Stored)));
|
||||
let got: serde_json::Value =
|
||||
serde_json::from_slice(&s.got.lock().expect("lock")[0]).expect("json");
|
||||
assert_eq!(got["step"], "code");
|
||||
assert_eq!(got["agent"], "atlas");
|
||||
assert_eq!(got["code"], "Abc_9.x-Q");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_status_and_a_delete_reach_the_minter_by_their_names() {
|
||||
let s = sink(Ok(Reply::Login { stored_at: None }));
|
||||
for (request, step) in [
|
||||
(
|
||||
Request::Status {
|
||||
agent: "atlas".to_owned(),
|
||||
},
|
||||
"status",
|
||||
),
|
||||
(
|
||||
Request::Delete {
|
||||
agent: "atlas".to_owned(),
|
||||
},
|
||||
"delete",
|
||||
),
|
||||
] {
|
||||
assert!(relay(&s, &request).await.is_ok());
|
||||
let got = s.got.lock().expect("lock").pop().expect("a step was sent");
|
||||
let got: serde_json::Value = serde_json::from_slice(&got).expect("json");
|
||||
assert_eq!(got["step"], step);
|
||||
assert_eq!(got["agent"], "atlas");
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_failed_step_is_a_bad_gateway_naming_why() {
|
||||
let s = sink(Ok(Reply::Failed {
|
||||
error: "OAuth error: invalid code".to_owned(),
|
||||
}));
|
||||
let request = Request::Cancel {
|
||||
agent: "atlas".to_owned(),
|
||||
};
|
||||
let e = relay(&s, &request).await.expect_err("a failure");
|
||||
assert_eq!(e.status, Some(StatusCode::BAD_GATEWAY));
|
||||
assert!(
|
||||
e.detail
|
||||
.as_deref()
|
||||
.is_some_and(|d| d.contains("invalid code")),
|
||||
"{:?}",
|
||||
e.detail
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn an_unreached_minter_is_unavailable() {
|
||||
let s = sink(Err("no claude login minter is listening".to_owned()));
|
||||
let request = Request::Cancel {
|
||||
agent: "atlas".to_owned(),
|
||||
};
|
||||
let e = relay(&s, &request).await.expect_err("unreached");
|
||||
assert_eq!(e.status, Some(StatusCode::SERVICE_UNAVAILABLE));
|
||||
}
|
||||
}
|
||||
667
swarm-controller/src/secrets/egress_allow.rs
Normal file
667
swarm-controller/src/secrets/egress_allow.rs
Normal file
|
|
@ -0,0 +1,667 @@
|
|||
//! `/api/egress/allowed-domains` — the destinations the swarm lets agents
|
||||
//! reach through their hive's egress proxy.
|
||||
//!
|
||||
//! The whole list is one value under one key of `egress-allow`
|
||||
//! (`swarm_wire::egress_allow`), which this daemon alone writes. Every hive
|
||||
//! reads it and renders the entries for the agents it runs: a swarm-wide entry
|
||||
//! joins the proxy's allow list for everyone, an entry with an agent is that
|
||||
//! agent's alone. A hive always allows the names its own nix configuration
|
||||
//! lists (`services.hyperhive.deploy.hive-controller.squid.allowedDomains`) as well, so these entries
|
||||
//! only add to them.
|
||||
//!
|
||||
//! Each name goes into the proxy's configuration, so it is checked here with
|
||||
//! `swarm_wire::egress_allow::normalize_domain` (the hive checks again) and
|
||||
//! refused when the proxy already allows it to everyone. The names the proxy
|
||||
//! always allows are the ones in [`ENV_BASE_DOMAINS`].
|
||||
|
||||
use axum::Json;
|
||||
use axum::extract::State;
|
||||
use axum::http::StatusCode;
|
||||
use problem_details::ProblemDetails;
|
||||
use swarm_controller_api::egress::{AllowedDomain, AllowedDomains};
|
||||
use swarm_queue_client::egress_allow;
|
||||
use swarm_wire::egress_allow::{AllowList, Entry, KEY, MAX_ENTRIES, covered_by, normalize_domain};
|
||||
|
||||
use crate::routes::{AppState, error_problem, wanted_error_status};
|
||||
use crate::schedules::{live, queue, read_or_default, refused, write_revision};
|
||||
|
||||
/// How many times a losing writer re-reads and re-applies, as in
|
||||
/// `wanted::MAX_ATTEMPTS`.
|
||||
const MAX_ATTEMPTS: usize = 5;
|
||||
|
||||
/// Why an operator can neither add nor remove an entry the controller derived.
|
||||
const DERIVED_REFUSED: &str = "this entry is kept automatically from the agent's backend environment or a linked \
|
||||
account; change or remove that variable, or unlink the account, instead";
|
||||
|
||||
/// Set from the hive module's `baseAllowedDomains` default by
|
||||
/// `nix/host-modules/swarm-controller.nix`: the names, separated by spaces,
|
||||
/// that every hive's proxy lets every authenticated agent reach. Unset means
|
||||
/// none are known and nothing is refused on that ground; a hive still skips
|
||||
/// the entries its own base list covers.
|
||||
pub(crate) const ENV_BASE_DOMAINS: &str = "SWARM_CONTROLLER_SQUID_BASE_DOMAINS";
|
||||
|
||||
pub(crate) fn base_domains() -> Vec<String> {
|
||||
std::env::var(ENV_BASE_DOMAINS)
|
||||
.unwrap_or_default()
|
||||
.split_whitespace()
|
||||
.map(str::to_ascii_lowercase)
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The entry to store for `req`, or why it is refused.
|
||||
pub(crate) fn checked(req: &AllowedDomain, base: &[String]) -> Result<Entry, String> {
|
||||
let domain = normalize_domain(&req.domain)?;
|
||||
if covered_by(&domain, base) {
|
||||
return Err(format!(
|
||||
"{domain} is already allowed for every agent by the proxy's base list"
|
||||
));
|
||||
}
|
||||
let agent = req
|
||||
.agent
|
||||
.as_deref()
|
||||
.map(|a| {
|
||||
hive_types::Ident::parse(a)
|
||||
.map(hive_types::Ident::into_string)
|
||||
.map_err(|reason| format!("agent {a:?}: {reason}"))
|
||||
})
|
||||
.transpose()?;
|
||||
Ok(Entry {
|
||||
domain,
|
||||
agent,
|
||||
derived: false,
|
||||
source: None,
|
||||
})
|
||||
}
|
||||
|
||||
/// What adding an entry to a list came to.
|
||||
enum Added {
|
||||
/// The entry was there: nothing to write.
|
||||
Already(AllowList),
|
||||
/// The list with the entry in it.
|
||||
Now(AllowList),
|
||||
}
|
||||
|
||||
/// `list` with `entry` added, or why it can't take another entry.
|
||||
fn added(mut list: AllowList, entry: &Entry) -> Result<Added, String> {
|
||||
if list.entries.contains(entry) {
|
||||
return Ok(Added::Already(list));
|
||||
}
|
||||
if list.entries.len() >= MAX_ENTRIES {
|
||||
return Err(format!(
|
||||
"the list holds {MAX_ENTRIES} entries, which is the most it takes"
|
||||
));
|
||||
}
|
||||
list.entries.push(entry.clone());
|
||||
list.entries.sort();
|
||||
Ok(Added::Now(list))
|
||||
}
|
||||
|
||||
fn view(list: AllowList) -> AllowedDomains {
|
||||
let mut entries = list.entries;
|
||||
entries.sort();
|
||||
AllowedDomains {
|
||||
entries: entries
|
||||
.into_iter()
|
||||
.map(|e| AllowedDomain {
|
||||
domain: e.domain,
|
||||
agent: e.agent,
|
||||
derived: e.derived,
|
||||
})
|
||||
.collect(),
|
||||
}
|
||||
}
|
||||
|
||||
fn queue_problem(e: &anyhow::Error) -> ProblemDetails {
|
||||
tracing::warn!(error = %format!("{e:#}"), "egress allow-list: queue failure");
|
||||
error_problem(wanted_error_status(e), &format!("{e:#}"))
|
||||
}
|
||||
|
||||
async fn open_or_create(
|
||||
client: &async_nats::Client,
|
||||
) -> Result<async_nats::jetstream::kv::Store, ProblemDetails> {
|
||||
egress_allow::open_or_create(client)
|
||||
.await
|
||||
.map_err(|e| queue_problem(&anyhow::Error::new(e)))
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
get,
|
||||
path = "/api/egress/allowed-domains",
|
||||
responses(
|
||||
(status = 200, description = "every entry, swarm-wide and per agent, sorted; empty \
|
||||
when the swarm has not set a list",
|
||||
body = AllowedDomains),
|
||||
(status = 503, description = "no swarm queue is configured on this host, or it is \
|
||||
not connected (problem+json)", body = String),
|
||||
(status = 500, description = "the list could not be read (problem+json)",
|
||||
body = String),
|
||||
),
|
||||
tag = "egress"
|
||||
)]
|
||||
pub(crate) async fn get_allowed_domains(
|
||||
State(state): State<AppState>,
|
||||
) -> Result<Json<AllowedDomains>, ProblemDetails> {
|
||||
let client = queue(&state).map_err(refused)?;
|
||||
let Some(store) = egress_allow::open(&client)
|
||||
.await
|
||||
.map_err(|e| queue_problem(&anyhow::Error::new(e)))?
|
||||
else {
|
||||
return Ok(Json(AllowedDomains::default()));
|
||||
};
|
||||
let (current, _, _) = read_or_default::<AllowList>(&store, KEY)
|
||||
.await
|
||||
.map_err(|e| queue_problem(&e))?;
|
||||
Ok(Json(view(current)))
|
||||
}
|
||||
|
||||
/// Allow one destination, for every agent or for one.
|
||||
///
|
||||
/// Adding an entry that is already there changes nothing. The entry adds to
|
||||
/// the names each hive's nix configuration already allows.
|
||||
#[utoipa::path(
|
||||
post,
|
||||
path = "/api/egress/allowed-domains",
|
||||
request_body = AllowedDomain,
|
||||
responses(
|
||||
(status = 200, description = "the whole list after the add", body = AllowedDomains),
|
||||
(status = 400, description = "the domain is not a DNS name (an IP address, a \
|
||||
wildcard, a single label and a port are refused), the proxy already allows \
|
||||
it to everyone, the agent is not an identifier or not declared on any hive, \
|
||||
or the list is full, or the entry is marked derived (problem+json)", body = String),
|
||||
(status = 422, description = "an unknown field"),
|
||||
(status = 503, description = "no swarm queue is configured on this host, or it is \
|
||||
not connected (problem+json)", body = String),
|
||||
(status = 500, description = "the list could not be written (problem+json)",
|
||||
body = String),
|
||||
),
|
||||
tag = "egress"
|
||||
)]
|
||||
pub(crate) async fn add_allowed_domain(
|
||||
State(state): State<AppState>,
|
||||
Json(req): Json<AllowedDomain>,
|
||||
) -> Result<Json<AllowedDomains>, ProblemDetails> {
|
||||
if req.derived {
|
||||
return Err(error_problem(StatusCode::BAD_REQUEST, DERIVED_REFUSED));
|
||||
}
|
||||
let entry = checked(&req, &base_domains())
|
||||
.map_err(|why| error_problem(StatusCode::BAD_REQUEST, &why))?;
|
||||
let client = queue(&state).map_err(refused)?;
|
||||
if let Some(agent) = &entry.agent
|
||||
&& !live(&state).await?.contains(agent)
|
||||
{
|
||||
return Err(error_problem(
|
||||
StatusCode::BAD_REQUEST,
|
||||
&format!("no hive's wanted state declares an agent {agent:?} that is not destroyed"),
|
||||
));
|
||||
}
|
||||
let store = open_or_create(&client).await?;
|
||||
for _ in 0..MAX_ATTEMPTS {
|
||||
let (list, revision, _) = read_or_default::<AllowList>(&store, KEY)
|
||||
.await
|
||||
.map_err(|e| queue_problem(&e))?;
|
||||
let list = match added(list, &entry) {
|
||||
Ok(Added::Already(list)) => return Ok(Json(view(list))),
|
||||
Ok(Added::Now(list)) => list,
|
||||
Err(why) => return Err(error_problem(StatusCode::BAD_REQUEST, &why)),
|
||||
};
|
||||
if write_revision(&store, KEY, &list, revision)
|
||||
.await
|
||||
.map_err(|e| queue_problem(&e))?
|
||||
.is_some()
|
||||
{
|
||||
tracing::info!(domain = %entry.domain, agent = ?entry.agent, "allowed a domain");
|
||||
return Ok(Json(view(list)));
|
||||
}
|
||||
}
|
||||
Err(queue_problem(&anyhow::anyhow!(
|
||||
"gave up adding {} after {MAX_ATTEMPTS} conflicting writes",
|
||||
entry.domain
|
||||
)))
|
||||
}
|
||||
|
||||
/// Stop allowing one destination for the scope it was added with.
|
||||
///
|
||||
/// Removing an entry that is not there changes nothing. A name a hive's nix
|
||||
/// configuration lists stays allowed on that hive.
|
||||
#[utoipa::path(
|
||||
delete,
|
||||
path = "/api/egress/allowed-domains",
|
||||
request_body = AllowedDomain,
|
||||
responses(
|
||||
(status = 200, description = "the whole list after the removal", body = AllowedDomains),
|
||||
(status = 400, description = "the domain is not a DNS name, or the agent is not an \
|
||||
identifier (problem+json)", body = String),
|
||||
(status = 409, description = "the entry is one the controller keeps from the agent's \
|
||||
backend environment, which an operator cannot remove (problem+json)",
|
||||
body = String),
|
||||
(status = 422, description = "an unknown field"),
|
||||
(status = 503, description = "no swarm queue is configured on this host, or it is \
|
||||
not connected (problem+json)", body = String),
|
||||
(status = 500, description = "the list could not be written (problem+json)",
|
||||
body = String),
|
||||
),
|
||||
tag = "egress"
|
||||
)]
|
||||
pub(crate) async fn remove_allowed_domain(
|
||||
State(state): State<AppState>,
|
||||
Json(req): Json<AllowedDomain>,
|
||||
) -> Result<Json<AllowedDomains>, ProblemDetails> {
|
||||
if req.derived {
|
||||
return Err(error_problem(StatusCode::CONFLICT, DERIVED_REFUSED));
|
||||
}
|
||||
// The base list is not consulted: an entry stored before a name joined it
|
||||
// can still be removed.
|
||||
let entry = checked(&req, &[]).map_err(|why| error_problem(StatusCode::BAD_REQUEST, &why))?;
|
||||
let client = queue(&state).map_err(refused)?;
|
||||
let store = open_or_create(&client).await?;
|
||||
for _ in 0..MAX_ATTEMPTS {
|
||||
let (mut list, revision, _) = read_or_default::<AllowList>(&store, KEY)
|
||||
.await
|
||||
.map_err(|e| queue_problem(&e))?;
|
||||
if !list.entries.contains(&entry) {
|
||||
if list
|
||||
.entries
|
||||
.iter()
|
||||
.any(|e| e.derived && e.domain == entry.domain && e.agent == entry.agent)
|
||||
{
|
||||
return Err(error_problem(StatusCode::CONFLICT, DERIVED_REFUSED));
|
||||
}
|
||||
return Ok(Json(view(list)));
|
||||
}
|
||||
list.entries.retain(|e| *e != entry);
|
||||
if write_revision(&store, KEY, &list, revision)
|
||||
.await
|
||||
.map_err(|e| queue_problem(&e))?
|
||||
.is_some()
|
||||
{
|
||||
tracing::info!(domain = %entry.domain, agent = ?entry.agent, "stopped allowing a domain");
|
||||
return Ok(Json(view(list)));
|
||||
}
|
||||
}
|
||||
Err(queue_problem(&anyhow::anyhow!(
|
||||
"gave up removing {} after {MAX_ATTEMPTS} conflicting writes",
|
||||
entry.domain
|
||||
)))
|
||||
}
|
||||
|
||||
/// The stored list, or `None` when no one has written it.
|
||||
///
|
||||
/// # Errors
|
||||
/// A queue failure.
|
||||
pub(crate) async fn current(client: &async_nats::Client) -> anyhow::Result<Option<AllowList>> {
|
||||
let Some(store) = egress_allow::open(client).await? else {
|
||||
return Ok(None);
|
||||
};
|
||||
let (list, _, _) = read_or_default::<AllowList>(&store, KEY).await?;
|
||||
Ok(Some(list))
|
||||
}
|
||||
|
||||
/// Re-read the list and write `change` of it, retrying a lost write, until it
|
||||
/// is written or `change` leaves it as it is. Answers whether a write landed.
|
||||
///
|
||||
/// A list that was never written is written only when `change` makes it
|
||||
/// non-empty, so a change that adds nothing creates no bucket or key.
|
||||
///
|
||||
/// # Errors
|
||||
/// A queue failure, or `MAX_ATTEMPTS` conflicting writes.
|
||||
pub(crate) async fn modify(
|
||||
client: &async_nats::Client,
|
||||
change: impl Fn(AllowList) -> AllowList,
|
||||
) -> anyhow::Result<bool> {
|
||||
let mut store = egress_allow::open(client).await?;
|
||||
for _ in 0..MAX_ATTEMPTS {
|
||||
let (mut list, revision) = match &store {
|
||||
Some(store) => {
|
||||
let (list, revision, _) = read_or_default::<AllowList>(store, KEY).await?;
|
||||
(list, revision)
|
||||
}
|
||||
None => (AllowList::default(), None),
|
||||
};
|
||||
list.entries.sort();
|
||||
let mut changed = change(list.clone());
|
||||
changed.entries.sort();
|
||||
changed.entries.dedup();
|
||||
if changed == list && (revision.is_some() || changed.entries.is_empty()) {
|
||||
return Ok(false);
|
||||
}
|
||||
if store.is_none() {
|
||||
store = Some(egress_allow::open_or_create(client).await?);
|
||||
}
|
||||
let target = store.as_ref().expect("opened above");
|
||||
if write_revision(target, KEY, &changed, revision)
|
||||
.await?
|
||||
.is_some()
|
||||
{
|
||||
return Ok(true);
|
||||
}
|
||||
}
|
||||
anyhow::bail!("gave up after {MAX_ATTEMPTS} conflicting writes")
|
||||
}
|
||||
|
||||
/// Drop every entry of a destroyed agent, derived and operator-added: a name
|
||||
/// is free again once its agent is destroyed, and the next agent of that name
|
||||
/// would inherit what it left. A failure is logged and does not stop the
|
||||
/// destroy, as in `agent_permissions::clear_on_destroy`.
|
||||
pub(crate) async fn clear_on_destroy(state: &AppState, hive: &str, agent: &str) {
|
||||
let cleared = async {
|
||||
let client = queue(state).map_err(|(_, why)| anyhow::anyhow!(why))?;
|
||||
modify(&client, |mut list| {
|
||||
list.entries.retain(|e| e.agent.as_deref() != Some(agent));
|
||||
list
|
||||
})
|
||||
.await
|
||||
}
|
||||
.await;
|
||||
match cleared {
|
||||
Ok(_) => tracing::info!(hive, agent, "destroyed agent's allowed domains cleared"),
|
||||
Err(e) => tracing::error!(
|
||||
hive,
|
||||
agent,
|
||||
error = %format!("{e:#}"),
|
||||
"clearing this agent's allowed domains FAILED; it was destroyed anyway, so a new \
|
||||
agent of the same name inherits them. Declaring the agent destroyed again re-runs this."
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::agent_limits::tests::{declared, state};
|
||||
use crate::test_nats::TestNats;
|
||||
|
||||
fn entry(domain: &str, agent: Option<&str>) -> AllowedDomain {
|
||||
AllowedDomain {
|
||||
domain: domain.to_owned(),
|
||||
agent: agent.map(str::to_owned),
|
||||
derived: false,
|
||||
}
|
||||
}
|
||||
|
||||
async fn add(
|
||||
state: &AppState,
|
||||
domain: &str,
|
||||
agent: Option<&str>,
|
||||
) -> Result<AllowedDomains, ProblemDetails> {
|
||||
add_allowed_domain(State(state.clone()), Json(entry(domain, agent)))
|
||||
.await
|
||||
.map(|j| j.0)
|
||||
}
|
||||
|
||||
async fn remove(
|
||||
state: &AppState,
|
||||
domain: &str,
|
||||
agent: Option<&str>,
|
||||
) -> Result<AllowedDomains, ProblemDetails> {
|
||||
remove_allowed_domain(State(state.clone()), Json(entry(domain, agent)))
|
||||
.await
|
||||
.map(|j| j.0)
|
||||
}
|
||||
|
||||
async fn listed(state: &AppState) -> Vec<(String, Option<String>)> {
|
||||
get_allowed_domains(State(state.clone()))
|
||||
.await
|
||||
.expect("the list is read")
|
||||
.0
|
||||
.entries
|
||||
.into_iter()
|
||||
.map(|e| (e.domain, e.agent))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The raw value a hive reads, or `None` for no key.
|
||||
async fn published(client: &async_nats::Client) -> Option<String> {
|
||||
egress_allow::open_or_create(client)
|
||||
.await
|
||||
.expect("bucket")
|
||||
.get(KEY)
|
||||
.await
|
||||
.expect("read")
|
||||
.map(|v| String::from_utf8(v.to_vec()).expect("utf-8"))
|
||||
}
|
||||
|
||||
fn base() -> Vec<String> {
|
||||
vec!["api.anthropic.com".to_owned(), ".claude.ai".to_owned()]
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_name_is_stored_normalised_and_an_ip_literal_is_refused() {
|
||||
let stored = checked(&entry(" GitHub.com ", Some("atlas")), &base()).expect("a name");
|
||||
assert_eq!(stored.domain, "github.com");
|
||||
assert_eq!(stored.agent.as_deref(), Some("atlas"));
|
||||
let dotted = checked(&entry(".githubusercontent.com", None), &base()).expect("dot form");
|
||||
assert_eq!(dotted.domain, ".githubusercontent.com");
|
||||
assert_eq!(dotted.agent, None);
|
||||
|
||||
for bad in [
|
||||
"1.2.3.4",
|
||||
"127.0.0.1",
|
||||
"[::1]",
|
||||
"::1",
|
||||
"*.example.com",
|
||||
"localhost",
|
||||
"example.com:443",
|
||||
"example.com\nhttp_access allow all",
|
||||
] {
|
||||
assert!(
|
||||
checked(&entry(bad, None), &base()).is_err(),
|
||||
"{bad:?} was accepted"
|
||||
);
|
||||
}
|
||||
for agent in ["", "At Las", "a/b", "../argus"] {
|
||||
assert!(
|
||||
checked(&entry("github.com", Some(agent)), &base()).is_err(),
|
||||
"agent {agent:?} was accepted"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_name_the_base_list_already_allows_is_refused() {
|
||||
for covered in [
|
||||
"api.anthropic.com",
|
||||
"claude.ai",
|
||||
"a.claude.ai",
|
||||
".claude.ai",
|
||||
] {
|
||||
let why = checked(&entry(covered, None), &base()).expect_err(covered);
|
||||
assert!(why.contains("base list"), "{why}");
|
||||
}
|
||||
// Control: the same names pass when the base list is unknown, and names
|
||||
// next to the base ones are not refused.
|
||||
assert!(checked(&entry("claude.ai", None), &[]).is_ok());
|
||||
for fresh in ["x.api.anthropic.com", ".anthropic.com", "notclaude.ai"] {
|
||||
assert!(checked(&entry(fresh, None), &base()).is_ok(), "{fresh}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Through the real handlers and a real `nats-server`: an entry lands in
|
||||
/// the one value a hive reads, the two scopes of one name are two entries,
|
||||
/// a repeat changes nothing, and a removal takes only the scope it names.
|
||||
///
|
||||
/// The published bytes are pinned literally because hive-c0re's
|
||||
/// `workers::squid_allow` tests decode this same string; a change to either
|
||||
/// side's reading of it fails one of the two.
|
||||
#[tokio::test]
|
||||
async fn the_route_writes_the_list_a_hive_reads_and_each_scope_is_its_own_entry() {
|
||||
let nats = TestNats::start();
|
||||
let client = nats.client().await;
|
||||
let state = declared(&client).await;
|
||||
|
||||
add(&state, "github.com", None).await.expect("swarm-wide");
|
||||
add(&state, "crates.io", Some("atlas"))
|
||||
.await
|
||||
.expect("for atlas");
|
||||
add(&state, "github.com", Some("atlas"))
|
||||
.await
|
||||
.expect("the same name for atlas alone");
|
||||
let before = published(&client).await;
|
||||
add(&state, "GITHUB.com", None).await.expect("a repeat");
|
||||
assert_eq!(published(&client).await, before, "a repeat writes nothing");
|
||||
|
||||
assert_eq!(
|
||||
published(&client).await.as_deref(),
|
||||
Some(
|
||||
r#"{"entries":[{"domain":"crates.io","agent":"atlas"},{"domain":"github.com"},{"domain":"github.com","agent":"atlas"}]}"#
|
||||
)
|
||||
);
|
||||
assert_eq!(
|
||||
listed(&state).await,
|
||||
[
|
||||
("crates.io".to_owned(), Some("atlas".to_owned())),
|
||||
("github.com".to_owned(), None),
|
||||
("github.com".to_owned(), Some("atlas".to_owned())),
|
||||
]
|
||||
);
|
||||
|
||||
remove(&state, "github.com", Some("atlas"))
|
||||
.await
|
||||
.expect("removes atlas's");
|
||||
assert_eq!(
|
||||
listed(&state).await,
|
||||
[
|
||||
("crates.io".to_owned(), Some("atlas".to_owned())),
|
||||
("github.com".to_owned(), None),
|
||||
]
|
||||
);
|
||||
// Removing what is not there is not an error and writes nothing.
|
||||
let before = published(&client).await;
|
||||
remove(&state, "github.com", Some("atlas"))
|
||||
.await
|
||||
.expect("already gone");
|
||||
assert_eq!(published(&client).await, before);
|
||||
|
||||
remove(&state, "github.com", None)
|
||||
.await
|
||||
.expect("swarm-wide");
|
||||
remove(&state, "crates.io", Some("atlas"))
|
||||
.await
|
||||
.expect("atlas's");
|
||||
assert_eq!(
|
||||
published(&client).await.as_deref(),
|
||||
Some(r#"{"entries":[]}"#),
|
||||
"the last removal leaves an empty list"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_full_list_takes_no_new_entry_but_a_present_one_is_not_a_new_one() {
|
||||
let full = AllowList {
|
||||
entries: (0..MAX_ENTRIES)
|
||||
.map(|i| Entry {
|
||||
domain: format!("host{i}.example.com"),
|
||||
agent: None,
|
||||
derived: false,
|
||||
source: None,
|
||||
})
|
||||
.collect(),
|
||||
};
|
||||
let new = Entry {
|
||||
domain: "github.com".to_owned(),
|
||||
agent: None,
|
||||
derived: false,
|
||||
source: None,
|
||||
};
|
||||
let why = added(full.clone(), &new).err().expect("a full list");
|
||||
assert!(why.contains("1000"), "{why}");
|
||||
// Controls: an entry already there is not refused, and one fewer fits.
|
||||
let present = full.entries[0].clone();
|
||||
assert!(matches!(
|
||||
added(full.clone(), &present),
|
||||
Ok(Added::Already(_))
|
||||
));
|
||||
let mut room = full;
|
||||
room.entries.pop();
|
||||
let Ok(Added::Now(list)) = added(room, &new) else {
|
||||
panic!("a list with room takes the entry");
|
||||
};
|
||||
assert_eq!(list.entries.len(), MAX_ENTRIES);
|
||||
}
|
||||
|
||||
/// A read before anything was added answers an empty list and creates no
|
||||
/// bucket.
|
||||
#[tokio::test]
|
||||
async fn a_read_before_any_entry_answers_empty_and_creates_no_bucket() {
|
||||
let nats = TestNats::start();
|
||||
let client = nats.client().await;
|
||||
let state = state(&client);
|
||||
|
||||
assert_eq!(listed(&state).await, []);
|
||||
assert!(
|
||||
egress_allow::open(&client)
|
||||
.await
|
||||
.expect("the queue answers")
|
||||
.is_none()
|
||||
);
|
||||
}
|
||||
|
||||
/// An agent no hive declares gets no entry, so a typo cannot allow a name
|
||||
/// for an agent that does not exist yet; an unscoped add is not asked.
|
||||
#[tokio::test]
|
||||
async fn an_agent_no_hive_declares_is_refused_and_nothing_is_written() {
|
||||
let nats = TestNats::start();
|
||||
let client = nats.client().await;
|
||||
let state = declared(&client).await;
|
||||
|
||||
let problem = add(&state, "github.com", Some("iris"))
|
||||
.await
|
||||
.expect_err("no hive declares iris");
|
||||
assert_eq!(problem.status, Some(StatusCode::BAD_REQUEST), "{problem:?}");
|
||||
assert_eq!(published(&client).await, None);
|
||||
add(&state, "github.com", Some("atlas"))
|
||||
.await
|
||||
.expect("control: a declared agent is accepted");
|
||||
}
|
||||
|
||||
async fn post_raw(app: &axum::Router, body: &'static str) -> StatusCode {
|
||||
use tower::ServiceExt as _;
|
||||
app.clone()
|
||||
.oneshot(
|
||||
axum::http::Request::post("/api/egress/allowed-domains")
|
||||
.header(axum::http::header::CONTENT_TYPE, "application/json")
|
||||
.body(axum::body::Body::from(body))
|
||||
.expect("request"),
|
||||
)
|
||||
.await
|
||||
.expect("router answers")
|
||||
.status()
|
||||
}
|
||||
|
||||
/// Through the real router: an IP literal or a wildcard is a 400 and
|
||||
/// writes nothing, an unknown field a 422, and the well-formed body after
|
||||
/// them is the control that the same route reaches the bucket.
|
||||
#[tokio::test]
|
||||
async fn the_router_refuses_an_ip_literal_and_a_wildcard_before_the_queue() {
|
||||
let nats = TestNats::start();
|
||||
let client = nats.client().await;
|
||||
let app = crate::startup::build_app(declared(&client).await);
|
||||
|
||||
for body in [
|
||||
r#"{"domain":"1.2.3.4"}"#,
|
||||
r#"{"domain":"10.0.0.1","agent":"atlas"}"#,
|
||||
r#"{"domain":"*.example.com"}"#,
|
||||
r#"{"domain":"[::1]"}"#,
|
||||
r#"{"domain":""}"#,
|
||||
] {
|
||||
assert_eq!(
|
||||
post_raw(&app, body).await,
|
||||
StatusCode::BAD_REQUEST,
|
||||
"{body}"
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
post_raw(&app, r#"{"domain":"github.com","hive":"pr1ma"}"#).await,
|
||||
StatusCode::UNPROCESSABLE_ENTITY
|
||||
);
|
||||
assert_eq!(published(&client).await, None);
|
||||
|
||||
assert_eq!(
|
||||
post_raw(&app, r#"{"domain":"github.com"}"#).await,
|
||||
StatusCode::OK
|
||||
);
|
||||
assert_eq!(
|
||||
published(&client).await.as_deref(),
|
||||
Some(r#"{"entries":[{"domain":"github.com"}]}"#)
|
||||
);
|
||||
}
|
||||
}
|
||||
755
swarm-controller/src/secrets/egress_deny.rs
Normal file
755
swarm-controller/src/secrets/egress_deny.rs
Normal file
|
|
@ -0,0 +1,755 @@
|
|||
//! `/api/egress/denied-domains` — the destinations the swarm refuses agents
|
||||
//! through their hive's egress proxy, whatever else allows them.
|
||||
//!
|
||||
//! The list is one value under the `deny` key of the `egress-allow` bucket
|
||||
//! (`swarm_wire::egress_allow`), which this daemon alone writes, beside the
|
||||
//! allow-list's key. Every hive reads it and renders the entries for the agents
|
||||
//! it runs: a swarm-wide entry is refused for everyone, an entry with an agent
|
||||
//! for that agent alone. The proxy checks the list before any allow rule, so an
|
||||
//! entry beats the base list, the hive's own names, the allow-list, the
|
||||
//! unrestricted flag and `log` mode alike, and an agent's entry can only add to
|
||||
//! the swarm-wide ones.
|
||||
//!
|
||||
//! Only an operator's request writes an entry. There is no derived entry: the
|
||||
//! stored type has no `derived` field, and nothing in this daemon reads an
|
||||
//! agent's environment or a linked account into this list.
|
||||
//!
|
||||
//! Each name goes into the proxy's configuration, so it is checked with
|
||||
//! `swarm_wire::egress_allow::normalize_domain` here and again by the hive.
|
||||
//! The base list is not consulted: refusing a name the proxy otherwise always
|
||||
//! allows is the point of the list.
|
||||
//!
|
||||
//! A hive reports the revision of the list it rendered in its status snapshot
|
||||
//! (`swarm_wire::hive_status::EGRESS_DENY_APPLIED`); [`behind`] names the hives
|
||||
//! whose report does not match, which the reads show as `behind`.
|
||||
|
||||
use axum::Json;
|
||||
use axum::extract::State;
|
||||
use axum::http::StatusCode;
|
||||
use problem_details::ProblemDetails;
|
||||
use swarm_controller_api::egress::{DeniedDomain, DeniedDomains};
|
||||
use swarm_queue_client::egress_allow;
|
||||
use swarm_wire::egress_allow::{DENY_KEY, DenyEntry, DenyList, MAX_ENTRIES, normalize_domain};
|
||||
use swarm_wire::hive_status::egress_deny_applied;
|
||||
|
||||
use crate::routes::{AppState, error_problem, wanted_error_status};
|
||||
use crate::schedules::{live, queue, read_or_default, refused, write_revision};
|
||||
use crate::status::{Freshness, HiveStatus};
|
||||
|
||||
/// How many times a losing writer re-reads and re-applies, as in
|
||||
/// `egress_allow::MAX_ATTEMPTS`.
|
||||
const MAX_ATTEMPTS: usize = 5;
|
||||
|
||||
/// The entry to store for `req`, or why it is refused.
|
||||
pub(crate) fn checked(req: &DeniedDomain) -> Result<DenyEntry, String> {
|
||||
let domain = normalize_domain(&req.domain)?;
|
||||
let agent = req
|
||||
.agent
|
||||
.as_deref()
|
||||
.map(|a| {
|
||||
hive_types::Ident::parse(a)
|
||||
.map(hive_types::Ident::into_string)
|
||||
.map_err(|reason| format!("agent {a:?}: {reason}"))
|
||||
})
|
||||
.transpose()?;
|
||||
Ok(DenyEntry { domain, agent })
|
||||
}
|
||||
|
||||
/// The hives among `rows` whose proxy is not known to refuse the list at
|
||||
/// `revision` yet.
|
||||
///
|
||||
/// A hive that reports a revision is behind when it differs. A hive that
|
||||
/// reports none (it predates the field, has not read the list, or has never
|
||||
/// reported) is behind only while the list holds an entry: it cannot be
|
||||
/// enforcing a name it was never told, but an empty list asks nothing of it.
|
||||
/// A hive the roster does not list is left out.
|
||||
pub(crate) fn behind(rows: &[HiveStatus], revision: u64, list_is_empty: bool) -> Vec<String> {
|
||||
rows.iter()
|
||||
.filter(|row| row.freshness != Freshness::Unknown)
|
||||
.filter(
|
||||
|row| match row.snapshot.as_ref().and_then(egress_deny_applied) {
|
||||
Some(applied) => applied != revision,
|
||||
None => !list_is_empty,
|
||||
},
|
||||
)
|
||||
.map(|row| row.name.clone())
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The list as the API answers it.
|
||||
fn view(list: DenyList, revision: u64, behind: Vec<String>) -> DeniedDomains {
|
||||
let mut entries = list.entries;
|
||||
entries.sort();
|
||||
DeniedDomains {
|
||||
entries: entries
|
||||
.into_iter()
|
||||
.map(|e| DeniedDomain {
|
||||
domain: e.domain,
|
||||
agent: e.agent,
|
||||
})
|
||||
.collect(),
|
||||
revision,
|
||||
behind,
|
||||
}
|
||||
}
|
||||
|
||||
/// Which hives are behind `list` at `revision`. A status read that fails names
|
||||
/// every hive, since nothing then confirms any.
|
||||
async fn behind_hives(state: &AppState, revision: u64, list: &DenyList) -> Vec<String> {
|
||||
let Some(reader) = state.status.as_ref() else {
|
||||
return Vec::new();
|
||||
};
|
||||
match reader
|
||||
.view(&state.hives, std::time::SystemTime::now())
|
||||
.await
|
||||
{
|
||||
Ok(rows) => behind(&rows, revision, list.entries.is_empty()),
|
||||
Err(e) => {
|
||||
tracing::warn!(error = %format!("{e:#}"), "egress deny list: reading the hives' status failed");
|
||||
state.hives.iter().map(|h| h.name.clone()).collect()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn queue_problem(e: &anyhow::Error) -> ProblemDetails {
|
||||
tracing::warn!(error = %format!("{e:#}"), "egress deny list: queue failure");
|
||||
error_problem(wanted_error_status(e), &format!("{e:#}"))
|
||||
}
|
||||
|
||||
async fn open_or_create(
|
||||
client: &async_nats::Client,
|
||||
) -> Result<async_nats::jetstream::kv::Store, ProblemDetails> {
|
||||
egress_allow::open_or_create(client)
|
||||
.await
|
||||
.map_err(|e| queue_problem(&anyhow::Error::new(e)))
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
get,
|
||||
path = "/api/egress/denied-domains",
|
||||
responses(
|
||||
(status = 200, description = "every entry, swarm-wide and per agent, sorted, the \
|
||||
stored revision, and the hives that have not reported rendering it; empty when \
|
||||
the swarm has not set a list",
|
||||
body = DeniedDomains),
|
||||
(status = 503, description = "no swarm queue is configured on this host, or it is \
|
||||
not connected (problem+json)", body = String),
|
||||
(status = 500, description = "the list could not be read (problem+json)",
|
||||
body = String),
|
||||
),
|
||||
tag = "egress"
|
||||
)]
|
||||
pub(crate) async fn get_denied_domains(
|
||||
State(state): State<AppState>,
|
||||
) -> Result<Json<DeniedDomains>, ProblemDetails> {
|
||||
let client = queue(&state).map_err(refused)?;
|
||||
let Some(store) = egress_allow::open(&client)
|
||||
.await
|
||||
.map_err(|e| queue_problem(&anyhow::Error::new(e)))?
|
||||
else {
|
||||
return Ok(Json(DeniedDomains::default()));
|
||||
};
|
||||
let (list, revision, _) = read_or_default::<DenyList>(&store, DENY_KEY)
|
||||
.await
|
||||
.map_err(|e| queue_problem(&e))?;
|
||||
let revision = revision.unwrap_or(0);
|
||||
let behind = behind_hives(&state, revision, &list).await;
|
||||
Ok(Json(view(list, revision, behind)))
|
||||
}
|
||||
|
||||
/// What changing a list came to.
|
||||
enum Changed {
|
||||
/// Nothing to write.
|
||||
Same(DenyList, u64),
|
||||
/// The list to write.
|
||||
New(DenyList),
|
||||
}
|
||||
|
||||
/// `list` with `entry` added, or why it can't take another entry.
|
||||
fn added(mut list: DenyList, entry: &DenyEntry, revision: u64) -> Result<Changed, String> {
|
||||
if list.entries.contains(entry) {
|
||||
return Ok(Changed::Same(list, revision));
|
||||
}
|
||||
if list.entries.len() >= MAX_ENTRIES {
|
||||
return Err(format!(
|
||||
"the list holds {MAX_ENTRIES} entries, which is the most it takes"
|
||||
));
|
||||
}
|
||||
list.entries.push(entry.clone());
|
||||
list.entries.sort();
|
||||
Ok(Changed::New(list))
|
||||
}
|
||||
|
||||
/// `list` without `entry`.
|
||||
fn removed(mut list: DenyList, entry: &DenyEntry, revision: u64) -> Changed {
|
||||
if !list.entries.contains(entry) {
|
||||
return Changed::Same(list, revision);
|
||||
}
|
||||
list.entries.retain(|e| e != entry);
|
||||
Changed::New(list)
|
||||
}
|
||||
|
||||
/// Re-read the list and write `change` of it, retrying a lost write, and answer
|
||||
/// the list as it stands after.
|
||||
async fn apply(
|
||||
state: &AppState,
|
||||
client: &async_nats::Client,
|
||||
what: &str,
|
||||
change: impl Fn(DenyList, u64) -> Result<Changed, String>,
|
||||
) -> Result<Json<DeniedDomains>, ProblemDetails> {
|
||||
let store = open_or_create(client).await?;
|
||||
for _ in 0..MAX_ATTEMPTS {
|
||||
let (list, revision, _) = read_or_default::<DenyList>(&store, DENY_KEY)
|
||||
.await
|
||||
.map_err(|e| queue_problem(&e))?;
|
||||
let list = match change(list, revision.unwrap_or(0)) {
|
||||
Ok(Changed::Same(list, revision)) => {
|
||||
let behind = behind_hives(state, revision, &list).await;
|
||||
return Ok(Json(view(list, revision, behind)));
|
||||
}
|
||||
Ok(Changed::New(list)) => list,
|
||||
Err(why) => return Err(error_problem(StatusCode::BAD_REQUEST, &why)),
|
||||
};
|
||||
if let Some(written) = write_revision(&store, DENY_KEY, &list, revision)
|
||||
.await
|
||||
.map_err(|e| queue_problem(&e))?
|
||||
{
|
||||
tracing::info!(domain = %what, revision = written, "changed the egress deny list");
|
||||
let behind = behind_hives(state, written, &list).await;
|
||||
return Ok(Json(view(list, written, behind)));
|
||||
}
|
||||
}
|
||||
Err(queue_problem(&anyhow::anyhow!(
|
||||
"gave up changing {what} after {MAX_ATTEMPTS} conflicting writes"
|
||||
)))
|
||||
}
|
||||
|
||||
/// Refuse one destination, for every agent or for one.
|
||||
///
|
||||
/// Adding an entry that is already there changes nothing. The entry is
|
||||
/// refused before any allow rule on every hive that has taken the list.
|
||||
#[utoipa::path(
|
||||
post,
|
||||
path = "/api/egress/denied-domains",
|
||||
request_body = DeniedDomain,
|
||||
responses(
|
||||
(status = 200, description = "the whole list after the add", body = DeniedDomains),
|
||||
(status = 400, description = "the domain is not a DNS name (an IP address, a \
|
||||
wildcard, a single label and a port are refused), the agent is not an \
|
||||
identifier or not declared on any hive, or the list is full (problem+json)",
|
||||
body = String),
|
||||
(status = 422, description = "an unknown field"),
|
||||
(status = 503, description = "no swarm queue is configured on this host, or it is \
|
||||
not connected (problem+json)", body = String),
|
||||
(status = 500, description = "the list could not be written (problem+json)",
|
||||
body = String),
|
||||
),
|
||||
tag = "egress"
|
||||
)]
|
||||
pub(crate) async fn add_denied_domain(
|
||||
State(state): State<AppState>,
|
||||
Json(req): Json<DeniedDomain>,
|
||||
) -> Result<Json<DeniedDomains>, ProblemDetails> {
|
||||
let entry = checked(&req).map_err(|why| error_problem(StatusCode::BAD_REQUEST, &why))?;
|
||||
let client = queue(&state).map_err(refused)?;
|
||||
if let Some(agent) = &entry.agent
|
||||
&& !live(&state).await?.contains(agent)
|
||||
{
|
||||
return Err(error_problem(
|
||||
StatusCode::BAD_REQUEST,
|
||||
&format!("no hive's wanted state declares an agent {agent:?} that is not destroyed"),
|
||||
));
|
||||
}
|
||||
apply(&state, &client, &entry.domain, |list, revision| {
|
||||
added(list, &entry, revision)
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// Stop refusing one destination for the scope it was added with.
|
||||
///
|
||||
/// Removing an entry that is not there changes nothing. A swarm-wide entry is
|
||||
/// removed only by naming it without an agent: removing an agent's entry for
|
||||
/// the same name leaves it refused for everyone.
|
||||
#[utoipa::path(
|
||||
delete,
|
||||
path = "/api/egress/denied-domains",
|
||||
request_body = DeniedDomain,
|
||||
responses(
|
||||
(status = 200, description = "the whole list after the removal", body = DeniedDomains),
|
||||
(status = 400, description = "the domain is not a DNS name, or the agent is not an \
|
||||
identifier (problem+json)", body = String),
|
||||
(status = 422, description = "an unknown field"),
|
||||
(status = 503, description = "no swarm queue is configured on this host, or it is \
|
||||
not connected (problem+json)", body = String),
|
||||
(status = 500, description = "the list could not be written (problem+json)",
|
||||
body = String),
|
||||
),
|
||||
tag = "egress"
|
||||
)]
|
||||
pub(crate) async fn remove_denied_domain(
|
||||
State(state): State<AppState>,
|
||||
Json(req): Json<DeniedDomain>,
|
||||
) -> Result<Json<DeniedDomains>, ProblemDetails> {
|
||||
let entry = checked(&req).map_err(|why| error_problem(StatusCode::BAD_REQUEST, &why))?;
|
||||
let client = queue(&state).map_err(refused)?;
|
||||
apply(&state, &client, &entry.domain, |list, revision| {
|
||||
Ok(removed(list, &entry, revision))
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// Drop every entry of a destroyed agent: a name is free again once its agent
|
||||
/// is destroyed, and the next agent of that name would inherit what it left. A
|
||||
/// list that was never written stays unwritten. A failure is logged and does
|
||||
/// not stop the destroy, as in `egress_allow::clear_on_destroy`.
|
||||
pub(crate) async fn clear_on_destroy(state: &AppState, hive: &str, agent: &str) {
|
||||
let cleared = async {
|
||||
let client = queue(state).map_err(|(_, why)| anyhow::anyhow!(why))?;
|
||||
let Some(store) = egress_allow::open(&client).await? else {
|
||||
return Ok(());
|
||||
};
|
||||
for _ in 0..MAX_ATTEMPTS {
|
||||
let (mut list, revision, _) = read_or_default::<DenyList>(&store, DENY_KEY).await?;
|
||||
let before = list.entries.len();
|
||||
list.entries.retain(|e| e.agent.as_deref() != Some(agent));
|
||||
if list.entries.len() == before {
|
||||
return Ok(());
|
||||
}
|
||||
if write_revision(&store, DENY_KEY, &list, revision)
|
||||
.await?
|
||||
.is_some()
|
||||
{
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
anyhow::bail!("gave up after {MAX_ATTEMPTS} conflicting writes")
|
||||
}
|
||||
.await;
|
||||
match cleared {
|
||||
Ok(()) => tracing::info!(hive, agent, "destroyed agent's denied domains cleared"),
|
||||
Err(e) => tracing::error!(
|
||||
hive,
|
||||
agent,
|
||||
error = %format!("{e:#}"),
|
||||
"clearing this agent's denied domains FAILED; it was destroyed anyway, so a new \
|
||||
agent of the same name inherits them. Declaring the agent destroyed again re-runs this."
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::agent_limits::tests::{declared, state};
|
||||
use crate::test_nats::TestNats;
|
||||
use swarm_wire::hive_status::EGRESS_DENY_APPLIED;
|
||||
|
||||
fn entry(domain: &str, agent: Option<&str>) -> DeniedDomain {
|
||||
DeniedDomain {
|
||||
domain: domain.to_owned(),
|
||||
agent: agent.map(str::to_owned),
|
||||
}
|
||||
}
|
||||
|
||||
async fn add(
|
||||
state: &AppState,
|
||||
domain: &str,
|
||||
agent: Option<&str>,
|
||||
) -> Result<DeniedDomains, ProblemDetails> {
|
||||
add_denied_domain(State(state.clone()), Json(entry(domain, agent)))
|
||||
.await
|
||||
.map(|j| j.0)
|
||||
}
|
||||
|
||||
async fn remove(
|
||||
state: &AppState,
|
||||
domain: &str,
|
||||
agent: Option<&str>,
|
||||
) -> Result<DeniedDomains, ProblemDetails> {
|
||||
remove_denied_domain(State(state.clone()), Json(entry(domain, agent)))
|
||||
.await
|
||||
.map(|j| j.0)
|
||||
}
|
||||
|
||||
async fn read(state: &AppState) -> DeniedDomains {
|
||||
get_denied_domains(State(state.clone()))
|
||||
.await
|
||||
.expect("the list is read")
|
||||
.0
|
||||
}
|
||||
|
||||
async fn listed(state: &AppState) -> Vec<(String, Option<String>)> {
|
||||
read(state)
|
||||
.await
|
||||
.entries
|
||||
.into_iter()
|
||||
.map(|e| (e.domain, e.agent))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The raw value a hive reads under `key`, or `None` for no key.
|
||||
async fn published(client: &async_nats::Client, key: &str) -> Option<String> {
|
||||
egress_allow::open_or_create(client)
|
||||
.await
|
||||
.expect("bucket")
|
||||
.get(key)
|
||||
.await
|
||||
.expect("read")
|
||||
.map(|v| String::from_utf8(v.to_vec()).expect("utf-8"))
|
||||
}
|
||||
|
||||
fn row(name: &str, freshness: Freshness, applied: Option<u64>) -> HiveStatus {
|
||||
HiveStatus {
|
||||
name: name.to_owned(),
|
||||
domain: None,
|
||||
dashboard: None,
|
||||
freshness,
|
||||
last_seen_unix: None,
|
||||
age_seconds: None,
|
||||
snapshot: applied.map(|r| serde_json::json!({ EGRESS_DENY_APPLIED: r })),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_name_is_stored_normalised_and_an_ip_literal_is_refused() {
|
||||
let stored = checked(&entry(" Evil.COM ", Some("atlas"))).expect("a name");
|
||||
assert_eq!(stored.domain, "evil.com");
|
||||
assert_eq!(stored.agent.as_deref(), Some("atlas"));
|
||||
let dotted = checked(&entry(".evil.com", None)).expect("dot form");
|
||||
assert_eq!(dotted.domain, ".evil.com");
|
||||
|
||||
for bad in [
|
||||
"1.2.3.4",
|
||||
"[::1]",
|
||||
"*.example.com",
|
||||
"localhost",
|
||||
"example.com:443",
|
||||
"example.com\nhttp_access allow all",
|
||||
] {
|
||||
assert!(checked(&entry(bad, None)).is_err(), "{bad:?} was accepted");
|
||||
}
|
||||
for agent in ["", "At Las", "a/b", "../argus"] {
|
||||
assert!(
|
||||
checked(&entry("evil.com", Some(agent))).is_err(),
|
||||
"agent {agent:?} was accepted"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// The base list is no reason to refuse a deny: denying a name that is
|
||||
/// otherwise always allowed is what the list is for.
|
||||
#[tokio::test]
|
||||
async fn a_name_the_base_list_allows_can_be_denied() {
|
||||
let nats = TestNats::start();
|
||||
let client = nats.client().await;
|
||||
let state = state(&client);
|
||||
// Control: the allow list's own check refuses this name.
|
||||
assert!(
|
||||
crate::egress_allow::checked(
|
||||
&swarm_controller_api::egress::AllowedDomain {
|
||||
domain: "api.anthropic.com".to_owned(),
|
||||
agent: None,
|
||||
derived: false,
|
||||
},
|
||||
&["api.anthropic.com".to_owned()],
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
add(&state, "api.anthropic.com", None)
|
||||
.await
|
||||
.expect("denied despite the base list");
|
||||
}
|
||||
|
||||
/// Through the real handlers and a real `nats-server`: an entry lands under
|
||||
/// the deny key a hive reads and never under the allow key, the two scopes
|
||||
/// of one name are two entries, a repeat writes nothing, and removing an
|
||||
/// agent's entry leaves the swarm-wide one in force.
|
||||
///
|
||||
/// The published bytes are pinned literally because hive-c0re's
|
||||
/// `workers::squid_deny` tests decode this same string.
|
||||
#[tokio::test]
|
||||
async fn the_route_writes_the_list_a_hive_reads_and_a_scoped_removal_never_lifts_the_swarm_wide_entry()
|
||||
{
|
||||
let nats = TestNats::start();
|
||||
let client = nats.client().await;
|
||||
let state = declared(&client).await;
|
||||
|
||||
add(&state, "evil.com", None).await.expect("swarm-wide");
|
||||
add(&state, "bad.io", Some("atlas")).await.expect("atlas's");
|
||||
add(&state, "evil.com", Some("atlas"))
|
||||
.await
|
||||
.expect("the same name for atlas alone");
|
||||
let before = published(&client, DENY_KEY).await;
|
||||
add(&state, "EVIL.com", None).await.expect("a repeat");
|
||||
assert_eq!(
|
||||
published(&client, DENY_KEY).await,
|
||||
before,
|
||||
"a repeat writes nothing"
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
published(&client, DENY_KEY).await.as_deref(),
|
||||
Some(
|
||||
r#"{"entries":[{"domain":"bad.io","agent":"atlas"},{"domain":"evil.com"},{"domain":"evil.com","agent":"atlas"}]}"#
|
||||
)
|
||||
);
|
||||
assert_eq!(
|
||||
published(&client, swarm_wire::egress_allow::KEY).await,
|
||||
None,
|
||||
"a deny is not an allow entry"
|
||||
);
|
||||
|
||||
remove(&state, "evil.com", Some("atlas"))
|
||||
.await
|
||||
.expect("removes atlas's");
|
||||
assert_eq!(
|
||||
listed(&state).await,
|
||||
[
|
||||
("bad.io".to_owned(), Some("atlas".to_owned())),
|
||||
("evil.com".to_owned(), None),
|
||||
],
|
||||
"the swarm-wide deny stays after atlas's is removed"
|
||||
);
|
||||
let before = published(&client, DENY_KEY).await;
|
||||
remove(&state, "evil.com", Some("atlas"))
|
||||
.await
|
||||
.expect("already gone");
|
||||
assert_eq!(published(&client, DENY_KEY).await, before);
|
||||
|
||||
remove(&state, "evil.com", None).await.expect("swarm-wide");
|
||||
remove(&state, "bad.io", Some("atlas"))
|
||||
.await
|
||||
.expect("atlas's");
|
||||
assert_eq!(
|
||||
published(&client, DENY_KEY).await.as_deref(),
|
||||
Some(r#"{"entries":[]}"#),
|
||||
"the last removal leaves an empty list"
|
||||
);
|
||||
}
|
||||
|
||||
/// An allow-list write leaves the deny list alone and the other way round.
|
||||
#[tokio::test]
|
||||
async fn the_allow_list_and_the_deny_list_are_separate_values() {
|
||||
let nats = TestNats::start();
|
||||
let client = nats.client().await;
|
||||
let state = declared(&client).await;
|
||||
|
||||
add(&state, "evil.com", None).await.expect("a deny");
|
||||
let allowed = crate::egress_allow::add_allowed_domain(
|
||||
State(state.clone()),
|
||||
Json(swarm_controller_api::egress::AllowedDomain {
|
||||
domain: "github.com".to_owned(),
|
||||
agent: None,
|
||||
derived: false,
|
||||
}),
|
||||
)
|
||||
.await
|
||||
.expect("an allow");
|
||||
assert_eq!(allowed.0.entries.len(), 1);
|
||||
assert_eq!(
|
||||
published(&client, DENY_KEY).await.as_deref(),
|
||||
Some(r#"{"entries":[{"domain":"evil.com"}]}"#)
|
||||
);
|
||||
assert_eq!(
|
||||
published(&client, swarm_wire::egress_allow::KEY)
|
||||
.await
|
||||
.as_deref(),
|
||||
Some(r#"{"entries":[{"domain":"github.com"}]}"#)
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_read_before_any_entry_answers_empty_and_creates_no_bucket() {
|
||||
let nats = TestNats::start();
|
||||
let client = nats.client().await;
|
||||
let state = state(&client);
|
||||
|
||||
let read = read(&state).await;
|
||||
assert!(read.entries.is_empty() && read.revision == 0 && read.behind.is_empty());
|
||||
assert!(
|
||||
egress_allow::open(&client)
|
||||
.await
|
||||
.expect("the queue answers")
|
||||
.is_none()
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn an_agent_no_hive_declares_is_refused_and_nothing_is_written() {
|
||||
let nats = TestNats::start();
|
||||
let client = nats.client().await;
|
||||
let state = declared(&client).await;
|
||||
|
||||
let problem = add(&state, "evil.com", Some("iris"))
|
||||
.await
|
||||
.expect_err("no hive declares iris");
|
||||
assert_eq!(problem.status, Some(StatusCode::BAD_REQUEST), "{problem:?}");
|
||||
assert_eq!(published(&client, DENY_KEY).await, None);
|
||||
add(&state, "evil.com", Some("atlas"))
|
||||
.await
|
||||
.expect("control: a declared agent is accepted");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_full_list_takes_no_new_entry_but_a_present_one_is_not_a_new_one() {
|
||||
let full = DenyList {
|
||||
entries: (0..MAX_ENTRIES)
|
||||
.map(|i| DenyEntry {
|
||||
domain: format!("host{i}.example.com"),
|
||||
agent: None,
|
||||
})
|
||||
.collect(),
|
||||
};
|
||||
let new = DenyEntry {
|
||||
domain: "evil.com".to_owned(),
|
||||
agent: None,
|
||||
};
|
||||
let why = added(full.clone(), &new, 1).err().expect("a full list");
|
||||
assert!(why.contains("1000"), "{why}");
|
||||
let present = full.entries[0].clone();
|
||||
assert!(matches!(
|
||||
added(full.clone(), &present, 1),
|
||||
Ok(Changed::Same(..))
|
||||
));
|
||||
let mut room = full;
|
||||
room.entries.pop();
|
||||
let Ok(Changed::New(list)) = added(room, &new, 1) else {
|
||||
panic!("a list with room takes the entry");
|
||||
};
|
||||
assert_eq!(list.entries.len(), MAX_ENTRIES);
|
||||
}
|
||||
|
||||
/// A hive is behind unless it reports the list's revision; one that reports
|
||||
/// nothing is behind only while the list asks something of it.
|
||||
#[test]
|
||||
fn a_hive_is_behind_unless_it_reports_the_revision_it_should_have() {
|
||||
let rows = [
|
||||
row("current", Freshness::Fresh, Some(7)),
|
||||
row("older", Freshness::Fresh, Some(5)),
|
||||
row("silent-old", Freshness::Fresh, None),
|
||||
row("never", Freshness::NeverReported, None),
|
||||
row("stale-current", Freshness::Stale, Some(7)),
|
||||
row("stranger", Freshness::Unknown, None),
|
||||
];
|
||||
assert_eq!(behind(&rows, 7, false), ["older", "silent-old", "never"]);
|
||||
// An empty list asks nothing of a hive that reports nothing, but a hive
|
||||
// that reports a different revision still holds names the list dropped.
|
||||
assert_eq!(behind(&rows, 7, true), ["older"]);
|
||||
assert_eq!(
|
||||
behind(&rows, 0, true),
|
||||
["current", "older", "stale-current"]
|
||||
);
|
||||
}
|
||||
|
||||
/// Through the status bucket: after an add every hive is behind until it
|
||||
/// publishes the revision the add answered.
|
||||
#[tokio::test]
|
||||
async fn a_hive_leaves_behind_when_its_snapshot_carries_the_revision() {
|
||||
let nats = TestNats::start();
|
||||
let client = nats.client().await;
|
||||
let state = declared(&client).await;
|
||||
|
||||
let added = add(&state, "evil.com", None).await.expect("a deny");
|
||||
assert!(added.revision > 0);
|
||||
assert_eq!(added.behind, ["pr1ma"], "it has not reported");
|
||||
|
||||
let status = swarm_queue_client::status::open_or_create(&client)
|
||||
.await
|
||||
.expect("status bucket");
|
||||
let publish = |applied: u64| {
|
||||
let body = serde_json::json!({
|
||||
"status": "ok", "warnings": [], EGRESS_DENY_APPLIED: applied
|
||||
});
|
||||
let status = status.clone();
|
||||
async move {
|
||||
status
|
||||
.put("pr1ma", body.to_string().into())
|
||||
.await
|
||||
.expect("publish");
|
||||
}
|
||||
};
|
||||
publish(added.revision - 1).await;
|
||||
assert_eq!(read(&state).await.behind, ["pr1ma"], "an older revision");
|
||||
publish(added.revision).await;
|
||||
let now = read(&state).await;
|
||||
assert_eq!(now.revision, added.revision);
|
||||
assert!(now.behind.is_empty(), "{:?}", now.behind);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn destroying_an_agent_drops_its_denies_and_keeps_the_rest() {
|
||||
let nats = TestNats::start();
|
||||
let client = nats.client().await;
|
||||
let state = declared(&client).await;
|
||||
add(&state, "evil.com", None).await.expect("swarm-wide");
|
||||
add(&state, "bad.io", Some("atlas")).await.expect("atlas's");
|
||||
|
||||
clear_on_destroy(&state, "pr1ma", "atlas").await;
|
||||
assert_eq!(listed(&state).await, [("evil.com".to_owned(), None)]);
|
||||
}
|
||||
|
||||
async fn call(app: &axum::Router, method: &str, body: &'static str, path: &str) -> StatusCode {
|
||||
use tower::ServiceExt as _;
|
||||
app.clone()
|
||||
.oneshot(
|
||||
axum::http::Request::builder()
|
||||
.method(method)
|
||||
.uri(path)
|
||||
.header(axum::http::header::CONTENT_TYPE, "application/json")
|
||||
.body(axum::body::Body::from(body))
|
||||
.expect("request"),
|
||||
)
|
||||
.await
|
||||
.expect("router answers")
|
||||
.status()
|
||||
}
|
||||
|
||||
/// Through the real router: an IP literal or a wildcard is a 400 and writes
|
||||
/// nothing, an unknown field (a `derived` flag included) a 422, and the
|
||||
/// well-formed body after them is the control that the route reaches the
|
||||
/// deny key.
|
||||
#[tokio::test]
|
||||
async fn the_router_refuses_bad_names_and_a_derived_flag_before_the_queue() {
|
||||
let nats = TestNats::start();
|
||||
let client = nats.client().await;
|
||||
let app = crate::startup::build_app(declared(&client).await);
|
||||
let path = "/api/egress/denied-domains";
|
||||
|
||||
for body in [
|
||||
r#"{"domain":"1.2.3.4"}"#,
|
||||
r#"{"domain":"*.example.com"}"#,
|
||||
r#"{"domain":""}"#,
|
||||
] {
|
||||
assert_eq!(
|
||||
call(&app, "POST", body, path).await,
|
||||
StatusCode::BAD_REQUEST,
|
||||
"{body}"
|
||||
);
|
||||
}
|
||||
for body in [
|
||||
r#"{"domain":"evil.com","derived":true}"#,
|
||||
r#"{"domain":"evil.com","hive":"pr1ma"}"#,
|
||||
] {
|
||||
assert_eq!(
|
||||
call(&app, "POST", body, path).await,
|
||||
StatusCode::UNPROCESSABLE_ENTITY,
|
||||
"{body}"
|
||||
);
|
||||
}
|
||||
assert_eq!(published(&client, DENY_KEY).await, None);
|
||||
|
||||
assert_eq!(
|
||||
call(&app, "POST", r#"{"domain":"evil.com"}"#, path).await,
|
||||
StatusCode::OK
|
||||
);
|
||||
assert_eq!(
|
||||
published(&client, DENY_KEY).await.as_deref(),
|
||||
Some(r#"{"entries":[{"domain":"evil.com"}]}"#)
|
||||
);
|
||||
assert_eq!(
|
||||
call(&app, "DELETE", r#"{"domain":"evil.com"}"#, path).await,
|
||||
StatusCode::OK
|
||||
);
|
||||
}
|
||||
}
|
||||
18
swarm-controller/src/secrets/mod.rs
Normal file
18
swarm-controller/src/secrets/mod.rs
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
//! The secrets concern: agent identities and their renewal and cutoff, the
|
||||
//! credentials the controller hands out (archive, proxy, backend) and the
|
||||
//! egress and read policies written to the store.
|
||||
|
||||
pub(crate) mod agent_cutoff;
|
||||
pub(crate) mod agent_entity;
|
||||
pub(crate) mod agent_identity;
|
||||
pub(crate) mod agent_renewal;
|
||||
pub(crate) mod agent_role_ttl;
|
||||
pub(crate) mod archive_access;
|
||||
pub(crate) mod backend_egress;
|
||||
pub(crate) mod backend_env;
|
||||
pub(crate) mod backend_secrets;
|
||||
pub(crate) mod claude_login;
|
||||
pub(crate) mod egress_allow;
|
||||
pub(crate) mod egress_deny;
|
||||
pub(crate) mod proxy_credential;
|
||||
pub(crate) mod read_policy;
|
||||
325
swarm-controller/src/secrets/proxy_credential.rs
Normal file
325
swarm-controller/src/secrets/proxy_credential.rs
Normal file
|
|
@ -0,0 +1,325 @@
|
|||
//! The credentials squid authenticates its clients with: one per agent, at
|
||||
//! `swarm_secret_client::proxy::agent_credential_path`, and one per hive for
|
||||
//! that hive's squid self-check, at `proxy::selfcheck_path`.
|
||||
//!
|
||||
//! Minted here because the agent's store policy is read-only and a hive's
|
||||
//! policy cannot create under another principal's prefix. [`spawn`]'s pass runs
|
||||
//! at start and every [`RECONCILE_INTERVAL`] over every agent that holds a store
|
||||
//! identity, so an agent that existed before this pass was added gets one on the
|
||||
//! next tick, with no restart.
|
||||
//!
|
||||
//! ⚠️ **Never replaced.** A path that holds anything is left alone, and the write
|
||||
//! is a `cas=0` create. Replacing a credential is a rotation: squid's users file
|
||||
//! is rendered from whatever the store holds, and a rotation has to reach every
|
||||
//! client that carries the old one in the same step.
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
use serde::de::IgnoredAny;
|
||||
use swarm_secret_client::{Error, SecretStore, client::DEFAULT_CERT_MOUNT, policy, proxy};
|
||||
|
||||
/// How often [`spawn`] re-checks every agent and hive.
|
||||
const RECONCILE_INTERVAL: std::time::Duration = std::time::Duration::from_mins(5);
|
||||
|
||||
/// What [`ensure`] did at one path.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Outcome {
|
||||
/// The path already held a credential.
|
||||
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 CredentialStore {
|
||||
/// 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: &proxy::Credential,
|
||||
) -> impl Future<Output = Result<(), Error>> + Send;
|
||||
}
|
||||
|
||||
impl CredentialStore 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: &proxy::Credential) -> Result<(), Error> {
|
||||
SecretStore::create(self, path, value).await
|
||||
}
|
||||
}
|
||||
|
||||
/// Make sure `path` holds a credential, 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 credential.
|
||||
///
|
||||
/// # Errors
|
||||
/// When the store refuses the read, or the create fails and the path is still
|
||||
/// empty.
|
||||
pub(crate) async fn ensure(store: &impl CredentialStore, path: &str) -> Result<Outcome> {
|
||||
if store
|
||||
.exists(path)
|
||||
.await
|
||||
.with_context(|| format!("reading {path}"))?
|
||||
{
|
||||
return Ok(Outcome::Present);
|
||||
}
|
||||
let credential = proxy::Credential {
|
||||
value: crate::agent_identity::generate_queue_secret()?,
|
||||
};
|
||||
let Err(e) = store.create(path, &credential).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}")))
|
||||
}
|
||||
|
||||
/// [`ensure`] at each of `paths`, which `what` names in the log. Returns how
|
||||
/// many it minted. A failure at one path is logged and the rest still run.
|
||||
async fn ensure_all(
|
||||
store: &impl CredentialStore,
|
||||
what: &str,
|
||||
paths: Vec<(String, Result<String, Error>)>,
|
||||
) -> usize {
|
||||
let mut minted = 0;
|
||||
for (name, path) in paths {
|
||||
let path = match path {
|
||||
Ok(path) => path,
|
||||
Err(e) => {
|
||||
tracing::warn!(name, error = %e, "{what}: unusable name");
|
||||
continue;
|
||||
}
|
||||
};
|
||||
match ensure(store, &path).await {
|
||||
Ok(Outcome::Present) => {}
|
||||
Ok(Outcome::Minted) => {
|
||||
minted += 1;
|
||||
tracing::info!(name, %path, "{what} minted");
|
||||
}
|
||||
Ok(Outcome::LostRace) => {
|
||||
tracing::info!(name, %path, "{what}: another writer created it first");
|
||||
}
|
||||
Err(e) => tracing::warn!(name, error = %format!("{e:#}"), "{what}: mint failed"),
|
||||
}
|
||||
}
|
||||
minted
|
||||
}
|
||||
|
||||
/// One pass: a credential for every agent in `agents` and a self-check
|
||||
/// credential for every hive in `hives`. Returns how many were minted.
|
||||
async fn mint_missing(store: &impl CredentialStore, agents: &[String], hives: &[String]) -> usize {
|
||||
let for_agents = agents
|
||||
.iter()
|
||||
.map(|a| (a.clone(), proxy::agent_credential_path(a)))
|
||||
.collect();
|
||||
let for_hives = hives
|
||||
.iter()
|
||||
.map(|h| (h.clone(), proxy::selfcheck_path(h)))
|
||||
.collect();
|
||||
ensure_all(store, "agent proxy credential", for_agents).await
|
||||
+ ensure_all(store, "hive squid self-check credential", for_hives).await
|
||||
}
|
||||
|
||||
/// The agents that hold a store identity: exactly the ones whose hive reads
|
||||
/// what a pass writes.
|
||||
async fn roster(store: &SecretStore) -> Result<Vec<String>> {
|
||||
let roles = store
|
||||
.list_cert_roles(DEFAULT_CERT_MOUNT)
|
||||
.await
|
||||
.context("listing the store's cert-auth roles")?;
|
||||
Ok(policy::agents_from_role_names(&roles))
|
||||
}
|
||||
|
||||
/// Run a 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(hives: Vec<String>) {
|
||||
tokio::spawn(async move {
|
||||
let mut ticker = tokio::time::interval(RECONCILE_INTERVAL);
|
||||
loop {
|
||||
ticker.tick().await;
|
||||
let pass = async {
|
||||
let store = crate::store::connect()
|
||||
.await
|
||||
.context("logging in to the swarm secret store")?;
|
||||
let agents = roster(&store).await?;
|
||||
anyhow::Ok((agents.len(), mint_missing(&store, &agents, &hives).await))
|
||||
};
|
||||
match pass.await {
|
||||
Ok((agents, minted)) if minted > 0 => {
|
||||
tracing::info!(
|
||||
"proxy credentials: minted {minted} (agents and hive self-checks); {agents} agents hold a store identity"
|
||||
);
|
||||
}
|
||||
Ok((agents, minted)) => {
|
||||
tracing::debug!(agents, minted, "proxy credentials: pass done");
|
||||
}
|
||||
Err(e) => tracing::warn!(
|
||||
error = %format!("{e:#}"),
|
||||
retry_in_s = RECONCILE_INTERVAL.as_secs(),
|
||||
"proxy credentials: pass failed; retrying next tick"
|
||||
),
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Mutex;
|
||||
|
||||
use super::*;
|
||||
|
||||
/// An in-memory store that refuses a create over a held path the way a
|
||||
/// `cas=0` write does, and counts the creates it was asked for.
|
||||
#[derive(Default)]
|
||||
struct Fake {
|
||||
held: Mutex<HashMap<String, String>>,
|
||||
creates: Mutex<usize>,
|
||||
/// A path whose create fails and leaves nothing behind.
|
||||
broken: Option<String>,
|
||||
/// Makes the next create find the path taken by someone else.
|
||||
race: Option<String>,
|
||||
}
|
||||
|
||||
impl Fake {
|
||||
fn holding(path: &str, value: &str) -> Self {
|
||||
let fake = Self::default();
|
||||
fake.held
|
||||
.lock()
|
||||
.unwrap()
|
||||
.insert(path.to_owned(), value.to_owned());
|
||||
fake
|
||||
}
|
||||
|
||||
fn value(&self, path: &str) -> Option<String> {
|
||||
self.held.lock().unwrap().get(path).cloned()
|
||||
}
|
||||
}
|
||||
|
||||
fn refused() -> Error {
|
||||
Error::MissingEnv("BAO_ADDR")
|
||||
}
|
||||
|
||||
impl CredentialStore for Fake {
|
||||
async fn exists(&self, path: &str) -> Result<bool, Error> {
|
||||
Ok(self.held.lock().unwrap().contains_key(path))
|
||||
}
|
||||
|
||||
async fn create(&self, path: &str, value: &proxy::Credential) -> Result<(), Error> {
|
||||
*self.creates.lock().unwrap() += 1;
|
||||
let mut held = self.held.lock().unwrap();
|
||||
if self.broken.as_deref() == Some(path) {
|
||||
return Err(refused());
|
||||
}
|
||||
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 ATLAS: &str = "swarm/agents/atlas/proxy-credential";
|
||||
const ARGUS: &str = "swarm/agents/argus/proxy-credential";
|
||||
const H1: &str = "swarm/hives/h1/squid-selfcheck";
|
||||
|
||||
fn names(names: &[&str]) -> Vec<String> {
|
||||
names.iter().map(|n| (*n).to_owned()).collect()
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn an_absent_credential_is_created() {
|
||||
let store = Fake::default();
|
||||
assert_eq!(ensure(&store, ATLAS).await.unwrap(), Outcome::Minted);
|
||||
let value = store.value(ATLAS).expect("written");
|
||||
// 32 bytes, base64url without padding.
|
||||
assert_eq!(value.len(), 43, "{value}");
|
||||
assert!(
|
||||
value
|
||||
.bytes()
|
||||
.all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_present_credential_is_untouched_and_never_updated() {
|
||||
let store = Fake::holding(ATLAS, "existing");
|
||||
assert_eq!(ensure(&store, ATLAS).await.unwrap(), Outcome::Present);
|
||||
assert_eq!(store.value(ATLAS).as_deref(), Some("existing"));
|
||||
assert_eq!(*store.creates.lock().unwrap(), 0, "no write was attempted");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_lost_race_keeps_the_winners_value() {
|
||||
let store = Fake {
|
||||
race: Some("winner".to_owned()),
|
||||
..Fake::default()
|
||||
};
|
||||
assert_eq!(ensure(&store, ATLAS).await.unwrap(), Outcome::LostRace);
|
||||
assert_eq!(store.value(ATLAS).as_deref(), Some("winner"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_failed_create_with_nothing_behind_it_is_an_error() {
|
||||
let store = Fake {
|
||||
broken: Some(ATLAS.to_owned()),
|
||||
..Fake::default()
|
||||
};
|
||||
assert!(ensure(&store, ATLAS).await.is_err());
|
||||
assert_eq!(store.value(ATLAS), None);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_pass_mints_for_every_agent_and_hive_that_lacks_one() {
|
||||
let store = Fake::holding(ARGUS, "existing");
|
||||
let minted = mint_missing(&store, &names(&["atlas", "argus"]), &names(&["h1"])).await;
|
||||
assert_eq!(minted, 2);
|
||||
assert!(store.value(ATLAS).is_some());
|
||||
assert!(store.value(H1).is_some());
|
||||
assert_eq!(store.value(ARGUS).as_deref(), Some("existing"));
|
||||
// Control: the second pass has nothing left to mint, and writes nothing.
|
||||
let creates = *store.creates.lock().unwrap();
|
||||
assert_eq!(
|
||||
mint_missing(&store, &names(&["atlas", "argus"]), &names(&["h1"])).await,
|
||||
0
|
||||
);
|
||||
assert_eq!(*store.creates.lock().unwrap(), creates);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn one_agent_failing_does_not_stop_the_rest() {
|
||||
let store = Fake {
|
||||
broken: Some(ATLAS.to_owned()),
|
||||
..Fake::default()
|
||||
};
|
||||
let minted = mint_missing(&store, &names(&["atlas", "argus"]), &names(&["h1"])).await;
|
||||
assert_eq!(minted, 2);
|
||||
assert!(store.value(ARGUS).is_some());
|
||||
assert!(store.value(H1).is_some());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn an_unusable_agent_name_mints_nothing() {
|
||||
let store = Fake::default();
|
||||
assert_eq!(mint_missing(&store, &names(&["../argus"]), &[]).await, 0);
|
||||
assert!(store.held.lock().unwrap().is_empty());
|
||||
}
|
||||
}
|
||||
557
swarm-controller/src/secrets/read_policy.rs
Normal file
557
swarm-controller/src/secrets/read_policy.rs
Normal file
|
|
@ -0,0 +1,557 @@
|
|||
//! Provisioning a hive's access to the swarm's secret store: the policy its
|
||||
//! certificate carries, and the cert-auth role that hands it that policy.
|
||||
//!
|
||||
//! The controller writes a credential; the hive fetches it with its own
|
||||
//! certificate. Without the role the certificate authenticates to nothing, and
|
||||
//! without the policy the token it gets may read nothing — either way the read
|
||||
//! half of a delivery answers 403.
|
||||
//!
|
||||
//! A pass runs at startup, and repeats until it reaches the store. The two
|
||||
//! start together, so the store being the slower one is the ordinary case
|
||||
//! rather than an edge one, and a pass that gave up there provisions nobody
|
||||
//! until something restarts this daemon. A shared policy the store refuses is
|
||||
//! the same kind of failure: the controller's own policy is rewritten by a unit
|
||||
//! that is not ordered against this daemon, so the refusal can be a moment too.
|
||||
//! Per-hive role failures are different: they are reported and skipped — one
|
||||
//! hive that cannot be provisioned should not take down a daemon that serves
|
||||
//! everything else, and a store that answers is answering the same way next
|
||||
//! time, so the next start is the retry for those.
|
||||
//!
|
||||
//! The rule is written once for all hives, [`policy::SHARED_HIVE_POLICY`]: one
|
||||
//! stanza is the same everywhere, the other is scoped to the reader's own name
|
||||
//! ([`swarm_secret_client::policy`] explains the asymmetry), taken from its
|
||||
//! login's alias on the cert mount instead of written into the text. A hive's
|
||||
//! role attaches that policy and no other. The hive list is loaded once because
|
||||
//! a config change means a redeploy.
|
||||
//!
|
||||
//! The shared agent policy is written by the same kind of pass
|
||||
//! ([`ensure_agent_policies`]), together with each agent's identity entity and
|
||||
//! the token lifetimes of its existing role ([`crate::agent_role_ttl`]).
|
||||
//! Its roster is the store's `hive-agent-*` cert-auth roles.
|
||||
|
||||
use std::{future::Future, time::Duration};
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
use backon::{BackoffBuilder as _, ConstantBuilder};
|
||||
use swarm_secret_client::{Error, client::DEFAULT_CERT_MOUNT, policy};
|
||||
|
||||
use crate::store::AccessStore;
|
||||
|
||||
/// File holding the authority hives are issued from, as
|
||||
/// `swarm-controller.nix` names it.
|
||||
pub const ENV_HIVE_CLIENT_CA: &str = "SWARM_CONTROLLER_HIVE_CLIENT_CA_FILE";
|
||||
|
||||
/// How long to wait before re-attempting a pass that did not complete.
|
||||
///
|
||||
/// `nix/host-modules/swarm-bao.nix`'s bootstrap unit retries the other side of
|
||||
/// this same race on the same cadence: the two halves of one race should not
|
||||
/// disagree about how long a wait is worth.
|
||||
const RETRY_INTERVAL: Duration = Duration::from_secs(30);
|
||||
|
||||
/// How many times [`RETRY_INTERVAL`] is waited before giving up. A store that
|
||||
/// has not appeared within [`RETRY_WINDOW`] is absent rather than slow, and a
|
||||
/// daemon logging into the void forever tells an operator nothing.
|
||||
const RETRY_ATTEMPTS: u32 = 2_880;
|
||||
|
||||
/// What [`RETRY_ATTEMPTS`] at [`RETRY_INTERVAL`] come to. A named third
|
||||
/// constant because it is the claim the other two make together, and either
|
||||
/// one of them can be edited alone.
|
||||
const RETRY_WINDOW: Duration = Duration::from_hours(24);
|
||||
|
||||
/// A pass that could not complete for a reason a later attempt may resolve: the
|
||||
/// store was not reached, or it answered and refused (an accessor read or a
|
||||
/// shared-policy write answered 403). Carries what to say about it.
|
||||
///
|
||||
/// Returned rather than logged where it happens: the first attempt deserves a
|
||||
/// warning and the two-hundredth is noise, and only the caller knows which one
|
||||
/// this is.
|
||||
struct Unreachable(String);
|
||||
|
||||
/// Give every hive in `hives` the access its certificate needs.
|
||||
///
|
||||
/// Returns once the first pass is done, so a store that is already up leaves
|
||||
/// nothing deferred. When that pass cannot complete, it repeats in the
|
||||
/// background for up to [`RETRY_WINDOW`].
|
||||
pub async fn ensure_hive_access(hives: Vec<String>) {
|
||||
if let Err(Unreachable(reason)) = provision(&hives).await {
|
||||
tracing::warn!(
|
||||
reason,
|
||||
retry_in = ?RETRY_INTERVAL,
|
||||
"hive provisioning could not complete (the swarm secret store was unreachable or refused); retrying in the background"
|
||||
);
|
||||
spawn_retry(hives);
|
||||
}
|
||||
}
|
||||
|
||||
/// Repeat [`provision`] until it reaches the store, or [`RETRY_WINDOW`] passes.
|
||||
fn spawn_retry(hives: Vec<String>) {
|
||||
tokio::spawn(async move {
|
||||
let reached = retry_until_ok(RETRY_INTERVAL, RETRY_ATTEMPTS, move || {
|
||||
let hives = hives.clone();
|
||||
async move {
|
||||
let outcome = provision(&hives).await;
|
||||
if let Err(Unreachable(reason)) = &outcome {
|
||||
tracing::debug!(reason, "hive provisioning: still not complete");
|
||||
}
|
||||
outcome
|
||||
}
|
||||
})
|
||||
.await;
|
||||
if let Some(attempt) = reached {
|
||||
tracing::info!(attempt, "hive provisioning reached the store");
|
||||
} else {
|
||||
tracing::warn!(
|
||||
attempts = RETRY_ATTEMPTS,
|
||||
window = ?RETRY_WINDOW,
|
||||
"giving up on hive provisioning; no hive can log in to the store until this daemon is restarted"
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Run `attempt` every `interval` until it succeeds, at most `attempts` times.
|
||||
/// Answers with the attempt that succeeded, or `None` if none did.
|
||||
///
|
||||
/// The cadence and the bound are parameters rather than the constants above so
|
||||
/// that a test can drive this loop without waiting out a real day.
|
||||
async fn retry_until_ok<F, Fut>(interval: Duration, attempts: u32, mut attempt: F) -> Option<u32>
|
||||
where
|
||||
F: FnMut() -> Fut,
|
||||
Fut: Future<Output = Result<(), Unreachable>>,
|
||||
{
|
||||
// One delay per attempt, waited before it: the pass the caller already ran
|
||||
// before deciding to retry at all is the attempt that needs no wait.
|
||||
let delays = ConstantBuilder::default()
|
||||
.with_delay(interval)
|
||||
.with_max_times(attempts as usize)
|
||||
.build();
|
||||
for (n, delay) in (1..).zip(delays) {
|
||||
tokio::time::sleep(delay).await;
|
||||
if attempt().await.is_ok() {
|
||||
return Some(n);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// One pass: log in once, write the shared hive policy, then every hive's role.
|
||||
///
|
||||
/// Policy first, because the role names the policy — the other order leaves a
|
||||
/// window in which the role points at nothing. Without the policy the roles are
|
||||
/// left as they are: a role written to name a policy that does not exist logs
|
||||
/// its hive in able to read nothing.
|
||||
///
|
||||
/// # Errors
|
||||
/// [`Unreachable`] for the states a later attempt can resolve: a store that is
|
||||
/// not up or that refuses the shared hive policy, and an authority file that is
|
||||
/// not placed yet. A deployment that is configured for neither is `Ok` —
|
||||
/// there is nothing to wait for.
|
||||
async fn provision(hives: &[String]) -> Result<(), Unreachable> {
|
||||
if hives.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
let store = match crate::store::connect().await {
|
||||
Ok(store) => store,
|
||||
// An unset `BAO_*` variable is a deployment that runs no store, not
|
||||
// one whose store is late: asking again changes nothing.
|
||||
Err(Error::MissingEnv(var)) => {
|
||||
tracing::info!(
|
||||
var,
|
||||
"no secret store configured; hive access is not managed here"
|
||||
);
|
||||
return Ok(());
|
||||
}
|
||||
Err(e) => return Err(Unreachable(e.to_string())),
|
||||
};
|
||||
provision_with(&store, hives, read_hive_authority).await
|
||||
}
|
||||
|
||||
/// The hive authority from the file `ENV_HIVE_CLIENT_CA` names, or `None` when
|
||||
/// none is configured.
|
||||
fn read_hive_authority() -> Result<Option<String>, Unreachable> {
|
||||
let Some(path) = std::env::var_os(ENV_HIVE_CLIENT_CA) else {
|
||||
return Ok(None);
|
||||
};
|
||||
let path = path.to_string_lossy().into_owned();
|
||||
// Retryable rather than fatal: the unit that places this file and this
|
||||
// daemon start together, so "not there yet" is a moment, not a verdict.
|
||||
std::fs::read_to_string(&path)
|
||||
.map(Some)
|
||||
.map_err(|e| Unreachable(format!("reading the hive authority {path}: {e}")))
|
||||
}
|
||||
|
||||
/// [`provision`] against `store`, with the authority read by `read_authority`.
|
||||
async fn provision_with(
|
||||
store: &impl AccessStore,
|
||||
hives: &[String],
|
||||
read_authority: impl FnOnce() -> Result<Option<String>, Unreachable>,
|
||||
) -> Result<(), Unreachable> {
|
||||
write_shared_policy(store).await?;
|
||||
let Some(ca) = read_authority()? else {
|
||||
tracing::info!("no hive certificate authority configured; hive roles are not managed here");
|
||||
return Ok(());
|
||||
};
|
||||
for hive in hives {
|
||||
if let Err(e) = write_role(store, hive, &ca).await {
|
||||
tracing::warn!(hive, error = %format!("{e:#}"), "creating this hive's store role failed");
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Write [`policy::SHARED_HIVE_POLICY`], rendered with the cert mount's
|
||||
/// accessor. Hive roles are written only once it is in place.
|
||||
///
|
||||
/// # Errors
|
||||
/// [`Unreachable`] when the store refuses the accessor read (the controller's
|
||||
/// policy may not carry it yet) or the write, or when the accessor is not
|
||||
/// usable in a policy: the roles already in the store are left as they are.
|
||||
async fn write_shared_policy(store: &impl AccessStore) -> Result<(), Unreachable> {
|
||||
let accessor = store
|
||||
.auth_mount_accessor(DEFAULT_CERT_MOUNT)
|
||||
.await
|
||||
.map_err(|e| {
|
||||
Unreachable(format!(
|
||||
"the cert auth mount's accessor could not be read: {e}"
|
||||
))
|
||||
})?;
|
||||
let document = policy::render_shared_hives(&accessor).map_err(|e| {
|
||||
Unreachable(format!(
|
||||
"the cert auth mount's accessor is not usable in a policy: {e}"
|
||||
))
|
||||
})?;
|
||||
store
|
||||
.write_policy(policy::SHARED_HIVE_POLICY, &document)
|
||||
.await
|
||||
.map_err(|e| {
|
||||
Unreachable(format!(
|
||||
"writing the {} policy failed: {e}",
|
||||
policy::SHARED_HIVE_POLICY
|
||||
))
|
||||
})?;
|
||||
tracing::info!(
|
||||
policy = policy::SHARED_HIVE_POLICY,
|
||||
"shared hive policy in place"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The policies a hive's role attaches: the shared one, and no policy named for
|
||||
/// the hive.
|
||||
fn attached_policies() -> Vec<String> {
|
||||
vec![policy::SHARED_HIVE_POLICY.to_owned()]
|
||||
}
|
||||
|
||||
/// The role for one hive: its own certificate's subject and the shared policy.
|
||||
async fn write_role(store: &impl AccessStore, hive: &str, ca: &str) -> Result<()> {
|
||||
let name = policy::hive_object_name(hive)?;
|
||||
let attached = attached_policies();
|
||||
store
|
||||
// The subject is the hive's name: `glue-bao-tls.nix` mints a hive's
|
||||
// client leaf with its name as the CN, and cert auth matches on that.
|
||||
.write_cert_role(
|
||||
DEFAULT_CERT_MOUNT,
|
||||
&name,
|
||||
ca,
|
||||
hive,
|
||||
&attached.iter().map(String::as_str).collect::<Vec<_>>(),
|
||||
)
|
||||
.await
|
||||
.with_context(|| format!("writing the cert-auth role {name}"))?;
|
||||
tracing::info!(hive, role = %name, "hive store role in place");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Write the shared agent policy and give every agent its identity entity, with
|
||||
/// the retry [`ensure_hive_access`] has and for the same reason.
|
||||
///
|
||||
/// Returns once the first pass is done. When that pass cannot complete,
|
||||
/// it repeats in the background for up to [`RETRY_WINDOW`].
|
||||
pub async fn ensure_agent_policies() {
|
||||
if let Err(Unreachable(reason)) = rewrite_agent_policies().await {
|
||||
tracing::warn!(
|
||||
reason,
|
||||
retry_in = ?RETRY_INTERVAL,
|
||||
"agent policy rewrite could not complete (the swarm secret store was unreachable or refused); retrying in the background"
|
||||
);
|
||||
tokio::spawn(async {
|
||||
let reached = retry_until_ok(RETRY_INTERVAL, RETRY_ATTEMPTS, || async {
|
||||
let outcome = rewrite_agent_policies().await;
|
||||
if let Err(Unreachable(reason)) = &outcome {
|
||||
tracing::debug!(reason, "agent policy rewrite: still not complete");
|
||||
}
|
||||
outcome
|
||||
})
|
||||
.await;
|
||||
if let Some(attempt) = reached {
|
||||
tracing::info!(attempt, "agent policy rewrite reached the store");
|
||||
} else {
|
||||
tracing::warn!(
|
||||
attempts = RETRY_ATTEMPTS,
|
||||
window = ?RETRY_WINDOW,
|
||||
"giving up on the agent policy rewrite; the shared agent policy and the agents' identity entities are not checked until this daemon is restarted"
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// One pass: log in once, list the agents, write the shared agent policy, give
|
||||
/// each agent its identity entity and bring each existing role's token
|
||||
/// lifetimes current.
|
||||
///
|
||||
/// The roles' certificate, names and policies are not touched. They and the
|
||||
/// certificate are `agent_identity::mint_and_verify`'s, and that reissues the
|
||||
/// certificate, so it is not what a pass on every start may call.
|
||||
///
|
||||
/// # Errors
|
||||
/// [`Unreachable`] when the store cannot be reached or will not list its
|
||||
/// roles: either way no agent was written, and a later attempt may get
|
||||
/// further. Also when it refuses the shared agent policy, after the agents
|
||||
/// have still been given their entities and token lifetimes. A deployment
|
||||
/// with no store configured is `Ok`.
|
||||
async fn rewrite_agent_policies() -> Result<(), Unreachable> {
|
||||
let store = match crate::store::connect().await {
|
||||
Ok(store) => store,
|
||||
Err(Error::MissingEnv(var)) => {
|
||||
tracing::info!(
|
||||
var,
|
||||
"no secret store configured; agent policies are not managed here"
|
||||
);
|
||||
return Ok(());
|
||||
}
|
||||
Err(e) => return Err(Unreachable(e.to_string())),
|
||||
};
|
||||
let roles = store
|
||||
.list_cert_roles(DEFAULT_CERT_MOUNT)
|
||||
.await
|
||||
.map_err(|e| Unreachable(format!("listing the store's cert-auth roles: {e}")))?;
|
||||
write_agent_policy_and_entities(&store, &roles).await
|
||||
}
|
||||
|
||||
/// The part of [`rewrite_agent_policies`] after the roles are listed.
|
||||
async fn write_agent_policy_and_entities(
|
||||
store: &impl AccessStore,
|
||||
roles: &[String],
|
||||
) -> Result<(), Unreachable> {
|
||||
// First, so the cert-auth role that names it never points at nothing.
|
||||
let written = store
|
||||
.write_policy(policy::SHARED_AGENT_POLICY, &policy::render_shared_agent())
|
||||
.await;
|
||||
if written.is_ok() {
|
||||
tracing::info!(
|
||||
policy = policy::SHARED_AGENT_POLICY,
|
||||
"shared agent policy in place"
|
||||
);
|
||||
}
|
||||
crate::agent_entity::ensure_agents(store, &policy::agents_from_role_names(roles)).await;
|
||||
crate::agent_role_ttl::bring_current(store, roles).await;
|
||||
written.map_err(|e| {
|
||||
Unreachable(format!(
|
||||
"writing the {} policy failed: {e}",
|
||||
policy::SHARED_AGENT_POLICY
|
||||
))
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::{cell::Cell, time::Duration};
|
||||
|
||||
use crate::store::{AccessStore, fake::FakeAccess};
|
||||
|
||||
use super::{
|
||||
RETRY_ATTEMPTS, RETRY_INTERVAL, RETRY_WINDOW, Unreachable, attached_policies, policy,
|
||||
provision_with, retry_until_ok, write_agent_policy_and_entities, write_role,
|
||||
};
|
||||
|
||||
#[test]
|
||||
fn the_retry_bound_is_the_window_it_claims() {
|
||||
assert_eq!(RETRY_INTERVAL * RETRY_ATTEMPTS, RETRY_WINDOW);
|
||||
}
|
||||
|
||||
/// The property this issue is about: a pass that fails because the store is
|
||||
/// not up yet happens again.
|
||||
#[tokio::test]
|
||||
async fn a_pass_is_repeated_until_it_reaches_the_store() {
|
||||
let calls = Cell::new(0_u32);
|
||||
let reached = retry_until_ok(Duration::from_millis(1), 10, || {
|
||||
calls.set(calls.get() + 1);
|
||||
let still_down = calls.get() < 3;
|
||||
async move {
|
||||
if still_down {
|
||||
Err(Unreachable("store not up".to_owned()))
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
})
|
||||
.await;
|
||||
assert_eq!(reached, Some(3));
|
||||
assert_eq!(calls.get(), 3, "the loop stops at the first success");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn the_loop_is_bounded_rather_than_endless() {
|
||||
let calls = Cell::new(0_u32);
|
||||
let reached = retry_until_ok(Duration::from_millis(1), 5, || {
|
||||
calls.set(calls.get() + 1);
|
||||
async { Err(Unreachable("store not up".to_owned())) }
|
||||
})
|
||||
.await;
|
||||
assert_eq!(reached, None, "a store that never appears is given up on");
|
||||
assert_eq!(calls.get(), 5, "one attempt per interval, and no more");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_hives_role_attaches_the_shared_policy_and_none_named_for_the_hive() {
|
||||
let attached = attached_policies();
|
||||
assert_eq!(attached, [policy::SHARED_HIVE_POLICY]);
|
||||
let own = policy::hive_object_name("pr1ma").expect("legal");
|
||||
assert!(
|
||||
!attached.contains(&own),
|
||||
"the role must not attach a policy named for the hive"
|
||||
);
|
||||
// The control: the same lookup finds a policy that is attached.
|
||||
assert!(attached.contains(&policy::SHARED_HIVE_POLICY.to_owned()));
|
||||
}
|
||||
|
||||
fn hives() -> Vec<String> {
|
||||
["pr1ma", "beta"].map(str::to_owned).to_vec()
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn every_hives_role_is_written_after_the_shared_policy_and_attaches_it_alone() {
|
||||
let store = FakeAccess::default();
|
||||
provision_with(&store, &hives(), || Ok(Some("HIVE-CA".to_owned())))
|
||||
.await
|
||||
.unwrap_or_else(|_| panic!("a store that accepts everything"));
|
||||
assert_eq!(
|
||||
store.roles_written(),
|
||||
[
|
||||
"write_cert_role hive-pr1ma hive-hives",
|
||||
"write_cert_role hive-beta hive-hives"
|
||||
]
|
||||
);
|
||||
let calls = store.calls();
|
||||
let policy_at = calls
|
||||
.iter()
|
||||
.position(|c| c == "write_policy hive-hives")
|
||||
.expect("the shared policy was written");
|
||||
let first_role_at = calls
|
||||
.iter()
|
||||
.position(|c| c.starts_with("write_cert_role "))
|
||||
.expect("a role was written");
|
||||
assert!(policy_at < first_role_at, "{calls:?}");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn an_unreadable_accessor_leaves_every_hive_role_as_it_was() {
|
||||
let store = FakeAccess::without_accessor();
|
||||
let outcome = provision_with(&store, &hives(), || Ok(Some("HIVE-CA".to_owned()))).await;
|
||||
assert!(
|
||||
outcome.is_err(),
|
||||
"a policy that cannot be written is retried"
|
||||
);
|
||||
assert!(store.roles_written().is_empty(), "{:?}", store.calls());
|
||||
// The control: the accessor read was attempted, and the same fake
|
||||
// writes roles when it works (the test above).
|
||||
assert_eq!(store.calls(), ["auth_mount_accessor"]);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_refused_shared_policy_leaves_every_hive_role_as_it_was() {
|
||||
let store = FakeAccess::refusing_policies();
|
||||
let outcome = provision_with(&store, &hives(), || Ok(Some("HIVE-CA".to_owned()))).await;
|
||||
assert!(outcome.is_err(), "a refused write is retried");
|
||||
assert!(store.roles_written().is_empty(), "{:?}", store.calls());
|
||||
assert!(
|
||||
store
|
||||
.calls()
|
||||
.contains(&"write_policy hive-hives".to_owned())
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_hive_whose_role_was_deleted_gets_it_back_when_it_is_in_the_roster_again() {
|
||||
let store = FakeAccess::default();
|
||||
write_role(&store, "pr1ma", "CA").await.expect("accepted");
|
||||
assert!(store.role("hive-pr1ma").is_some());
|
||||
store
|
||||
.delete_cert_role("auth/cert", "hive-pr1ma")
|
||||
.await
|
||||
.expect("accepted");
|
||||
assert_eq!(store.role("hive-pr1ma"), None);
|
||||
write_role(&store, "pr1ma", "CA").await.expect("accepted");
|
||||
assert!(store.role("hive-pr1ma").is_some());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn without_an_authority_the_policy_is_written_and_no_role_is() {
|
||||
let store = FakeAccess::default();
|
||||
provision_with(&store, &hives(), || Ok(None))
|
||||
.await
|
||||
.unwrap_or_else(|_| panic!("no authority configured is not a retry"));
|
||||
assert!(store.roles_written().is_empty(), "{:?}", store.calls());
|
||||
assert!(
|
||||
store
|
||||
.calls()
|
||||
.contains(&"write_policy hive-hives".to_owned())
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn an_authority_that_cannot_be_read_is_retried_and_writes_no_role() {
|
||||
let store = FakeAccess::default();
|
||||
let outcome = provision_with(&store, &hives(), || {
|
||||
Err(Unreachable("not placed yet".to_owned()))
|
||||
})
|
||||
.await;
|
||||
assert!(outcome.is_err());
|
||||
assert!(store.roles_written().is_empty(), "{:?}", store.calls());
|
||||
}
|
||||
|
||||
/// The property this change is about: a pass that is refused the shared
|
||||
/// policy is repeated, and the roles are written once the store accepts it.
|
||||
#[tokio::test]
|
||||
async fn a_refused_accessor_read_is_repeated_and_the_roles_follow() {
|
||||
let store = FakeAccess::with_accessor_refused(1);
|
||||
let hives = hives();
|
||||
let pass = || provision_with(&store, &hives, || Ok(Some("HIVE-CA".to_owned())));
|
||||
assert!(pass().await.is_err(), "the first pass is refused");
|
||||
assert!(store.roles_written().is_empty(), "{:?}", store.calls());
|
||||
let reached = retry_until_ok(Duration::from_millis(1), 10, pass).await;
|
||||
assert_eq!(reached, Some(1), "the first retry succeeds");
|
||||
assert_eq!(
|
||||
store.roles_written(),
|
||||
[
|
||||
"write_cert_role hive-pr1ma hive-hives",
|
||||
"write_cert_role hive-beta hive-hives"
|
||||
],
|
||||
"{:?}",
|
||||
store.calls()
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_refused_shared_agent_policy_is_retried_and_a_written_one_is_not() {
|
||||
let refused = FakeAccess::refusing_policies();
|
||||
assert!(
|
||||
write_agent_policy_and_entities(&refused, &[])
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
// The control: the same pass against a store that accepts the write.
|
||||
let accepting = FakeAccess::default();
|
||||
assert!(
|
||||
write_agent_policy_and_entities(&accepting, &[])
|
||||
.await
|
||||
.is_ok()
|
||||
);
|
||||
assert!(
|
||||
accepting
|
||||
.calls()
|
||||
.contains(&format!("write_policy {}", policy::SHARED_AGENT_POLICY))
|
||||
);
|
||||
}
|
||||
}
|
||||
Loading…
Reference in a new issue