From 98fe0310def5c176c6f8fa35a583fa063982636e Mon Sep 17 00:00:00 2001 From: Zac Mrowicki Date: Wed, 15 Apr 2020 18:29:47 +0000 Subject: [PATCH] Initial commit of KeySource trait This commit adds the KeySource trait to tough. It is meant to replace the KeySource enum in tuftool and allows for users to implement their own sources of Keys. Initially we implement this trait for local files. --- tough/src/error.rs | 14 +++++++++++++ tough/src/key_source.rs | 45 +++++++++++++++++++++++++++++++++++++++++ tough/src/lib.rs | 1 + 3 files changed, 60 insertions(+) create mode 100644 tough/src/key_source.rs diff --git a/tough/src/error.rs b/tough/src/error.rs index 85e207b1..fb9907a4 100644 --- a/tough/src/error.rs +++ b/tough/src/error.rs @@ -57,6 +57,20 @@ pub enum Error { backtrace: Backtrace, }, + #[snafu(display("Failed to read {}: {}", path.display(), source))] + FileRead { + path: PathBuf, + source: std::io::Error, + backtrace: Backtrace, + }, + + #[snafu(display("Failed to write to {}: {}", path.display(), source))] + FileWrite { + path: PathBuf, + source: std::io::Error, + backtrace: Backtrace, + }, + /// A downloaded target's checksum does not match the checksum listed in the repository /// metadata. #[snafu(display( diff --git a/tough/src/key_source.rs b/tough/src/key_source.rs new file mode 100644 index 00000000..df47cfa1 --- /dev/null +++ b/tough/src/key_source.rs @@ -0,0 +1,45 @@ +// Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: MIT OR Apache-2.0 + +use crate::error; +use crate::sign::{parse_keypair, Sign}; +use snafu::ResultExt; +use std::fmt::Debug; +use std::path::PathBuf; +use std::result::Result; + +/// This trait should be implemented for each source of signing keys. Examples +/// of sources include: files, AWS SSM, etc. +pub trait KeySource: Debug + Send + Sync { + /// Returns an object that implements the `Sign` trait + fn as_sign(&self) -> Result, Box>; + + /// Writes a key back to the `KeySource` + fn write( + &self, + value: &str, + key_id_hex: &str, + ) -> Result<(), Box>; +} + +#[derive(Debug)] +pub struct LocalKeySource { + pub path: PathBuf, +} + +/// Implements the `KeySource` trait for a `LocalKeySource` (file) +impl KeySource for LocalKeySource { + fn as_sign(&self) -> Result, Box> { + let data = std::fs::read(&self.path).context(error::FileRead { path: &self.path })?; + Ok(Box::new(parse_keypair(&data)?)) + } + + fn write( + &self, + value: &str, + _key_id_hex: &str, + ) -> Result<(), Box> { + Ok(std::fs::write(&self.path, value.as_bytes()) + .context(error::FileWrite { path: &self.path })?) + } +} diff --git a/tough/src/lib.rs b/tough/src/lib.rs index 1f01e995..9c35a1ed 100644 --- a/tough/src/lib.rs +++ b/tough/src/lib.rs @@ -24,6 +24,7 @@ mod datastore; pub mod error; mod fetch; mod io; +pub mod key_source; pub mod schema; pub mod sign; mod transport;