thru_base/
key_reference.rs1use std::{
6 io,
7 path::{Path, PathBuf},
8};
9
10use serde::Deserialize;
11use zeroize::Zeroizing;
12
13use crate::{
14 key_file,
15 signer::{LocalSigner, Signer},
16 tn_tools::Pubkey,
17};
18
19#[derive(Debug, Clone, Deserialize)]
21#[serde(tag = "type", deny_unknown_fields)]
22pub enum KeySource {
23 #[serde(rename = "file")]
24 File {
25 path: PathBuf,
26 #[serde(default)]
27 managed: bool,
28 },
29 #[serde(rename = "macos-keychain")]
30 MacosKeychain { id: String },
31}
32
33#[derive(Debug, Clone, Deserialize)]
35#[serde(deny_unknown_fields)]
36pub struct KeyReference {
37 pub public_key: String,
38 pub source: KeySource,
39}
40
41impl KeyReference {
42 pub fn expected_public_key(&self) -> io::Result<[u8; 32]> {
44 let invalid = |message: &'static str| io::Error::new(io::ErrorKind::InvalidData, message);
45 let expected = Pubkey::new(self.public_key.clone())
46 .and_then(|public_key| public_key.to_bytes())
47 .map_err(|_| invalid("Invalid signing key public_key metadata"))?;
48 if Pubkey::from_bytes(&expected).as_str() != self.public_key {
49 return Err(invalid(
50 "Signing key public_key metadata must be a canonical ta address",
51 ));
52 }
53 Ok(expected)
54 }
55
56 pub fn load_file_seed(
60 &self,
61 base_dir: &Path,
62 ) -> io::Result<(Zeroizing<[u8; 32]>, [u8; 32])> {
63 let path = match &self.source {
64 KeySource::File { path, .. } => base_dir.join(path),
65 KeySource::MacosKeychain { .. } => {
66 return Err(io::Error::new(
67 io::ErrorKind::Unsupported,
68 "A dedicated file-backed signing key is required; macos-keychain sources are unsupported and will not be exported or used as a fallback",
69 ));
70 }
71 };
72 let expected = self.expected_public_key()?;
73 #[cfg(not(unix))]
74 return Err(io::Error::new(
75 io::ErrorKind::Unsupported,
76 format!(
77 "{}: signing key files require Unix ownership and permission checks",
78 path.display()
79 ),
80 ));
81 #[cfg(unix)]
82 {
83 let file = key_file::open_key_file(&path)?;
84 let seed = key_file::read_seed(file).map_err(|error| {
85 io::Error::new(
86 error.kind(),
87 format!("Signing key file {}: {error}", path.display()),
88 )
89 })?;
90 let public_key = LocalSigner::from_seed(*seed).public_key();
91 if public_key != expected {
92 return Err(io::Error::new(
93 io::ErrorKind::InvalidData,
94 format!(
95 "Signing key file {} does not match public_key metadata",
96 path.display()
97 ),
98 ));
99 }
100 Ok((seed, public_key))
101 }
102 }
103}
104
105#[cfg(all(test, unix))]
106mod tests {
107 use super::*;
108 use std::os::unix::fs::PermissionsExt;
109
110 fn reference(directory: &Path, seed: &str) -> KeyReference {
111 let path = directory.join("k.hex");
112 std::fs::write(&path, format!("\n{seed}\t\n")).unwrap();
113 std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600)).unwrap();
114 let mut bytes = [0u8; 32];
115 hex::decode_to_slice(seed, &mut bytes).unwrap();
116 let public_key = LocalSigner::from_seed(bytes).public_key();
117 KeyReference {
118 public_key: Pubkey::from_bytes(&public_key).as_str().to_string(),
119 source: KeySource::File {
120 path: PathBuf::from("k.hex"),
121 managed: false,
122 },
123 }
124 }
125
126 #[test]
127 fn matches_canonical_public_key_and_rejects_mismatch_without_echo() {
128 let directory = tempfile::tempdir().unwrap();
129 std::fs::set_permissions(directory.path(), std::fs::Permissions::from_mode(0o700)).unwrap();
130 let seed = "ab".repeat(32);
131 let mut entry = reference(directory.path(), &seed);
132 let (loaded, public_key) = entry.load_file_seed(directory.path()).unwrap();
133 assert_eq!(*loaded, [0xab; 32]);
134 assert_eq!(public_key, entry.expected_public_key().unwrap());
135
136 entry.public_key = Pubkey::from_bytes(&[0; 32]).as_str().to_string();
137 let error = entry.load_file_seed(directory.path()).unwrap_err().to_string();
138 assert!(error.contains("does not match") && !error.contains(&seed));
139 entry.public_key = seed.clone();
140 let error = entry.load_file_seed(directory.path()).unwrap_err().to_string();
141 assert!(error.contains("metadata") && !error.contains(&seed));
142
143 entry.source = KeySource::MacosKeychain { id: "k.hex".into() };
144 let error = entry.load_file_seed(directory.path()).unwrap_err().to_string();
145 assert!(error.contains("file-backed") && !error.contains("k.hex"));
146 }
147}