1use crate::error::Error;
4use std::fmt;
5
6#[derive(Copy, Clone, Debug, PartialEq, Eq)]
8pub enum DigestAlgorithm {
9 Sha256,
10}
11
12#[derive(Copy, Clone, Debug, PartialEq, Eq)]
14pub enum SigningAlgorithm {
15 RsaSha256,
16}
17
18pub enum Key<'a> {
20 Pkcs8(&'a [u8]),
23 Der(&'a [u8]),
26 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
42pub trait DigestCalulator {
44 fn digest(&self, algorithm: DigestAlgorithm, data: &[u8], output_digest: &mut [u8]);
47}
48
49pub trait Signer {
51 fn sign(
53 &self,
54 algorithm: SigningAlgorithm,
55 key: Key<'_>,
56 data: &[u8],
57 ) -> Result<Vec<u8>, Error>;
58}
59
60#[derive(Deserialize, Debug, Clone)]
62struct ServiceAccountInfo {
63 private_key: String,
65 client_email: String,
67}
68
69pub trait KeyProvider {
71 fn key(&self) -> Key<'_>;
73 fn authorizer(&self) -> &str;
76}
77
78pub struct ServiceAccount {
81 key: Vec<u8>,
82 email: String,
83}
84
85impl ServiceAccount {
86 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 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 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#[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#[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}