Watch
0
0
Fork
You've already forked hyperhive
0

gate ssh signing per agent: ssh permission, signing policy on the login role, ca key endpoint

This commit is contained in:
atlas 2026-11-16 18:29:06 +01:00 • committed by mara
commit 910f9a6f50
2 changed files with 805 additions and 57 deletions

View file

@ -474,6 +474,67 @@ impl SecretStore {
Ok(())
}
/// The public key of the SSH secrets engine mounted at `mount`, one
/// `authorized_keys`-style line, or `None` when the mount holds no CA yet.
///
/// # Errors
/// [`Error::Vault`] for anything that is not a 400 or 404: a denial, or an
/// unreachable store.
pub async fn ssh_ca_public_key(&self, mount: &str) -> Result<Option<String>, Error> {
let request = ReadSshCa {
mount: mount.to_owned(),
};
match vaultrs::api::exec_with_result(&self.inner, request).await {
Ok(ca) => Ok(Some(ca.public_key.trim().to_owned()).filter(|k| !k.is_empty())),
Err(e) if is_absent(&e) || is_bad_request(&e) => Ok(None),
Err(e) => Err(e.into()),
}
}
/// The policies the cert-auth role `name` attaches to its tokens, or `None`
/// when the role does not exist.
///
/// # Errors
/// [`Error::Vault`] for anything that is not a 404.
pub async fn cert_role_policies(
&self,
mount: &str,
name: &str,
) -> Result<Option<Vec<String>>, Error> {
let request = ReadCertRolePolicies {
mount: mount.to_owned(),
name: name.to_owned(),
};
match vaultrs::api::exec_with_result(&self.inner, request).await {
Ok(role) => Ok(Some(role.token_policies)),
Err(e) if is_absent(&e) => Ok(None),
Err(e) => Err(e.into()),
}
}
/// Replace the policies the existing cert-auth role `name` attaches, leaving
/// the rest of the role as it is. The write names no other field, for the
/// reason [`Self::set_cert_role_token_ttls`] gives. Tokens already issued
/// keep the policies they were issued with until they expire or are renewed.
///
/// # Errors
/// [`Error::Vault`] when the token's policy does not cover
/// `auth/<mount>/certs/<name>`, or the store refuses the write.
pub async fn set_cert_role_policies(
&self,
mount: &str,
name: &str,
policies: &[&str],
) -> Result<(), Error> {
let request = SetCertRolePolicies {
mount: mount.to_owned(),
name: name.to_owned(),
token_policies: policies.iter().map(|p| (*p).to_owned()).collect(),
};
vaultrs::api::exec_with_empty(&self.inner, request).await?;
Ok(())
}
/// Have the PKI role `role` on `mount` issue a client certificate for
/// `common_name`, returning it with its key and the issuing CA.
///
@ -768,6 +829,11 @@ fn is_absent(e: &vaultrs::error::ClientError) -> bool {
matches!(e, vaultrs::error::ClientError::APIError { code: 404, .. })
}
/// A 400, which the SSH engine answers a CA read with while it holds no CA.
fn is_bad_request(e: &vaultrs::error::ClientError) -> bool {
matches!(e, vaultrs::error::ClientError::APIError { code: 400, .. })
}
/// Write an ACL policy, spelled out here because [`vaultrs`] does not have it:
/// its `sys::policy` module targets `sys/policy/<name>`, the deprecated alias,
/// and the store ACLs that path separately from `sys/policies/acl/<name>`. A
@ -828,6 +894,53 @@ struct SetCertRoleTtls {
token_max_ttl: String,
}
/// Read an SSH engine mount's CA.
#[derive(Endpoint)]
#[endpoint(path = "{self.mount}/config/ca", method = "GET", response = "SshCa")]
struct ReadSshCa {
#[endpoint(skip)]
mount: String,
}
/// The public half of the CA, the one field read.
#[derive(Debug, serde::Deserialize)]
struct SshCa {
public_key: String,
}
/// Read the policies of a cert-auth role.
#[derive(Endpoint)]
#[endpoint(
path = "auth/{self.mount}/certs/{self.name}",
method = "GET",
response = "CertRolePolicies"
)]
struct ReadCertRolePolicies {
#[endpoint(skip)]
mount: String,
#[endpoint(skip)]
name: String,
}
/// The one field of a cert-auth role [`SecretStore::cert_role_policies`] reads.
#[derive(Debug, serde::Deserialize)]
struct CertRolePolicies {
#[serde(default)]
token_policies: Vec<String>,
}
/// Write the policies of a cert-auth role and nothing else, as [`SetCertRoleTtls`]
/// does for the lifetimes.
#[derive(Endpoint)]
#[endpoint(path = "auth/{self.mount}/certs/{self.name}", method = "POST")]
struct SetCertRolePolicies {
#[endpoint(skip)]
mount: String,
#[endpoint(skip)]
name: String,
token_policies: Vec<String>,
}
/// The request [`SecretStore::set_cert_role_token_ttls`] sends.
fn set_cert_role_token_ttls_request(mount: &str, name: &str) -> SetCertRoleTtls {
SetCertRoleTtls {

View file

@ -194,6 +194,11 @@ pub fn render_shared_hives(mount_accessor: &str) -> Result<String, Error> {
/// forbids.
pub const SHARED_AGENT_POLICY: &str = "hive-agent";
/// The policy that holds the SSH signing grant ([`render_ssh_signer`]). Inside
/// [`HIVE_PREFIX`] so the controller may write it. It is a policy name; the cert-auth role `hive-agent-ssh` would be an agent
/// called `ssh`'s, a different namespace.
pub const SSH_POLICY: &str = "hive-agent-ssh";
/// The template that stands for the agent's name in [`render_shared_agent`]:
/// the name of the login's identity entity, which swarm-controller sets to the
/// agent's name.
@ -233,11 +238,8 @@ pub const SSH_ROLE: &str = "swarm-agent";
/// none of [`render_shared_hives`]'s breadth applies. A hive still reads this
/// agent's secrets, and closing that is its own decision.
///
/// The last stanza is `update` on [`SSH_MOUNT`]'s sign endpoint for [`SSH_ROLE`]:
/// the agent submits a public key it generated and gets a short-lived user
/// certificate back. It names no agent. What a certificate may say is the
/// role's: the principal is the identity entity's name, so an agent can be
/// signed for its own name and no other.
/// No SSH stanza: signing is [`SSH_POLICY`]'s, which an agent's role attaches
/// only while the operator has switched SSH on for it.
#[must_use]
pub fn render_shared_agent() -> String {
let kind = <&str>::from(Kind::Agent);
@ -251,8 +253,21 @@ pub fn render_shared_agent() -> String {
"{MOUNT}/data/{ROOT}/{kind}/{ENTITY_NAME_TEMPLATE}/{}",
backend_env::LEAF
));
let sign = sign_stanza(&format!("{SSH_MOUNT}/sign/{SSH_ROLE}"));
format!("{read}{list}{seed}{sign}")
format!("{read}{list}{seed}")
}
/// The policy that lets an agent have its SSH key signed: `update` on
/// [`SSH_MOUNT`]'s sign endpoint for [`SSH_ROLE`], and nothing else. The same
/// text for every agent. The agent submits a public key it generated and gets a
/// short-lived user certificate back. What the certificate may say is the
/// role's: the principal is the identity entity's name, so an agent is signed
/// for its own name and no other.
///
/// Attached to an agent's cert-auth role only while its `ssh` permission is on
/// (`swarm-controller`'s `agent_ssh`).
#[must_use]
pub fn render_ssh_signer() -> String {
sign_stanza(&format!("{SSH_MOUNT}/sign/{SSH_ROLE}"))
}
/// What an agent's token grants under [`SHARED_AGENT_POLICY`]: the document
@ -284,8 +299,7 @@ mod tests {
render_shared_agent(),
"path \"secret/data/swarm/agents/{{identity.entity.name}}/*\" {\n capabilities = [\"read\"]\n}\n\
path \"secret/metadata/swarm/agents/{{identity.entity.name}}/*\" {\n capabilities = [\"list\"]\n}\n\
path \"secret/data/swarm/agents/{{identity.entity.name}}/backend-env\" {\n capabilities = [\"create\", \"read\"]\n}\n\
path \"ssh-agents/sign/swarm-agent\" {\n capabilities = [\"update\"]\n}\n"
path \"secret/data/swarm/agents/{{identity.entity.name}}/backend-env\" {\n capabilities = [\"create\", \"read\"]\n}\n"
);
}
@ -294,33 +308,30 @@ mod tests {
let shared = render_shared_agent();
assert!(!shared.contains("atlas"));
assert!(!shared.contains("agents/*"), "{shared}");
assert!(!shared.contains("update"));
assert!(!shared.contains("delete"));
// `update` is the signing stanza's and no KV path's: a KV leaf the
// agent could rewrite would let it replace a credential it only seeds.
let secret_only = shared
.split("path \"ssh-agents/")
.next()
.unwrap_or_default();
assert!(!secret_only.contains("update"), "{shared}");
}
/// What the SSH policy holds, byte for byte: one update stanza on one role's
/// sign path, the same text for every agent.
#[test]
fn the_agent_may_sign_through_one_role_and_do_nothing_else_on_the_ssh_mount() {
let shared = render_shared_agent();
let ssh: Vec<&str> = shared
.split("path \"")
.filter(|s| s.starts_with(SSH_MOUNT))
.collect();
fn the_ssh_policy_is_update_on_one_sign_path_and_nothing_else() {
assert_eq!(
ssh,
["ssh-agents/sign/swarm-agent\" {\n capabilities = [\"update\"]\n}\n"]
render_ssh_signer(),
"path \"ssh-agents/sign/swarm-agent\" {\n capabilities = [\"update\"]\n}\n"
);
// The control: the filter finds a stanza that is there.
assert!(shared.split("path \"").any(|s| s.starts_with(MOUNT)));
assert_eq!(
format!("{SSH_MOUNT}/sign/{SSH_ROLE}"),
"ssh-agents/sign/swarm-agent"
);
assert!(SSH_POLICY.starts_with(HIVE_PREFIX));
assert_ne!(SSH_POLICY, SHARED_AGENT_POLICY);
}
#[test]
fn the_shared_agent_policy_names_nothing_on_the_ssh_mount() {
assert!(!render_shared_agent().contains(SSH_MOUNT));
assert!(render_ssh_signer().contains(SSH_MOUNT));
}
#[test]
@ -525,8 +536,7 @@ mod tests {
/// What `effective_agent("atlas")` must be, byte for byte.
const ATLAS_DOCUMENT: &str = "path \"secret/data/swarm/agents/atlas/*\" {\n capabilities = [\"read\"]\n}\n\
path \"secret/metadata/swarm/agents/atlas/*\" {\n capabilities = [\"list\"]\n}\n\
path \"secret/data/swarm/agents/atlas/backend-env\" {\n capabilities = [\"create\", \"read\"]\n}\n\
path \"ssh-agents/sign/swarm-agent\" {\n capabilities = [\"update\"]\n}\n";
path \"secret/data/swarm/agents/atlas/backend-env\" {\n capabilities = [\"create\", \"read\"]\n}\n";
#[test]
fn an_agents_document_is_its_stanzas_naming_that_agent() {
@ -565,8 +575,8 @@ mod tests {
assert!(!p.contains("argus"), "no other principal is named");
assert_eq!(
p.matches("path \"").count(),
4,
"four stanzas, or the document grants something unaccounted for: {p}"
3,
"three stanzas, or the document grants something unaccounted for: {p}"
);
}
@ -610,12 +620,7 @@ mod tests {
["secret/data/swarm/agents/atlas/*", leaf.as_str()]
);
assert_eq!(paths_granting(&p, "create"), [leaf.as_str()]);
// The one `update` is the SSH signing endpoint's: no KV path takes it.
assert_eq!(
paths_granting(&p, "update"),
["ssh-agents/sign/swarm-agent"]
);
for capability in ["delete", "sudo", "patch"] {
for capability in ["update", "delete", "sudo", "patch"] {
assert!(
!p.contains(capability),
"an agent's document must not grant {capability}: {p}"
@ -636,9 +641,8 @@ mod tests {
// granted, nor is `list` anywhere but `metadata/`.
let p = effective_agent("atlas");
let stanzas: Vec<&str> = p.split_inclusive("}\n").collect();
assert_eq!(stanzas.len(), 4, "{p}");
// The third is the create stanza and the fourth the signing stanza,
// each pinned by a test above.
assert_eq!(stanzas.len(), 3, "{p}");
// The third is the create stanza, pinned by the test above.
for stanza in &stanzas[..2] {
let on_data = stanza.starts_with("path \"secret/data/");
let on_metadata = stanza.starts_with("path \"secret/metadata/");