Skip to main content

tame_gcs/
signing.rs

1//! Helper facilities for calculating content digests and signing data
2
3use crate::error::Error;
4use std::fmt;
5
6/// The supported algorithms for creating a digest of content
7#[derive(Copy, Clone, Debug, PartialEq, Eq)]
8pub enum DigestAlgorithm {
9    Sha256,
10}
11
12/// The supported algorithms for signing payloads
13#[derive(Copy, Clone, Debug, PartialEq, Eq)]
14pub enum SigningAlgorithm {
15    RsaSha256,
16}
17
18/// The supported key formats
19pub enum Key<'a> {
20    /// Unencrypted PKCS#8 RSA private key. See [ring](https://briansmith.org/rustdoc/ring/signature/struct.RsaKeyPair.html#method.from_pkcs8)
21    /// for more information
22    Pkcs8(&'a [u8]),
23    /// Uncencrypted RSA private key that isn't wrapped in PKCS#8. See [ring](https://briansmith.org/rustdoc/ring/signature/struct.RsaKeyPair.html#method.from_der)
24    /// for more information
25    Der(&'a [u8]),
26    /// See [ring](https://briansmith.org/rustdoc/ring/hmac/index.html) for more information.
27    Hmac(&'a [u8]),
28}
29
30impl fmt::Debug for Key<'_> {
31    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
32        let name = match self {
33            Key::Pkcs8(_) => "pkcs8",
34            Key::Der(_) => "der",
35            Key::Hmac(_) => "hmac",
36        };
37
38        write!(f, "{}", name)
39    }
40}
41
42/// Used to calculate a digest of payloads with a specific algorithm
43pub trait DigestCalulator {
44    /// Calculate a digest of a block of data, the algorithm determines the size
45    /// of the slice used for returning the digest
46    fn digest(&self, algorithm: DigestAlgorithm, data: &[u8], output_digest: &mut [u8]);
47}
48
49/// Used to sign a block of data
50pub trait Signer {
51    /// Sign a block of data with the specified algorith, and a private key
52    fn sign(
53        &self,
54        algorithm: SigningAlgorithm,
55        key: Key<'_>,
56        data: &[u8],
57    ) -> Result<Vec<u8>, Error>;
58}
59
60/// Internal type use to grab the pieces of the service account we need for signing
61#[derive(Deserialize, Debug, Clone)]
62struct ServiceAccountInfo {
63    /// The private key we use to sign
64    private_key: String,
65    /// The unique id used as the issuer of the JWT claim
66    client_email: String,
67}
68
69/// Provides the details needed for signing a URL
70pub trait KeyProvider {
71    /// The actual key used to sign the URL
72    fn key(&self) -> Key<'_>;
73    /// The identifier for the key author, in GCP this is the email
74    /// address of the service account
75    fn authorizer(&self) -> &str;
76}
77
78/// A [GCP service account](https://cloud.google.com/iam/docs/creating-managing-service-account-keys),
79/// used as a `KeyProvider` when signing URLs.
80pub struct ServiceAccount {
81    key: Vec<u8>,
82    email: String,
83}
84
85impl ServiceAccount {
86    /// Attempts to load a service account from a JSON file
87    pub fn load_json_file<P: AsRef<std::path::Path>>(path: P) -> Result<Self, Error> {
88        let file_content = std::fs::read(path)?;
89        Self::load_json(file_content)
90    }
91
92    /// Attempts to load a service account from a JSON byte slice
93    pub fn load_json<B: AsRef<[u8]>>(json_data: B) -> Result<Self, Error> {
94        let info: ServiceAccountInfo = serde_json::from_slice(json_data.as_ref())?;
95
96        let key_string = info
97            .private_key
98            .split("-----")
99            .nth(2)
100            .ok_or_else(|| Error::KeyRejected("invalid key format".to_owned()))?;
101
102        // Strip out all of the newlines
103        let key_string = key_string.split_whitespace().fold(
104            String::with_capacity(key_string.len()),
105            |mut s, line| {
106                s.push_str(line);
107                s
108            },
109        );
110
111        let key_bytes = data_encoding::BASE64
112            .decode(key_string.as_bytes())
113            .map_err(Error::Base64Decode)?;
114
115        Ok(Self {
116            key: key_bytes,
117            email: info.client_email,
118        })
119    }
120}
121
122impl KeyProvider for ServiceAccount {
123    fn key(&self) -> Key<'_> {
124        Key::Pkcs8(&self.key)
125    }
126
127    fn authorizer(&self) -> &str {
128        &self.email
129    }
130}
131
132/// Implements `DigestCalculator` via [`ring`](https://briansmith.org/rustdoc/ring/digest/index.html)
133#[cfg(feature = "signing")]
134pub struct RingDigest;
135
136#[cfg(feature = "signing")]
137impl DigestCalulator for RingDigest {
138    fn digest(&self, algorithm: DigestAlgorithm, data: &[u8], output_digest: &mut [u8]) {
139        use ring::digest;
140
141        match algorithm {
142            DigestAlgorithm::Sha256 => {
143                assert_eq!(
144                    output_digest.len(),
145                    32,
146                    "output digest has invalid length for Sha256"
147                );
148                let digest = digest::digest(&digest::SHA256, data);
149                output_digest.copy_from_slice(digest.as_ref());
150            }
151        }
152    }
153}
154
155/// Implements `Signer` via [`ring`](https://briansmith.org/rustdoc/ring/signature/index.html)
156#[cfg(feature = "signing")]
157pub struct RingSigner;
158
159#[cfg(feature = "signing")]
160impl Signer for RingSigner {
161    fn sign(
162        &self,
163        algorithm: SigningAlgorithm,
164        key: Key<'_>,
165        data: &[u8],
166    ) -> Result<Vec<u8>, Error> {
167        match algorithm {
168            SigningAlgorithm::RsaSha256 => {
169                let key_pair = match key {
170                    Key::Pkcs8(key) => ring::signature::RsaKeyPair::from_pkcs8(key),
171                    Key::Der(key) => ring::signature::RsaKeyPair::from_der(key),
172                    Key::Hmac(_) => {
173                        return Err(Error::KeyRejected(
174                            "HMAC cannot be used with RSA signing".to_owned(),
175                        ));
176                    }
177                }?;
178
179                let mut signature = vec![0; key_pair.public().modulus_len()];
180                let rng = ring::rand::SystemRandom::new();
181
182                key_pair.sign(
183                    &ring::signature::RSA_PKCS1_SHA256,
184                    &rng,
185                    data,
186                    &mut signature,
187                )?;
188
189                Ok(signature)
190            }
191        }
192    }
193}
194
195#[cfg(test)]
196mod test {
197    #[test]
198    fn loads_svc_account() {
199        use super::KeyProvider;
200
201        let acct = super::ServiceAccount::load_json_file("./tests/test_account.json").unwrap();
202
203        match acct.key() {
204            super::Key::Pkcs8(_) => {}
205            key => panic!("invalid key format {:?}", key),
206        }
207
208        assert_eq!(
209            acct.authorizer(),
210            "real-address@very-good-project-id.iam.gserviceaccount.com"
211        );
212    }
213}