Debian Codegraph @

crt/s2n/bindings/rust/aws-kms-tls-auth/src/provider.rs

raw symbols SCIP
1 // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2 // SPDX-License-Identifier: Apache-2.0
3
4 use crate::{epoch_schedule, psk_derivation::EpochSecret, KeyArn, ONE_HOUR};
5 use aws_sdk_kms::Client;
6 use s2n_tls::{callbacks::ConnectionFuture, config::ConnectionInitializer};
7 use std::{
8 cmp::min,
9 collections::VecDeque,
10 fmt::Debug,
11 pin::Pin,
12 sync::{Arc, Mutex, RwLock},
13 time::Duration,
14 };
15
16 /// We aim to start using the key for epoch n after this duration has elapsed.
17 ///
18 /// Consider a scenario where epoch n is exactly 30 minutes (1800 seconds) away.
19 /// If we slept for exactly 1800 seconds and checked the system clock again, epoch
20 /// n might not have started because System Clocks may be corrected, unreliable, etc.
21 ///
22 /// This cushion reduces the chances of that happening.
23 const ROTATION_CUSHION: Duration = Duration::from_secs(60);
24
25 #[derive(Debug)]
26 struct ProviderSecrets {
27 key_arn: KeyArn,
28 /// secret currently used to generate PSKs. Generally this is the epoch secret
29 /// for the current epoch `n`.
30 ///
31 /// In the event of failure to fetch new epoch secrets, the client will continue
32 /// using the existing key. The client does _not_ enforce a certain key lifetime,
33 /// and will continue to make a best effort to connect.
34 ///
35 /// This means that clients are not responsible for enforcing the lifetime of
36 /// epoch secrets, and that is controlled server-side.
37 current_secret: RwLock<Arc<EpochSecret>>,
38 /// secrets for epoch `n + 1` and `n + 2`
39 next_secrets: Mutex<VecDeque<EpochSecret>>,
40 smoothing_factor: Duration,
41 }
42
43 impl ProviderSecrets {
44 fn current_secret(&self) -> Arc<EpochSecret> {
45 self.current_secret.read().unwrap().clone()
46 }
47
48 fn available_epochs(&self) -> Vec<u64> {
49 let mut epochs = Vec::new();
50 epochs.push(self.current_secret().key_epoch);
51 self.next_secrets
52 .lock()
53 .unwrap()
54 .iter()
55 .map(|s| s.key_epoch)
56 .for_each(|epoch| epochs.push(epoch));
57 epochs
58 }
59
60 fn newest_available_epoch(&self) -> Option<u64> {
61 self.next_secrets
62 .lock()
63 .unwrap()
64 .iter()
65 .map(|epoch_secret| epoch_secret.key_epoch)
66 .max()
67 }
68
69 /// Fetch the next set of secrets.
70 ///
71 /// This will almost always be fetching the secrets for `current_epoch + 2`
72 /// unless previous fetches failed. See [epoch_schedule] for more information.
73 ///
74 /// This function returns the duration until it should be called again. Generally
75 /// ~24 hours if the fetch succeeded, or ~1 hour if the fetch failed.
76 async fn fetch_secrets(
77 &self,
78 current_epoch: u64,
79 kms_client: &Client,
80 failure_notification: &(dyn Fn(anyhow::Error) + Send + Sync + 'static),
81 ) -> Result<Duration, Duration> {
82 let mut to_fetch = vec![current_epoch, current_epoch + 1, current_epoch + 2];
83 let available = self.available_epochs();
84 to_fetch.retain(|epoch| !available.contains(epoch));
85
86 for epoch in to_fetch {
87 match EpochSecret::fetch_epoch_secret(kms_client, &self.key_arn, epoch).await {
88 Ok(epoch_secret) => {
89 tracing::debug!("fetched secret for epoch {epoch} from {}", self.key_arn);
90 self.next_secrets.lock().unwrap().push_back(epoch_secret);
91 }
92 Err(e) => {
93 tracing::error!(
94 "failed to fetch secret for epoch {epoch} from {}",
95 self.key_arn
96 );
97 failure_notification(e);
98 return Err(ONE_HOUR);
99 }
100 }
101 }
102
103 let sleep = self.newest_available_epoch().and_then(|next_fetch| {
104 epoch_schedule::until_fetch(next_fetch + 1, self.smoothing_factor)
105 });
106 match sleep {
107 Some(duration) => Ok(duration),
108 None => Err(ONE_HOUR),
109 }
110 }
111
112 /// Attempt to update the current epoch secret. This should be called at the
113 /// start of each epoch.
114 ///
115 /// Returns the duration until the next orderly rotation should be attempted.
116 fn rotate_secrets(&self, current_epoch: u64) -> Duration {
117 let needs_rotation = self.current_secret().key_epoch < current_epoch;
118 let rotation_key = self
119 .next_secrets
120 .lock()
121 .unwrap()
122 .iter()
123 .find(|secret| secret.key_epoch == current_epoch)
124 .cloned();
125
126 if needs_rotation {
127 match rotation_key {
128 Some(key) => {
129 tracing::debug!(
130 "current key is now epoch {current_epoch} from {}",
131 self.key_arn
132 );
133 *self.current_secret.write().unwrap() = Arc::new(key);
134 }
135 None => {
136 tracing::warn!("rotation needed, but the key was not available")
137 }
138 }
139 }
140
141 match epoch_schedule::until_epoch_start(current_epoch + 1) {
142 Some(duration) => duration + ROTATION_CUSHION,
143 None => {
144 // the next epoch has already started. This might be the case if
145 // the fetch happened late in the epoch and had high latency.
146 Duration::from_secs(0)
147 }
148 }
149 }
150
151 /// Remove old, unused secrets.
152 ///
153 /// This will not modify [`ProviderSecrets::current_secret`].
154 fn drop_old_secrets(&self, current_epoch: u64) {
155 self.next_secrets
156 .lock()
157 .unwrap()
158 .retain(|secret| secret.key_epoch > current_epoch);
159 }
160
161 // wrapping all of the update logic in this method helps with testability without
162 // having to add a generic "clock" parameter.
163 async fn poll_update(
164 &self,
165 current_epoch: u64,
166 kms_client: &Client,
167 failure_notification: &(dyn Fn(anyhow::Error) + Send + Sync + 'static),
168 ) -> Result<Duration, Duration> {
169 let until_next_fetch = self
170 .fetch_secrets(current_epoch, kms_client, failure_notification)
171 .await;
172 let until_next_rotation = self.rotate_secrets(current_epoch);
173 self.drop_old_secrets(current_epoch);
174
175 match until_next_fetch {
176 Ok(until_fetch) => Ok(min(until_fetch, until_next_rotation)),
177 Err(until_fetch) => Err(min(until_fetch, until_next_rotation)),
178 }
179 }
180 }
181 #[derive(Debug, Clone)]
182 pub struct PskProvider {
183 secret_state: Arc<ProviderSecrets>,
184 }
185
186 impl PskProvider {
187 pub async fn initialize(
188 kms_client: Client,
189 key_arn: KeyArn,
190 failure_notification: impl Fn(anyhow::Error) + Send + Sync + 'static,
191 ) -> anyhow::Result<Self> {
192 let current_epoch = epoch_schedule::current_epoch();
193 let current_secret =
194 EpochSecret::fetch_epoch_secret(&kms_client, &key_arn, current_epoch).await?;
195 let secret_state = Arc::new(ProviderSecrets {
196 key_arn,
197 current_secret: RwLock::new(Arc::new(current_secret)),
198 next_secrets: Mutex::new(VecDeque::new()),
199 smoothing_factor: epoch_schedule::smoothing_factor(),
200 });
201
202 let update = secret_state
203 .poll_update(current_epoch, &kms_client, &failure_notification)
204 .await;
205 if update.is_err() {
206 anyhow::bail!("failed to fetch keys during startup");
207 }
208
209 tokio::task::spawn({
210 let secret_state = Arc::clone(&secret_state);
211 async move {
212 loop {
213 let current_epoch = epoch_schedule::current_epoch();
214
215 let sleep_duration = secret_state
216 .poll_update(current_epoch, &kms_client, &failure_notification)
217 .await;
218 let sleep_duration = match sleep_duration {
219 Ok(duration) => duration,
220 Err(duration) => duration,
221 };
222 tracing::debug!("sleeping for {sleep_duration:?}");
223 tokio::time::sleep(sleep_duration).await;
224 }
225 }
226 });
227 Ok(Self { secret_state })
228 }
229 }
230
231 impl ConnectionInitializer for PskProvider {
232 fn initialize_connection(
233 &self,
234 connection: &mut s2n_tls::connection::Connection,
235 ) -> Result<Option<Pin<Box<dyn ConnectionFuture>>>, s2n_tls::error::Error> {
236 let psk = self.secret_state.current_secret().new_connection_psk()?;
237 connection.append_psk(&psk)?;
238 Ok(None)
239 }
240 }
241
242 #[cfg(test)]
243 mod tests {
244 use super::*;
245 use crate::test_utils::{
246 configs_from_callbacks, handshake, mocked_kms_client, PskIdentityObserver, KMS_KEY_ARN_A,
247 };
248 use aws_sdk_kms::{
249 operation::generate_mac::{GenerateMacError, GenerateMacOutput},
250 primitives::Blob,
251 Client,
252 };
253 use aws_smithy_mocks::{mock, mock_client, RuleMode};
254 use std::{
255 sync::{
256 atomic::{AtomicUsize, Ordering},
257 Arc,
258 },
259 time::Duration,
260 };
261
262 /// The session names for each connection should be unique
263 #[tokio::test]
264 async fn session_names_are_random() {
265 let psk_provider =
266 PskProvider::initialize(mocked_kms_client(), KMS_KEY_ARN_A.to_owned(), |_| {})
267 .await
268 .unwrap();
269 let psk_capturer = PskIdentityObserver::default();
270 let observer_handle = psk_capturer.clone();
271 let (client_config, server_config) = configs_from_callbacks(psk_provider, psk_capturer);
272
273 handshake(&client_config, &server_config).await.unwrap_err();
274 handshake(&client_config, &server_config).await.unwrap_err();
275
276 let observed_psks = observer_handle.0.lock().unwrap().clone();
277 assert!(observed_psks[1].key_epoch - observed_psks[0].key_epoch <= 1);
278 assert!(observed_psks[1].session_name != observed_psks[0].session_name);
279 }
280
281 #[tokio::test]
282 async fn poll_update() -> Result<(), Duration> {
283 let psk_provider =
284 PskProvider::initialize(mocked_kms_client(), KMS_KEY_ARN_A.to_owned(), |_| {})
285 .await
286 .unwrap();
287 let mut this_epoch = epoch_schedule::current_epoch();
288 let client = mocked_kms_client();
289 let secret_state = psk_provider.secret_state;
290
291 // call poll update to get our initial state for "this_epoch"
292 secret_state
293 .poll_update(this_epoch, &client, &|_| {})
294 .await?;
295 let available = secret_state.available_epochs();
296 assert_eq!(available.len(), 3);
297 assert!(available.contains(&this_epoch));
298 assert!(available.contains(&(this_epoch + 1)));
299 assert!(available.contains(&(this_epoch + 2)));
300 let current_epoch_secret = secret_state.current_secret();
301
302 // a second call should be idempotent, no time has passed
303 secret_state
304 .poll_update(this_epoch, &client, &|_| {})
305 .await?;
306 assert_eq!(secret_state.available_epochs(), available);
307 assert_eq!(secret_state.current_secret(), current_epoch_secret);
308 let oldest = *available.iter().min().unwrap();
309
310 // when time advances, we
311 // 1. fetch a new secret
312 // 2. rotate the current one
313 // 3. drop the old one
314 this_epoch += 1;
315 secret_state
316 .poll_update(this_epoch, &client, &|_| {})
317 .await?;
318 assert_eq!(secret_state.available_epochs().len(), available.len());
319 assert!(secret_state
320 .available_epochs()
321 .into_iter()
322 .all(|epoch| epoch != oldest));
323 assert!(secret_state.available_epochs().contains(&(this_epoch + 2)));
324 assert_eq!(secret_state.current_secret().key_epoch, this_epoch);
325
326 // time skips are gracefully handled
327 this_epoch += 2;
328 secret_state
329 .poll_update(this_epoch, &client, &|_| {})
330 .await?;
331 assert_eq!(secret_state.available_epochs().len(), 3);
332 assert!(secret_state.available_epochs().contains(&this_epoch));
333 assert!(secret_state.available_epochs().contains(&(this_epoch + 1)));
334 assert!(secret_state.available_epochs().contains(&(this_epoch + 2)));
335 assert_eq!(secret_state.current_secret().key_epoch, this_epoch);
336
337 Ok(())
338 }
339
340 #[tokio::test]
341 async fn provider_initialization_when_kms_fetch_fails() {
342 let fail_rule = mock!(Client::generate_mac).then_error(|| {
343 aws_sdk_kms::operation::generate_mac::GenerateMacError::unhandled("MockedFailure")
344 });
345
346 let kms_client = mock_client!(aws_sdk_kms, RuleMode::MatchAny, [&fail_rule]);
347
348 let error = PskProvider::initialize(kms_client, KMS_KEY_ARN_A.to_owned(), |_| {})
349 .await
350 .unwrap_err();
351
352 assert_eq!(error.to_string(), "service error");
353 }
354
355 #[tokio::test]
356 async fn poll_update_with_failure() {
357 let error_count = Arc::new(AtomicUsize::new(0));
358 let notification_fn = {
359 let error_count = Arc::clone(&error_count);
360 move |_: anyhow::Error| {
361 error_count.fetch_add(1, Ordering::SeqCst);
362 }
363 };
364
365 let rule = mock!(Client::generate_mac)
366 .sequence()
367 .output(|| {
368 GenerateMacOutput::builder()
369 .mac(Blob::new(b"mock_mac_output".to_vec()))
370 .build()
371 })
372 .times(4)
373 .error(|| GenerateMacError::unhandled("MockedFailure"))
374 .times(4)
375 .build();
376 let kms_client = mock_client!(aws_sdk_kms, [&rule]);
377
378 // we successfully initialize, resulting in 3 KMS calls
379 let psk_provider = PskProvider::initialize(
380 kms_client.clone(),
381 KMS_KEY_ARN_A.to_owned(),
382 notification_fn.clone(),
383 )
384 .await
385 .unwrap();
386 assert_eq!(rule.num_calls(), 3);
387 let mut current_epoch = epoch_schedule::current_epoch();
388
389 // we successfully fetch the secret, the error count should be 0
390 current_epoch += 1;
391 psk_provider
392 .secret_state
393 .poll_update(current_epoch, &kms_client, &notification_fn)
394 .await
395 .unwrap();
396 assert_eq!(error_count.load(Ordering::SeqCst), 0);
397 assert_eq!(
398 psk_provider.secret_state.available_epochs(),
399 vec![current_epoch, current_epoch + 1, current_epoch + 2]
400 );
401 assert_eq!(
402 psk_provider
403 .secret_state
404 .current_secret
405 .read()
406 .unwrap()
407 .key_epoch,
408 current_epoch
409 );
410
411 // we fail to fetch the secret, the error count should be 1
412 current_epoch += 1;
413 psk_provider
414 .secret_state
415 .poll_update(current_epoch, &kms_client, &notification_fn)
416 .await
417 .unwrap_err();
418 assert_eq!(error_count.load(Ordering::SeqCst), 1);
419 assert_eq!(rule.num_calls(), 5);
420 // we failed to fetch the latest secret
421 assert_eq!(
422 psk_provider.secret_state.available_epochs(),
423 vec![current_epoch, current_epoch + 1]
424 );
425 assert_eq!(
426 psk_provider
427 .secret_state
428 .current_secret
429 .read()
430 .unwrap()
431 .key_epoch,
432 current_epoch
433 );
434
435 // The cases below assert that when we fail to fetch new secrets, a best
436 // effort is made using the last secret we fetched.
437 current_epoch += 1;
438 psk_provider
439 .secret_state
440 .poll_update(current_epoch, &kms_client, &notification_fn)
441 .await
442 .unwrap_err();
443 assert_eq!(
444 psk_provider.secret_state.available_epochs(),
445 vec![current_epoch]
446 );
447 assert_eq!(
448 psk_provider
449 .secret_state
450 .current_secret
451 .read()
452 .unwrap()
453 .key_epoch,
454 current_epoch
455 );
456
457 current_epoch += 1;
458 psk_provider
459 .secret_state
460 .poll_update(current_epoch, &kms_client, &notification_fn)
461 .await
462 .unwrap_err();
463 assert_eq!(
464 psk_provider.secret_state.available_epochs(),
465 vec![current_epoch - 1]
466 );
467 assert_eq!(
468 psk_provider
469 .secret_state
470 .current_secret
471 .read()
472 .unwrap()
473 .key_epoch,
474 current_epoch - 1
475 );
476
477 current_epoch += 1;
478 psk_provider
479 .secret_state
480 .poll_update(current_epoch, &kms_client, &notification_fn)
481 .await
482 .unwrap_err();
483 assert_eq!(
484 psk_provider.secret_state.available_epochs(),
485 vec![current_epoch - 2]
486 );
487 assert_eq!(
488 psk_provider
489 .secret_state
490 .current_secret
491 .read()
492 .unwrap()
493 .key_epoch,
494 current_epoch - 2
495 );
496 }
497 }