| 1 |
|
| 2 |
|
| 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 |
|
| 17 |
|
| 18 |
|
| 19 |
|
| 20 |
|
| 21 |
|
| 22 |
|
| 23 |
const ROTATION_CUSHION: Duration = Duration::from_secs(60); |
| 24 |
|
| 25 |
#[derive(Debug)] |
| 26 |
struct ProviderSecrets { |
| 27 |
key_arn: KeyArn, |
| 28 |
|
| 29 |
|
| 30 |
|
| 31 |
|
| 32 |
|
| 33 |
|
| 34 |
|
| 35 |
|
| 36 |
|
| 37 |
current_secret: RwLock<Arc<EpochSecret>>, |
| 38 |
|
| 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 |
|
| 70 |
|
| 71 |
|
| 72 |
|
| 73 |
|
| 74 |
|
| 75 |
|
| 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 |
|
| 113 |
|
| 114 |
|
| 115 |
|
| 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 |
|
| 145 |
|
| 146 |
Duration::from_secs(0) |
| 147 |
} |
| 148 |
} |
| 149 |
} |
| 150 |
|
| 151 |
|
| 152 |
|
| 153 |
|
| 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 |
|
| 162 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 311 |
|
| 312 |
|
| 313 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 390 |
current_epoch += 1; |
| 391 |
psk_provider |
| 392 |
.secret_state |
| 393 |
.poll_update(current_epoch, &kms_client, ¬ification_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 |
|
| 412 |
current_epoch += 1; |
| 413 |
psk_provider |
| 414 |
.secret_state |
| 415 |
.poll_update(current_epoch, &kms_client, ¬ification_fn) |
| 416 |
.await |
| 417 |
.unwrap_err(); |
| 418 |
assert_eq!(error_count.load(Ordering::SeqCst), 1); |
| 419 |
assert_eq!(rule.num_calls(), 5); |
| 420 |
|
| 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 |
|
| 436 |
|
| 437 |
current_epoch += 1; |
| 438 |
psk_provider |
| 439 |
.secret_state |
| 440 |
.poll_update(current_epoch, &kms_client, ¬ification_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, ¬ification_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, ¬ification_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 |
} |