Skip to content

Commit c67fb80

Browse files
committed
Load keys concurrently
Signed-off-by: Kai A. Hiller <[email protected]>
1 parent ec693ed commit c67fb80

File tree

1 file changed

+19
-17
lines changed

1 file changed

+19
-17
lines changed

crates/config/src/sections/secrets.rs

Lines changed: 19 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ use std::borrow::Cow;
88

99
use anyhow::{Context, bail};
1010
use camino::Utf8PathBuf;
11+
use futures::future::{try_join, try_join_all};
1112
use mas_jose::jwk::{JsonWebKey, JsonWebKeySet};
1213
use mas_keystore::{Encrypter, Keystore, PrivateKey};
1314
use rand::{
@@ -161,6 +162,22 @@ impl KeyConfig {
161162
Key::Value(key) => Cow::Borrowed(key),
162163
})
163164
}
165+
166+
/// Returns the JSON Web Key derived from this key config.
167+
///
168+
/// Password and/or key are read from file if they’re given as path.
169+
async fn json_web_key(&self) -> anyhow::Result<JsonWebKey<mas_keystore::PrivateKey>> {
170+
let (key, password) = try_join(self.key(), self.password()).await?;
171+
172+
let private_key = match password {
173+
Some(password) => PrivateKey::load_encrypted(key.as_bytes(), password.as_bytes())?,
174+
None => PrivateKey::load(key.as_bytes())?,
175+
};
176+
177+
Ok(JsonWebKey::new(private_key)
178+
.with_kid(self.kid.clone())
179+
.with_use(mas_iana::jose::JsonWebKeyUse::Sig))
180+
}
164181
}
165182

166183
/// Application secrets
@@ -189,24 +206,9 @@ impl SecretsConfig {
189206
/// Returns an error when a key could not be imported
190207
#[tracing::instrument(name = "secrets.load", skip_all)]
191208
pub async fn key_store(&self) -> anyhow::Result<Keystore> {
192-
let mut keys = Vec::with_capacity(self.keys.len());
193-
for item in &self.keys {
194-
let password = item.password().await?;
195-
196-
let key = item.key().await?;
197-
let private_key = match password {
198-
Some(password) => PrivateKey::load_encrypted(key.as_bytes(), password.as_bytes())?,
199-
None => PrivateKey::load(key.as_bytes())?,
200-
};
201-
202-
let key = JsonWebKey::new(private_key)
203-
.with_kid(item.kid.clone())
204-
.with_use(mas_iana::jose::JsonWebKeyUse::Sig);
205-
keys.push(key);
206-
}
209+
let web_keys = try_join_all(self.keys.iter().map(KeyConfig::json_web_key)).await?;
207210

208-
let keys = JsonWebKeySet::new(keys);
209-
Ok(Keystore::new(keys))
211+
Ok(Keystore::new(JsonWebKeySet::new(web_keys)))
210212
}
211213

212214
/// Derive an [`Encrypter`] out of the config

0 commit comments

Comments
 (0)