Watch
0
0
Fork
You've already forked hyperhive
0

swarm-secret-client: name the store-answer mappings and test them

Each optional read, listing, delete, SSH CA read, alias lookup and versioned
read in SecretStore decided what a 404 (or a 400, or an empty 204) means
inline, next to the vaultrs call. Move those decisions into small functions
(none_when_absent, empty_when_absent, done_when_absent, ssh_ca_key,
entity_from_lookup, versioned) and the cert-role policy write's request into
set_cert_role_policies_request. Behaviour is unchanged.

Test them with constructed ClientError values: 404 is nothing there, every
other status (400, 403, 429, 500, 503) stays the store's error with the
status in the message, a blank SSH CA key is none, an empty alias answer is
a miss and any other parse failure is not, a versioned read keeps the number
and time and a wrong-shaped object is an error. Also pin the cert-role read
structs and the paths the grant names.

The vaultrs call lines themselves stay unit-uncovered by design; the VM tests
drive them against a real bao.
This commit is contained in:
maia 2026-11-30 10:43:06 +01:00 • committed by mara
commit 5079eb58d0

View file

@ -240,11 +240,7 @@ impl SecretStore {
/// [`Error::Vault`] for anything that is not a 404: a denial, an
/// unreachable store, or an object that does not decode as `T`.
pub async fn read_optional<T: DeserializeOwned>(&self, path: &str) -> Result<Option<T>, Error> {
match vaultrs::kv2::read(&self.inner, MOUNT, path).await {
Ok(value) => Ok(Some(value)),
Err(vaultrs::error::ClientError::APIError { code: 404, .. }) => Ok(None),
Err(e) => Err(e.into()),
}
none_when_absent(vaultrs::kv2::read(&self.inner, MOUNT, path).await)
}
/// The newest version of the object at `path` and its KV v2 [`Version`], or
@ -266,21 +262,7 @@ impl SecretStore {
.path(path)
.build()
.map_err(|e| Error::Settings(e.to_string()))?;
match vaultrs::api::exec_with_result(&self.inner, endpoint).await {
Ok(res) => {
let value = serde_json::from_value(res.data)
.map_err(|source| vaultrs::error::ClientError::JsonParseError { source })?;
Ok(Some((
value,
Version {
number: res.metadata.version,
created_time: res.metadata.created_time,
},
)))
}
Err(vaultrs::error::ClientError::APIError { code: 404, .. }) => Ok(None),
Err(e) => Err(e.into()),
}
versioned(vaultrs::api::exec_with_result(&self.inner, endpoint).await)
}
/// When the newest version at `path` was written, as the store spells the
@ -297,11 +279,8 @@ impl SecretStore {
/// [`Error::Vault`] for anything that is not a 404: a denial, or an
/// unreachable store.
pub async fn updated_time(&self, path: &str) -> Result<Option<String>, Error> {
match vaultrs::kv2::read_metadata(&self.inner, MOUNT, path).await {
Ok(meta) => Ok(Some(meta.updated_time)),
Err(e) if is_absent(&e) => Ok(None),
Err(e) => Err(e.into()),
}
let meta = none_when_absent(vaultrs::kv2::read_metadata(&self.inner, MOUNT, path).await)?;
Ok(meta.map(|meta| meta.updated_time))
}
/// The keys stored directly under `path`, or none when nothing is.
@ -323,11 +302,7 @@ impl SecretStore {
/// [`Error::Vault`] for anything that is not a 404: a denial, or an
/// unreachable store.
pub async fn list(&self, path: &str) -> Result<Vec<String>, Error> {
match vaultrs::kv2::list(&self.inner, MOUNT, path).await {
Ok(keys) => Ok(keys),
Err(e) if is_absent(&e) => Ok(Vec::new()),
Err(e) => Err(e.into()),
}
empty_when_absent(vaultrs::kv2::list(&self.inner, MOUNT, path).await)
}
/// Write `value` at `path`, creating a new version.
@ -384,11 +359,7 @@ impl SecretStore {
/// [`Error::Vault`] for anything that is not a 404 — a denial, or a store
/// that could not be reached.
pub async fn delete_all_versions(&self, path: &str) -> Result<(), Error> {
match vaultrs::kv2::delete_metadata(&self.inner, MOUNT, path).await {
Ok(()) => Ok(()),
Err(e) if is_absent(&e) => Ok(()),
Err(e) => Err(e.into()),
}
done_when_absent(vaultrs::kv2::delete_metadata(&self.inner, MOUNT, path).await)
}
/// Replace the ACL policy named `name` with `policy`.
@ -449,11 +420,7 @@ impl SecretStore {
mount: mount.to_owned(),
name: name.to_owned(),
};
match vaultrs::api::exec_with_result(&self.inner, request).await {
Ok(ttls) => Ok(Some(ttls)),
Err(e) if is_absent(&e) => Ok(None),
Err(e) => Err(e.into()),
}
none_when_absent(vaultrs::api::exec_with_result(&self.inner, request).await)
}
/// Set the token lifetimes of the existing cert-auth role `name` to
@ -484,11 +451,7 @@ impl SecretStore {
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()),
}
ssh_ca_key(vaultrs::api::exec_with_result(&self.inner, request).await)
}
/// The policies the cert-auth role `name` attaches to its tokens, or `None`
@ -505,11 +468,8 @@ impl SecretStore {
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()),
}
let role = none_when_absent(vaultrs::api::exec_with_result(&self.inner, request).await)?;
Ok(role.map(|role: CertRolePolicies| role.token_policies))
}
/// Replace the policies the existing cert-auth role `name` attaches, leaving
@ -526,12 +486,11 @@ impl SecretStore {
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?;
vaultrs::api::exec_with_empty(
&self.inner,
set_cert_role_policies_request(mount, name, policies),
)
.await?;
Ok(())
}
@ -571,11 +530,11 @@ impl SecretStore {
/// [`Error::Vault`] for anything that is not a 404: a denial, or an
/// unreachable store.
pub async fn list_cert_roles(&self, mount: &str) -> Result<Vec<String>, Error> {
match vaultrs::auth::cert::ca_cert_role::list(&self.inner, mount).await {
Ok(listed) => Ok(listed.keys),
Err(vaultrs::error::ClientError::APIError { code: 404, .. }) => Ok(Vec::new()),
Err(e) => Err(e.into()),
}
empty_when_absent(
vaultrs::auth::cert::ca_cert_role::list(&self.inner, mount)
.await
.map(|listed| listed.keys),
)
}
/// The accessor of the auth method mounted at `mount`: the id an entity
@ -612,15 +571,7 @@ impl SecretStore {
alias_name: alias_name.to_owned(),
alias_mount_accessor: mount_accessor.to_owned(),
};
match vaultrs::api::exec_with_result(&self.inner, request).await {
Ok(entity) => Ok(Some(entity)),
// A lookup that finds nothing is answered with an empty 204, which
// does not parse as the envelope. Any other parse failure stays one.
Err(vaultrs::error::ClientError::RestClientError {
source: rustify::errors::ClientError::ResponseParseError { content, .. },
}) if content.as_deref().is_none_or(str::is_empty) => Ok(None),
Err(e) => Err(e.into()),
}
entity_from_lookup(vaultrs::api::exec_with_result(&self.inner, request).await)
}
/// The id of the identity entity named `name`, or `None` when there is
@ -633,11 +584,8 @@ impl SecretStore {
let request = ReadEntityByName {
name: name.to_owned(),
};
match vaultrs::api::exec_with_result(&self.inner, request).await {
Ok(entity) => Ok(Some(entity.id)),
Err(e) if is_absent(&e) => Ok(None),
Err(e) => Err(e.into()),
}
let entity = none_when_absent(vaultrs::api::exec_with_result(&self.inner, request).await)?;
Ok(entity.map(|entity: EntityRef| entity.id))
}
/// Create the identity entity `name` with no policies, metadata or
@ -701,11 +649,7 @@ impl SecretStore {
/// [`Error::Vault`] when the token's policy does not cover
/// `auth/<mount>/certs/<name>`, or the store is unreachable.
pub async fn delete_cert_role(&self, mount: &str, name: &str) -> Result<(), Error> {
match vaultrs::auth::cert::ca_cert_role::delete(&self.inner, mount, name).await {
Ok(()) => Ok(()),
Err(e) if is_absent(&e) => Ok(()),
Err(e) => Err(e.into()),
}
done_when_absent(vaultrs::auth::cert::ca_cert_role::delete(&self.inner, mount, name).await)
}
/// Attach the alias `alias_name` on the auth mount `mount_accessor` to
@ -834,6 +778,77 @@ fn is_bad_request(e: &vaultrs::error::ClientError) -> bool {
matches!(e, vaultrs::error::ClientError::APIError { code: 400, .. })
}
/// A store answer where a 404 means "nothing there": `Ok(None)`.
///
/// The one rule [`SecretStore::read_optional`] documents, kept in one place so
/// every reader of an optional thing states it the same way. Anything else
/// that failed stays the store's own error, a 403 included.
fn none_when_absent<T>(answer: Result<T, vaultrs::error::ClientError>) -> Result<Option<T>, Error> {
match answer {
Ok(value) => Ok(Some(value)),
Err(e) if is_absent(&e) => Ok(None),
Err(e) => Err(e.into()),
}
}
/// [`none_when_absent`] for a listing: a 404 is the empty list.
fn empty_when_absent(
answer: Result<Vec<String>, vaultrs::error::ClientError>,
) -> Result<Vec<String>, Error> {
none_when_absent(answer).map(Option::unwrap_or_default)
}
/// [`none_when_absent`] for a delete: a 404 is a delete that was done already.
fn done_when_absent(answer: Result<(), vaultrs::error::ClientError>) -> Result<(), Error> {
none_when_absent(answer).map(|_| ())
}
/// The SSH CA's public key as one trimmed line, or `None` when the mount holds
/// no CA yet: the store answers that with a 404 or a 400, or with an empty key.
fn ssh_ca_key(answer: Result<SshCa, vaultrs::error::ClientError>) -> Result<Option<String>, Error> {
match answer {
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 entity an alias lookup found, or `None` when it found nothing.
///
/// A lookup that finds nothing is answered with an empty 204, which does not
/// parse as the envelope. Any other parse failure stays one.
fn entity_from_lookup(
answer: Result<EntityRef, vaultrs::error::ClientError>,
) -> Result<Option<EntityRef>, Error> {
match answer {
Ok(entity) => Ok(Some(entity)),
Err(vaultrs::error::ClientError::RestClientError {
source: rustify::errors::ClientError::ResponseParseError { content, .. },
}) if content.as_deref().is_none_or(str::is_empty) => Ok(None),
Err(e) => Err(e.into()),
}
}
/// A KV v2 read decoded as `T`, with the [`Version`] it was stored as, or
/// `None` on a 404. A body that does not decode as `T` is an error, not an
/// absence.
fn versioned<T: DeserializeOwned>(
answer: Result<vaultrs::api::kv2::responses::ReadSecretResponse, vaultrs::error::ClientError>,
) -> Result<Option<(T, Version)>, Error> {
let Some(res) = none_when_absent(answer)? else {
return Ok(None);
};
let value = serde_json::from_value(res.data)
.map_err(|source| vaultrs::error::ClientError::JsonParseError { source })?;
Ok(Some((
value,
Version {
number: res.metadata.version,
created_time: res.metadata.created_time,
},
)))
}
/// 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
@ -951,6 +966,19 @@ fn set_cert_role_token_ttls_request(mount: &str, name: &str) -> SetCertRoleTtls
}
}
/// The request [`SecretStore::set_cert_role_policies`] sends.
fn set_cert_role_policies_request(
mount: &str,
name: &str,
policies: &[&str],
) -> SetCertRolePolicies {
SetCertRolePolicies {
mount: mount.to_owned(),
name: name.to_owned(),
token_policies: policies.iter().map(|p| (*p).to_owned()).collect(),
}
}
/// The options [`SecretStore::create`] writes with: version 0, which only a
/// path holding nothing is at.
fn create_only() -> vaultrs::api::kv2::requests::SetSecretRequestOptions {
@ -1433,4 +1461,258 @@ mod tests {
"identity/entity/name/atlas"
);
}
type StoreError = vaultrs::error::ClientError;
fn status(code: u16) -> StoreError {
StoreError::APIError {
code,
errors: vec![],
}
}
/// The status codes a store answers with that are not "nothing there".
const REFUSALS: [u16; 5] = [400, 403, 429, 500, 503];
fn names_status(e: &Error, code: u16) {
assert!(
matches!(e, Error::Vault(_)),
"a refusal is the store's own error: {e:?}"
);
assert!(
e.to_string().contains(&code.to_string()),
"the status {code} must be in the message: {e}"
);
}
#[test]
fn a_404_is_nothing_there_and_an_answer_is_the_value() {
assert_eq!(
none_when_absent(Ok::<_, StoreError>(7)).expect("ok"),
Some(7)
);
assert_eq!(
none_when_absent::<u8>(Err(status(404))).expect("a 404 is not a failure"),
None
);
}
#[test]
fn any_other_status_is_an_error_that_names_it() {
for code in REFUSALS {
let e = none_when_absent::<u8>(Err(status(code))).expect_err("a refusal stays one");
names_status(&e, code);
}
}
#[test]
fn a_404_listing_is_empty_and_a_denied_one_is_not() {
let keys = vec!["a".to_owned(), "b/".to_owned()];
assert_eq!(empty_when_absent(Ok(keys.clone())).expect("ok"), keys);
assert_eq!(
empty_when_absent(Err(status(404))).expect("a 404 is an empty directory"),
Vec::<String>::new()
);
for code in REFUSALS {
let e = empty_when_absent(Err(status(code))).expect_err("a refusal stays one");
names_status(&e, code);
}
}
#[test]
fn deleting_what_is_not_there_succeeds_and_a_denied_delete_does_not() {
done_when_absent(Ok(())).expect("a delete that landed");
done_when_absent(Err(status(404))).expect("deleted already");
for code in REFUSALS {
let e = done_when_absent(Err(status(code))).expect_err("a refusal stays one");
names_status(&e, code);
}
}
#[test]
fn a_mount_without_a_ca_answers_none_whether_it_says_404_400_or_blank() {
let ca = |key: &str| SshCa {
public_key: key.to_owned(),
};
assert_eq!(
ssh_ca_key(Ok(ca(" ssh-ed25519 AAAA ca\n"))).expect("ok"),
Some("ssh-ed25519 AAAA ca".to_owned()),
"one trimmed line"
);
assert_eq!(ssh_ca_key(Ok(ca(" \n"))).expect("ok"), None, "a blank key");
assert_eq!(ssh_ca_key(Err(status(404))).expect("ok"), None);
assert_eq!(ssh_ca_key(Err(status(400))).expect("ok"), None);
for code in [403, 429, 500, 503] {
let e = ssh_ca_key(Err(status(code))).expect_err("a refusal stays one");
names_status(&e, code);
}
}
fn parse_failure(content: Option<&str>) -> StoreError {
StoreError::RestClientError {
source: rustify::errors::ClientError::ResponseParseError {
source: std::io::Error::other("no JSON").into(),
content: content.map(str::to_owned),
},
}
}
#[test]
fn a_lookup_with_an_empty_answer_found_nothing() {
let entity = EntityRef {
id: "e1".to_owned(),
name: "atlas".to_owned(),
};
assert_eq!(
entity_from_lookup(Ok(entity.clone())).expect("ok"),
Some(entity)
);
for empty in [None, Some("")] {
assert_eq!(
entity_from_lookup(Err(parse_failure(empty))).expect("a 204 is no match"),
None,
"content {empty:?}"
);
}
}
#[test]
fn a_lookup_that_fails_for_any_other_reason_is_an_error() {
let e = entity_from_lookup(Err(parse_failure(Some("<html>bad gateway</html>"))))
.expect_err("a body that is not the envelope is not a miss");
assert!(matches!(e, Error::Vault(_)), "{e:?}");
for code in [404, 403, 500] {
let e = entity_from_lookup(Err(status(code))).expect_err("only a 204 is a miss");
names_status(&e, code);
}
}
fn stored(
data: &serde_json::Value,
version: u64,
) -> vaultrs::api::kv2::responses::ReadSecretResponse {
serde_json::from_value(serde_json::json!({
"data": data,
"metadata": {
"created_time": "2026-11-30T09:00:00.123Z",
"deletion_time": "",
"custom_metadata": null,
"destroyed": false,
"version": version,
},
}))
.expect("a KV v2 read answer")
}
#[test]
fn a_versioned_read_carries_the_number_and_the_time_it_was_stored_with() {
let (value, version) = versioned::<std::collections::BTreeMap<String, String>>(Ok(stored(
&serde_json::json!({"value": "v"}),
4,
)))
.expect("ok")
.expect("something is stored");
assert_eq!(value["value"], "v");
assert_eq!(
version,
Version {
number: 4,
created_time: "2026-11-30T09:00:00.123Z".to_owned(),
}
);
}
#[test]
fn a_versioned_read_of_nothing_is_none_and_of_a_denied_path_is_an_error() {
assert!(
versioned::<serde_json::Value>(Err(status(404)))
.expect("a 404 is nothing stored")
.is_none()
);
for code in REFUSALS {
let e =
versioned::<serde_json::Value>(Err(status(code))).expect_err("a refusal stays one");
names_status(&e, code);
}
}
#[test]
fn a_stored_object_of_the_wrong_shape_is_an_error_and_not_an_absence() {
let e = versioned::<std::collections::BTreeMap<String, String>>(Ok(stored(
&serde_json::json!(["not", "a", "map"]),
1,
)))
.expect_err("the shape belongs to the caller, so a mismatch is the caller's to see");
assert!(matches!(e, Error::Vault(_)), "{e:?}");
}
#[test]
fn a_role_read_decodes_the_two_lifetimes_and_the_policies_it_asks_for() {
let ttls: CertRoleTokenTtls = serde_json::from_value(serde_json::json!({
"token_ttl": 3600,
"token_max_ttl": 7200,
"certificate": "PEM",
"token_policies": ["p"],
}))
.expect("extra fields are ignored");
assert_eq!(
ttls,
CertRoleTokenTtls {
token_ttl: 3600,
token_max_ttl: 7200
}
);
let role: CertRolePolicies =
serde_json::from_value(serde_json::json!({"token_policies": ["a", "b"]}))
.expect("policies");
assert_eq!(role.token_policies, ["a", "b"]);
let none: CertRolePolicies =
serde_json::from_value(serde_json::json!({"token_ttl": 1})).expect("no policies");
assert!(
none.token_policies.is_empty(),
"a role with no policy key has none"
);
}
#[test]
fn the_role_and_ca_reads_address_the_paths_the_grant_names() {
use rustify::endpoint::Endpoint as _;
let ttls = ReadCertRoleTtls {
mount: "cert".to_owned(),
name: "hive-agent-a".to_owned(),
};
assert_eq!(ttls.path(), "auth/cert/certs/hive-agent-a");
assert!(matches!(ttls.method(), rustify::enums::RequestMethod::GET));
let policies = ReadCertRolePolicies {
mount: "cert".to_owned(),
name: "hive-agent-a".to_owned(),
};
assert_eq!(policies.path(), "auth/cert/certs/hive-agent-a");
let ca = ReadSshCa {
mount: "ssh-agents".to_owned(),
};
assert_eq!(ca.path(), "ssh-agents/config/ca");
assert!(matches!(ca.method(), rustify::enums::RequestMethod::GET));
}
/// As the lifetimes' write: the store keeps the fields a write leaves out,
/// so this one names the policies and nothing else.
#[test]
fn the_policy_write_names_the_policies_and_nothing_else() {
use rustify::endpoint::Endpoint as _;
let request = set_cert_role_policies_request("cert", "hive-agent-a", &["shared", "own"]);
assert_eq!(request.path(), "auth/cert/certs/hive-agent-a");
let body = request
.body()
.expect("the body serialises")
.expect("a write sends one");
let sent: serde_json::Value = serde_json::from_slice(&body).expect("JSON");
assert_eq!(
sent,
serde_json::json!({"token_policies": ["shared", "own"]})
);
}
}