dnapi_rs/
credentials.rs

1//! Contains the `Credentials` struct, which contains all keys, IDs, organizations and other identity-related and security-related data that is persistent in a `Client`
2
3use serde::{Deserialize, Serialize};
4use std::error::Error;
5use trifid_pki::cert::{deserialize_ed25519_public_many, serialize_ed25519_public};
6use trifid_pki::ed25519_dalek::{SigningKey, VerifyingKey};
7
8#[derive(Serialize, Deserialize, Clone)]
9/// Contains information necessary to make requests against the `DNClient` API.
10pub struct Credentials {
11    /// The assigned Host ID that this client represents
12    pub host_id: String,
13    /// The ed25519 private key used to sign requests against the API
14    pub ed_privkey: SigningKey,
15    /// The counter used in the other API requests. It is unknown what the purpose of this is, but the original client persists it and it is needed for API calls.
16    pub counter: u32,
17    /// The set of trusted ed25519 keys that may be used by the API to sign API responses.
18    pub trusted_keys: Vec<VerifyingKey>,
19}
20
21/// Converts an array of `VerifyingKey`s to a singular bundle of PEM-encoded keys
22pub fn ed25519_public_keys_to_pem(keys: &[VerifyingKey]) -> Vec<u8> {
23    let mut res = vec![];
24
25    for key in keys {
26        res.append(&mut serialize_ed25519_public(&key.to_bytes()));
27    }
28
29    res
30}
31
32/// Converts a set of PEM-encoded ed25519 public keys, and converts them into an array of `VerifyingKey`s.
33/// # Errors
34/// This function will return an error if the PEM could not be decoded, or if any of the encoded keys are invalid.
35pub fn ed25519_public_keys_from_pem(pem: &[u8]) -> Result<Vec<VerifyingKey>, Box<dyn Error>> {
36    let pems = deserialize_ed25519_public_many(pem)?;
37    let mut keys = vec![];
38
39    #[allow(clippy::unwrap_used)]
40    for pem in pems {
41        keys.push(VerifyingKey::from_bytes(
42            &pem.try_into().unwrap_or_else(|_| unreachable!()),
43        )?);
44    }
45
46    Ok(keys)
47}