Skip to main content

thru_base/
key_file.rs

1//! Owner-only filesystem storage shared by signing keys and API credentials.
2//! Signing keys additionally require a private parent and a single hard link.
3//!
4//! Signing key file format, version 1 (what the CLI writes):
5//!
6//! ```json
7//! {
8//!   "version": 1,
9//!   "key_type": "ed25519",
10//!   "public_key": "ta...",
11//!   "seed": "<64 hex characters>"
12//! }
13//! ```
14//!
15//! Readers also accept the legacy format: a bare 64-hex-character seed.
16
17use std::{
18    fs::{self, File, Metadata, OpenOptions},
19    io::{self, Read},
20    path::Path,
21};
22use zeroize::Zeroizing;
23
24use crate::{
25    signer::{LocalSigner, Signer},
26    tn_tools::Pubkey,
27};
28
29const MAX_KEY_FILE_BYTES: usize = 4096;
30
31/// Version of the JSON signing key file format.
32pub const KEY_FILE_VERSION: u64 = 1;
33/// The only key type version 1 defines.
34pub const KEY_FILE_KEY_TYPE: &str = "ed25519";
35
36/// How a signing key file was encoded.
37#[derive(Debug, Clone, Copy, PartialEq, Eq)]
38pub enum KeyFileFormat {
39    /// Version-1 JSON (`version`, `key_type`, `public_key`, `seed`).
40    Json,
41    /// Legacy bare 64-hex-character seed.
42    LegacyHex,
43}
44
45fn path_error(path: &Path, error: io::Error) -> io::Error {
46    io::Error::new(error.kind(), format!("{}: {error}", path.display()))
47}
48
49fn unsafe_path(path: &Path, message: &str) -> io::Error {
50    path_error(
51        path,
52        io::Error::new(io::ErrorKind::PermissionDenied, message),
53    )
54}
55
56/// Validate effective-user ownership and reject all group/other permissions.
57/// On non-Unix platforms, retain the CLI's portable file-type-only policy.
58pub fn validate_owner(metadata: &Metadata, path: &Path) -> io::Result<()> {
59    #[cfg(unix)]
60    {
61        use std::os::unix::fs::{MetadataExt, PermissionsExt};
62        if metadata.uid() != unsafe { libc::geteuid() }
63            || metadata.permissions().mode() & 0o077 != 0
64        {
65            return Err(unsafe_path(
66                path,
67                "Secret storage must be owned by this user with owner-only permissions",
68            ));
69        }
70    }
71    #[cfg(not(unix))]
72    let _ = (metadata, path);
73    Ok(())
74}
75
76pub fn inspect_private_dir(root: &Path) -> io::Result<Option<Metadata>> {
77    let metadata = match fs::symlink_metadata(root) {
78        Ok(metadata) => metadata,
79        Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(None),
80        Err(error) => return Err(path_error(root, error)),
81    };
82    if metadata.file_type().is_symlink() || !metadata.is_dir() {
83        return Err(unsafe_path(
84            root,
85            "Refusing a symlink or non-directory secret storage directory",
86        ));
87    }
88    validate_owner(&metadata, root)?;
89    Ok(Some(metadata))
90}
91
92/// Create missing private directories without chmod'ing existing directories.
93pub fn ensure_private_dir(root: &Path) -> io::Result<Metadata> {
94    if let Some(metadata) = inspect_private_dir(root)? {
95        return Ok(metadata);
96    }
97    let mut builder = fs::DirBuilder::new();
98    builder.recursive(true);
99    #[cfg(unix)]
100    {
101        use std::os::unix::fs::DirBuilderExt;
102        builder.mode(0o700);
103    }
104    builder
105        .create(root)
106        .map_err(|error| path_error(root, error))?;
107    inspect_private_dir(root)?.ok_or_else(|| {
108        path_error(
109            root,
110            io::Error::new(
111                io::ErrorKind::NotFound,
112                "Secret storage directory disappeared",
113            ),
114        )
115    })
116}
117
118/// Open only a regular, owner-only file without following a final symlink.
119/// O_NONBLOCK prevents a raced-in FIFO from hanging before the handle check.
120/// This API intentionally preserves the API-credential policy on hard links.
121pub fn secure_open(path: &Path, write: bool, create: bool) -> io::Result<File> {
122    let mut options = OpenOptions::new();
123    options.read(true).write(write).create(create);
124    #[cfg(unix)]
125    {
126        use std::os::unix::fs::OpenOptionsExt;
127        options
128            .mode(0o600)
129            .custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK);
130    }
131    match fs::symlink_metadata(path) {
132        Ok(metadata) => {
133            if metadata.file_type().is_symlink() || !metadata.is_file() {
134                return Err(unsafe_path(
135                    path,
136                    "Refusing a symlink or non-regular secret file",
137                ));
138            }
139            validate_owner(&metadata, path)?;
140        }
141        Err(error) if error.kind() == io::ErrorKind::NotFound => {}
142        Err(error) => return Err(path_error(path, error)),
143    }
144    let file = options
145        .open(path)
146        .map_err(|error| path_error(path, error))?;
147    let metadata = file.metadata().map_err(|error| path_error(path, error))?;
148    if !metadata.is_file() {
149        return Err(unsafe_path(path, "Secret storage must be a regular file"));
150    }
151    validate_owner(&metadata, path)?;
152    Ok(file)
153}
154
155/// Open a signing key relative to its already-validated parent descriptor.
156pub fn open_key_file(path: &Path) -> io::Result<File> {
157    #[cfg(unix)]
158    {
159        let parent = open_key_parent(path)?;
160        open_key_file_at(&parent, path)
161    }
162    #[cfg(not(unix))]
163    {
164        let parent = path
165            .parent()
166            .filter(|parent| !parent.as_os_str().is_empty())
167            .unwrap_or(Path::new("."));
168        inspect_private_dir(parent)?.ok_or_else(|| {
169            path_error(
170                parent,
171                io::Error::new(
172                    io::ErrorKind::NotFound,
173                    "Signing key directory does not exist",
174                ),
175            )
176        })?;
177        secure_open(path, false, false)
178    }
179}
180
181#[cfg(unix)]
182fn open_key_parent(path: &Path) -> io::Result<File> {
183    use std::os::unix::fs::OpenOptionsExt;
184
185    let parent = path
186        .parent()
187        .filter(|parent| !parent.as_os_str().is_empty())
188        .unwrap_or(Path::new("."));
189    let directory = OpenOptions::new()
190        .read(true)
191        .custom_flags(libc::O_DIRECTORY | libc::O_NOFOLLOW | libc::O_CLOEXEC)
192        .open(parent)
193        .map_err(|error| path_error(parent, error))?;
194    let metadata = directory
195        .metadata()
196        .map_err(|error| path_error(parent, error))?;
197    validate_owner(&metadata, parent)?;
198    Ok(directory)
199}
200
201#[cfg(unix)]
202fn open_key_file_at(parent: &File, path: &Path) -> io::Result<File> {
203    use std::{
204        ffi::CString,
205        os::{
206            fd::{AsRawFd, FromRawFd},
207            unix::{ffi::OsStrExt, fs::MetadataExt},
208        },
209    };
210
211    let name = path
212        .file_name()
213        .ok_or_else(|| unsafe_path(path, "Signing key path must name a regular file"))?;
214    let name = CString::new(name.as_bytes()).map_err(|_| {
215        path_error(
216            path,
217            io::Error::new(io::ErrorKind::InvalidInput, "Invalid signing key path"),
218        )
219    })?;
220    // The parent cannot be redirected by a rename after its ownership check.
221    let fd = unsafe {
222        libc::openat(
223            parent.as_raw_fd(),
224            name.as_ptr(),
225            libc::O_RDONLY | libc::O_NOFOLLOW | libc::O_NONBLOCK | libc::O_CLOEXEC,
226        )
227    };
228    if fd < 0 {
229        return Err(path_error(path, io::Error::last_os_error()));
230    }
231    // SAFETY: openat returned a new descriptor owned exclusively by this File.
232    let file = unsafe { File::from_raw_fd(fd) };
233    let metadata = file.metadata().map_err(|error| path_error(path, error))?;
234    if !metadata.is_file() {
235        return Err(unsafe_path(
236            path,
237            "Signing key storage must be a regular file",
238        ));
239    }
240    validate_owner(&metadata, path)?;
241    if metadata.nlink() != 1 {
242        return Err(unsafe_path(path, "Refusing a hard-linked signing key file"));
243    }
244    Ok(file)
245}
246
247fn invalid_key(message: &'static str) -> io::Error {
248    io::Error::new(io::ErrorKind::InvalidData, message)
249}
250
251/// The `seed` field decodes straight into zeroizing storage; its text is never
252/// kept or echoed.
253struct JsonSeed(Zeroizing<[u8; 32]>);
254
255impl<'de> serde::Deserialize<'de> for JsonSeed {
256    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
257        struct SeedVisitor;
258        impl serde::de::Visitor<'_> for SeedVisitor {
259            type Value = JsonSeed;
260            fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
261                formatter.write_str("a 64-character hex seed")
262            }
263            fn visit_str<E: serde::de::Error>(self, value: &str) -> Result<JsonSeed, E> {
264                let mut seed = Zeroizing::new([0; 32]);
265                hex::decode_to_slice(value, seed.as_mut())
266                    .map_err(|_| E::custom("invalid seed"))?;
267                Ok(JsonSeed(seed))
268            }
269        }
270        deserializer.deserialize_str(SeedVisitor)
271    }
272}
273
274#[derive(serde::Deserialize)]
275#[serde(deny_unknown_fields)]
276struct KeyFileV1 {
277    version: u64,
278    key_type: String,
279    public_key: String,
280    seed: JsonSeed,
281}
282
283fn decode_json_key(raw: &[u8]) -> io::Result<Zeroizing<[u8; 32]>> {
284    let file: KeyFileV1 = serde_json::from_slice(raw).map_err(|error| {
285        // serde messages can quote values; report only the position.
286        io::Error::new(
287            io::ErrorKind::InvalidData,
288            format!(
289                "Signing key file is not a valid version-1 key file (JSON error at line {}, column {})",
290                error.line(),
291                error.column()
292            ),
293        )
294    })?;
295    if file.version != KEY_FILE_VERSION {
296        return Err(invalid_key(
297            "Unsupported signing key file version; expected 1",
298        ));
299    }
300    if file.key_type != KEY_FILE_KEY_TYPE {
301        return Err(invalid_key(
302            "Unsupported signing key type; expected ed25519",
303        ));
304    }
305    let derived = Pubkey::from_bytes(&LocalSigner::from_seed(*file.seed.0).public_key());
306    if derived.as_str() != file.public_key {
307        return Err(invalid_key(
308            "Signing key file public_key does not match its seed",
309        ));
310    }
311    Ok(file.seed.0)
312}
313
314/// Decode a version-1 JSON key file or a legacy bare hex seed. Errors never
315/// include the input.
316pub fn decode_key_file(raw: &[u8]) -> io::Result<(Zeroizing<[u8; 32]>, KeyFileFormat)> {
317    if raw.len() > MAX_KEY_FILE_BYTES {
318        return Err(invalid_key("Signing key input exceeds the 4096-byte limit"));
319    }
320    let raw = raw.trim_ascii();
321    if raw.first() == Some(&b'{') {
322        return decode_json_key(raw).map(|seed| (seed, KeyFileFormat::Json));
323    }
324    let mut seed = Zeroizing::new([0; 32]);
325    hex::decode_to_slice(raw, seed.as_mut()).map_err(|_| {
326        invalid_key(
327            "Signing key must be a version-1 JSON key file or exactly 64 hexadecimal characters (a 32-byte seed)",
328        )
329    })?;
330    Ok((seed, KeyFileFormat::LegacyHex))
331}
332
333pub fn decode_seed(raw: &[u8]) -> io::Result<Zeroizing<[u8; 32]>> {
334    decode_key_file(raw).map(|(seed, _)| seed)
335}
336
337/// Encode `seed` as a version-1 JSON key file. The result holds the seed, so it
338/// is zeroized on drop; its capacity is reserved so no partial copy is left.
339pub fn encode_key_file(seed: &[u8; 32]) -> Zeroizing<String> {
340    let address = Pubkey::from_bytes(&LocalSigner::from_seed(*seed).public_key());
341    let mut hex_seed = Zeroizing::new([0; 64]);
342    hex::encode_to_slice(seed, hex_seed.as_mut()).expect("64-byte buffer for a 32-byte seed");
343    let mut out = Zeroizing::new(String::with_capacity(256));
344    out.push_str("{\n  \"version\": 1,\n  \"key_type\": \"ed25519\",\n  \"public_key\": \"");
345    out.push_str(address.as_str());
346    out.push_str("\",\n  \"seed\": \"");
347    out.push_str(std::str::from_utf8(hex_seed.as_ref()).expect("hex is ASCII"));
348    out.push_str("\"\n}\n");
349    out
350}
351
352/// Read at most 4097 bytes and report the format; never include reader data in
353/// diagnostics.
354pub fn read_key_file(reader: impl Read) -> io::Result<(Zeroizing<[u8; 32]>, KeyFileFormat)> {
355    let mut raw = Zeroizing::new([0; MAX_KEY_FILE_BYTES + 1]);
356    let mut length = 0;
357    let mut reader = reader.take(raw.len() as u64);
358    while length < raw.len() {
359        match reader.read(&mut raw[length..]) {
360            Ok(0) => break,
361            Ok(count) => length += count,
362            Err(error) if error.kind() == io::ErrorKind::Interrupted => continue,
363            Err(error) => {
364                return Err(io::Error::new(
365                    error.kind(),
366                    "Unable to read signing key input",
367                ));
368            }
369        }
370    }
371    decode_key_file(&raw[..length])
372}
373
374/// Read at most 4097 bytes; never include reader data in diagnostics.
375pub fn read_seed(reader: impl Read) -> io::Result<Zeroizing<[u8; 32]>> {
376    read_key_file(reader).map(|(seed, _)| seed)
377}
378
379#[cfg(test)]
380mod tests {
381    use super::*;
382
383    #[test]
384    fn seed_decoder_is_bounded_ascii_only_and_sanitized() {
385        let seed = "ab".repeat(32);
386        assert_eq!(
387            *decode_seed(format!(" \t\r\n{seed}\n").as_bytes()).unwrap(),
388            [0xab; 32]
389        );
390        assert_eq!(*read_seed(seed.as_bytes()).unwrap(), [0xab; 32]);
391        for raw in [
392            format!("\u{a0}{seed}").into_bytes(),
393            format!("\u{b}{seed}").into_bytes(),
394            format!("{seed}invalid").into_bytes(),
395            format!("{seed}{}", " ".repeat(4096)).into_bytes(),
396            vec![0xff; 64],
397            Vec::new(),
398        ] {
399            for error in [
400                decode_seed(&raw).unwrap_err(),
401                read_seed(raw.as_slice()).unwrap_err(),
402            ] {
403                assert_eq!(error.kind(), io::ErrorKind::InvalidData);
404                assert!(!error.to_string().contains(&seed));
405            }
406        }
407    }
408
409    #[test]
410    fn json_key_files_round_trip_and_are_strict_without_echo() {
411        let seed = [0x5a; 32];
412        let hex_seed = hex::encode(seed);
413        let encoded = encode_key_file(&seed);
414        let (decoded, format) = decode_key_file(encoded.as_bytes()).unwrap();
415        assert_eq!((*decoded, format), (seed, KeyFileFormat::Json));
416        assert_eq!(*read_seed(encoded.as_bytes()).unwrap(), seed);
417        assert_eq!(
418            decode_key_file(hex_seed.as_bytes()).unwrap().1,
419            KeyFileFormat::LegacyHex
420        );
421        let value: serde_json::Value = serde_json::from_str(&encoded).unwrap();
422        let address = Pubkey::from_bytes(&LocalSigner::from_seed(seed).public_key());
423        assert_eq!(value["public_key"], address.as_str());
424        assert_eq!(value["version"], 1);
425        assert_eq!(value["key_type"], "ed25519");
426
427        let other = Pubkey::from_bytes(&LocalSigner::from_seed([1; 32]).public_key());
428        let replace = |from: &str, to: &str| encoded.replace(from, to);
429        for (raw, expected) in [
430            (replace("\"version\": 1", "\"version\": 2"), "version"),
431            (replace("ed25519", "secp256k1"), "key type"),
432            (replace(address.as_str(), other.as_str()), "does not match"),
433            (
434                replace("\"version\": 1,", "\"version\": 1, \"extra\": 0,"),
435                "JSON",
436            ),
437            (replace("\"version\": 1,", ""), "JSON"),
438            (replace(&hex_seed, &hex_seed[..62]), "JSON"),
439            (
440                replace(&format!("\"{hex_seed}\""), &format!("[\"{hex_seed}\"]")),
441                "JSON",
442            ),
443            (replace("\n}\n", ""), "JSON"),
444        ] {
445            let error = decode_key_file(raw.as_bytes()).unwrap_err();
446            assert_eq!(error.kind(), io::ErrorKind::InvalidData);
447            let message = error.to_string();
448            assert!(message.contains(expected), "{message}");
449            assert!(!message.contains(&hex_seed[..16]), "{message}");
450        }
451    }
452
453    #[cfg(unix)]
454    #[test]
455    fn owner_only_read_only_modes_are_accepted_without_chmod() {
456        use std::os::unix::fs::PermissionsExt;
457        let directory = tempfile::tempdir().unwrap();
458        let path = directory.path().join("secret");
459        secure_open(&path, true, true).unwrap();
460        for file_mode in [0o400, 0o600, 0o700] {
461            fs::set_permissions(&path, fs::Permissions::from_mode(file_mode)).unwrap();
462            fs::set_permissions(directory.path(), fs::Permissions::from_mode(0o500)).unwrap();
463            assert!(open_key_file(&path).is_ok());
464            assert_eq!(
465                ensure_private_dir(directory.path())
466                    .unwrap()
467                    .permissions()
468                    .mode()
469                    & 0o777,
470                0o500
471            );
472        }
473        fs::set_permissions(directory.path(), fs::Permissions::from_mode(0o700)).unwrap();
474        for file_mode in [0o604, 0o640, 0o644, 0o660] {
475            fs::set_permissions(&path, fs::Permissions::from_mode(file_mode)).unwrap();
476            let error = open_key_file(&path).unwrap_err();
477            assert!(error.to_string().contains(&path.display().to_string()));
478        }
479        fs::set_permissions(&path, fs::Permissions::from_mode(0o400)).unwrap();
480        for directory_mode in [0o701, 0o710, 0o755] {
481            fs::set_permissions(directory.path(), fs::Permissions::from_mode(directory_mode))
482                .unwrap();
483            assert!(open_key_file(&path).is_err());
484            assert!(ensure_private_dir(directory.path()).is_err());
485            assert_eq!(
486                fs::metadata(directory.path()).unwrap().permissions().mode() & 0o777,
487                directory_mode
488            );
489        }
490        fs::set_permissions(directory.path(), fs::Permissions::from_mode(0o700)).unwrap();
491    }
492
493    #[cfg(unix)]
494    #[test]
495    fn child_open_stays_in_validated_parent_after_replacement() {
496        use std::os::unix::fs::{PermissionsExt, symlink};
497
498        for replace_with_symlink in [false, true] {
499            let root = tempfile::tempdir().unwrap();
500            let parent_path = root.path().join("keys");
501            fs::create_dir(&parent_path).unwrap();
502            fs::set_permissions(&parent_path, fs::Permissions::from_mode(0o700)).unwrap();
503            let path = parent_path.join("secret");
504            let original = "ab".repeat(32);
505            fs::write(&path, original).unwrap();
506            fs::set_permissions(&path, fs::Permissions::from_mode(0o400)).unwrap();
507            let parent = open_key_parent(&path).unwrap();
508
509            // Replace the pathname precisely between parent validation and openat.
510            fs::rename(&parent_path, root.path().join("original")).unwrap();
511            let replacement = root.path().join("replacement");
512            fs::create_dir(&replacement).unwrap();
513            fs::set_permissions(&replacement, fs::Permissions::from_mode(0o700)).unwrap();
514            let replacement_key = replacement.join("secret");
515            fs::write(&replacement_key, "cd".repeat(32)).unwrap();
516            fs::set_permissions(&replacement_key, fs::Permissions::from_mode(0o400)).unwrap();
517            if replace_with_symlink {
518                symlink(&replacement, &parent_path).unwrap();
519            } else {
520                fs::rename(&replacement, &parent_path).unwrap();
521            }
522
523            assert_eq!(
524                *read_seed(open_key_file_at(&parent, &path).unwrap()).unwrap(),
525                [0xab; 32]
526            );
527        }
528    }
529
530    #[cfg(unix)]
531    #[test]
532    fn signing_files_reject_links_and_non_regular_files() {
533        use std::os::unix::fs::symlink;
534        let directory = tempfile::tempdir().unwrap();
535        use std::os::unix::fs::PermissionsExt;
536        fs::set_permissions(directory.path(), fs::Permissions::from_mode(0o700)).unwrap();
537        let path = directory.path().join("secret");
538        secure_open(&path, true, true).unwrap();
539        let link = directory.path().join("link");
540        symlink(&path, &link).unwrap();
541        assert!(secure_open(&link, false, false).is_err());
542        assert!(secure_open(directory.path(), false, false).is_err());
543        fs::remove_file(&link).unwrap();
544        fs::hard_link(&path, &link).unwrap();
545        assert!(open_key_file(&path).is_err());
546        assert!(secure_open(&path, false, false).is_ok());
547        let fifo = directory.path().join("fifo");
548        let fifo_path = std::ffi::CString::new(fifo.as_os_str().as_encoded_bytes()).unwrap();
549        assert_eq!(unsafe { libc::mkfifo(fifo_path.as_ptr(), 0o600) }, 0);
550        assert!(open_key_file(&fifo).is_err());
551        let parent_link = directory.path().join("parent");
552        symlink(directory.path(), &parent_link).unwrap();
553        assert!(open_key_file(&parent_link.join("secret")).is_err());
554        let missing = directory.path().join("missing");
555        assert!(
556            open_key_file(&missing)
557                .unwrap_err()
558                .to_string()
559                .contains(&missing.display().to_string())
560        );
561    }
562}