use std::path::Path;
use adk_awp::signing::jws::jwk_thumbprint;
use awp_types::PublicKeyJwk;
use serde::{Deserialize, Serialize};
use super::bundle::PackError;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct TrustedKey {
pub publisher: String,
pub kid: String,
pub public_key: PublicKeyJwk,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub note: Option<String>,
}
impl TrustedKey {
pub fn new(
publisher: impl Into<String>,
kid: impl Into<String>,
public_key: PublicKeyJwk,
) -> Self {
Self { publisher: publisher.into(), kid: kid.into(), public_key, note: None }
}
#[must_use]
pub fn noted(mut self, note: impl Into<String>) -> Self {
self.note = Some(note.into());
self
}
pub fn thumbprint(&self) -> String {
jwk_thumbprint(&self.public_key)
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct TrustList {
#[serde(default)]
pub keys: Vec<TrustedKey>,
}
impl TrustList {
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn with(mut self, key: TrustedKey) -> Self {
self.add(key);
self
}
pub fn add(&mut self, key: TrustedKey) -> bool {
if self.keys.iter().any(|held| {
held.publisher == key.publisher
&& held.kid == key.kid
&& held.public_key == key.public_key
}) {
return false;
}
self.keys.retain(|held| !(held.publisher == key.publisher && held.kid == key.kid));
self.keys.push(key);
true
}
pub fn key(&self, publisher: &str, kid: &str) -> Option<&PublicKeyJwk> {
self.keys
.iter()
.find(|key| key.publisher == publisher && key.kid == kid)
.map(|key| &key.public_key)
}
pub fn read(path: &Path) -> Result<Self, PackError> {
match std::fs::read(path) {
Ok(bytes) => serde_json::from_slice(&bytes).map_err(|error| {
PackError::Io(format!("{} is not a pack trust list: {error}", path.display()))
}),
Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(Self::new()),
Err(error) => Err(PackError::Io(format!("{}: {error}", path.display()))),
}
}
pub fn write(&self, path: &Path) -> Result<(), PackError> {
let mut bytes =
serde_json::to_vec_pretty(self).map_err(|error| PackError::Io(error.to_string()))?;
bytes.push(b'\n');
super::installed::write_atomically(path, &bytes)
}
}