-
-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathca.rs
More file actions
851 lines (775 loc) · 31.3 KB
/
ca.rs
File metadata and controls
851 lines (775 loc) · 31.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
//! Dynamically provisions and picks Certificate Authorities.
use std::{collections::BTreeMap, ffi::OsStr, fmt::Display, path::Path};
use kube_runtime::reflector::Lookup;
use openssl::{
asn1::{Asn1Integer, Asn1Time},
bn::{BigNum, MsbOption},
conf::{Conf, ConfMethod},
hash::MessageDigest,
nid::Nid,
pkey::{PKey, Private},
rsa::Rsa,
x509::{
X509, X509Builder, X509NameBuilder,
extension::{AuthorityKeyIdentifier, BasicConstraints, KeyUsage, SubjectKeyIdentifier},
},
};
use snafu::{OptionExt, ResultExt, Snafu};
use stackable_operator::{
k8s_openapi::{
ByteString,
api::core::v1::{ConfigMap, Secret},
},
kube::{
self,
api::{
DynamicObject, PostParams,
entry::{self, Entry},
},
runtime::reflector::ObjectRef,
},
shared::time::Duration,
};
use stackable_secret_operator_utils::crd::{ConfigMapReference, SecretReference};
use time::OffsetDateTime;
use tracing::{info, info_span, warn};
use crate::{
backend::SecretBackendError,
crd::v1alpha2,
utils::{Asn1TimeParseError, Unloggable, asn1time_to_offsetdatetime},
};
/// v1 format: support a single cert/pkey pair
mod secret_v1_keys {
pub const CERTIFICATE: &str = "ca.crt";
pub const PRIVATE_KEY: &str = "ca.key";
}
/// v2 format: support multiple cert/pkey pairs, prefixed by `{i}.`
mod secret_v2_key_suffixes {
pub const CERTIFICATE: &str = ".ca.crt";
pub const PRIVATE_KEY: &str = ".ca.key";
}
#[derive(Debug, Snafu)]
pub enum Error {
#[snafu(display("failed to generate certificate key"))]
GenerateKey { source: openssl::error::ErrorStack },
#[snafu(display("failed to load CA from {secret}"))]
FindCertificateAuthority {
source: kube::Error,
secret: ObjectRef<Secret>,
},
#[snafu(display("failed to load extra trust root from {object}"))]
FindExtraTrustRoot {
source: stackable_operator::client::Error,
object: ObjectRef<DynamicObject>,
},
#[snafu(display("CA {secret} does not exist, and autoGenerate is false"))]
CaNotFoundAndGenDisabled { secret: ObjectRef<Secret> },
#[snafu(display("CA {secret} is missing required key {key:?}"))]
MissingCertificate {
key: String,
secret: ObjectRef<Secret>,
},
#[snafu(display("failed to load certificate from key {key:?} of {object}"))]
LoadCertificate {
source: openssl::error::ErrorStack,
key: String,
object: ObjectRef<DynamicObject>,
},
#[snafu(display(
"unsupported certificate format in key {key:?} of {object}; supported extensions: .crt, .der"
))]
UnsupportedCertificateFormat {
key: String,
object: ObjectRef<DynamicObject>,
},
#[snafu(display("failed to parse CA lifetime from key {key:?} of {secret}"))]
ParseLifetime {
source: Asn1TimeParseError,
key: String,
secret: ObjectRef<Secret>,
},
#[snafu(display("failed to build certificate"))]
BuildCertificate { source: openssl::error::ErrorStack },
#[snafu(display("failed to serialize certificate"))]
SerializeCertificate { source: openssl::error::ErrorStack },
#[snafu(display("failed to save CA certificate to {secret}"))]
SaveCaCertificate {
source: entry::CommitError,
secret: ObjectRef<Secret>,
},
#[snafu(display("CA save was requested but automatic management is disabled"))]
SaveRequestedButForbidden,
}
type Result<T, E = Error> = std::result::Result<T, E>;
impl SecretBackendError for Error {
fn grpc_code(&self) -> tonic::Code {
match self {
Error::GenerateKey { .. } => tonic::Code::Internal,
Error::MissingCertificate { .. } => tonic::Code::FailedPrecondition,
Error::FindCertificateAuthority { .. } => tonic::Code::Unavailable,
Error::FindExtraTrustRoot { .. } => tonic::Code::Unavailable,
Error::CaNotFoundAndGenDisabled { .. } => tonic::Code::FailedPrecondition,
Error::LoadCertificate { .. } => tonic::Code::FailedPrecondition,
Error::UnsupportedCertificateFormat { .. } => tonic::Code::InvalidArgument,
Error::ParseLifetime { .. } => tonic::Code::FailedPrecondition,
Error::BuildCertificate { .. } => tonic::Code::FailedPrecondition,
Error::SerializeCertificate { .. } => tonic::Code::FailedPrecondition,
Error::SaveCaCertificate { .. } => tonic::Code::Unavailable,
Error::SaveRequestedButForbidden => tonic::Code::FailedPrecondition,
}
}
fn secondary_object(&self) -> Option<ObjectRef<kube::api::DynamicObject>> {
match self {
Error::GenerateKey { .. } => None,
Error::FindCertificateAuthority { secret, .. } => Some(secret.clone().erase()),
Error::FindExtraTrustRoot { object, .. } => Some(object.clone()),
Error::CaNotFoundAndGenDisabled { secret } => Some(secret.clone().erase()),
Error::MissingCertificate { secret, .. } => Some(secret.clone().erase()),
Error::LoadCertificate { object, .. } => Some(object.clone()),
Error::UnsupportedCertificateFormat { object, .. } => Some(object.clone()),
Error::ParseLifetime { secret, .. } => Some(secret.clone().erase()),
Error::BuildCertificate { .. } => None,
Error::SerializeCertificate { .. } => None,
Error::SaveCaCertificate { secret, .. } => Some(secret.clone().erase()),
Error::SaveRequestedButForbidden => None,
}
}
}
#[derive(Debug, Snafu)]
#[snafu(module)]
pub enum GetCaError {
#[snafu(display("no CA in {secret} will live until at least {cutoff}"))]
NoCaLivesLongEnough {
cutoff: OffsetDateTime,
secret: ObjectRef<Secret>,
},
}
impl SecretBackendError for GetCaError {
fn grpc_code(&self) -> tonic::Code {
match self {
GetCaError::NoCaLivesLongEnough { .. } => tonic::Code::FailedPrecondition,
}
}
fn secondary_object(&self) -> Option<ObjectRef<kube::api::DynamicObject>> {
match self {
GetCaError::NoCaLivesLongEnough { secret, .. } => Some(secret.clone().erase()),
}
}
}
#[derive(Debug)]
pub struct Config {
/// Whether [`Manager`] is allowed to automatically provision and manage this CA.
///
/// If `false`, logs will be emitted where Secret Operator would have taken action.
pub manage_ca: bool,
/// The duration of any new CA certificates provisioned.
pub ca_certificate_lifetime: Duration,
/// The retirement duration at the end of the CA certificate lifetime, where the CA is not used
/// to sign certificates and where the CA certificate does not have to be published.
pub ca_certificate_retirement_duration: Duration,
/// If no existing CA certificate outlives `rotate_if_ca_expires_before`, a new
/// certificate will be generated.
///
/// To ensure compatibility with pods that have already been started, the old CA
/// will still be used as long as the provisioned certificate's lifetime fits
/// inside the old CA's. This allows the new CA to be gradually introduced to all
/// pods' truststores.
///
/// Hence, this value _should_ be larger than the PKI's maximum certificate lifetime,
/// and smaller than [`Self::ca_certificate_lifetime`].
pub rotate_if_ca_expires_before: Option<Duration>,
/// Configuration how TLS private keys should be created.
pub key_generation: v1alpha2::CertificateKeyGeneration,
}
/// A single certificate authority certificate.
#[derive(Debug)]
pub struct CertificateAuthority {
pub certificate: X509,
pub private_key: Unloggable<PKey<Private>>,
not_after: OffsetDateTime,
}
impl Display for CertificateAuthority {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("CertificateAuthority(serial=")?;
match self.certificate.serial_number().to_bn() {
Ok(sn) => write!(f, "{}", sn)?,
Err(_) => f.write_str("<invalid>")?,
}
f.write_str(")")
}
}
impl CertificateAuthority {
/// Generate a new self-signed CA with a random key.
fn new_self_signed(config: &Config) -> Result<Self> {
let subject_name = X509NameBuilder::new()
.and_then(|mut name| {
name.append_entry_by_nid(Nid::COMMONNAME, "secret-operator self-signed")?;
Ok(name)
})
.context(BuildCertificateSnafu)?
.build();
let now = OffsetDateTime::now_utc();
let not_before = now - Duration::from_minutes_unchecked(5);
let not_after = now + config.ca_certificate_lifetime;
let conf =
Conf::new(ConfMethod::default()).expect("failed to initialize OpenSSL configuration");
let private_key_length = match config.key_generation {
v1alpha2::CertificateKeyGeneration::Rsa { length } => length,
};
let private_key = Rsa::generate(private_key_length)
.and_then(PKey::try_from)
.context(GenerateKeySnafu)?;
let certificate = X509Builder::new()
.and_then(|mut x509| {
x509.set_subject_name(&subject_name)?;
x509.set_issuer_name(&subject_name)?;
x509.set_not_before(Asn1Time::from_unix(not_before.unix_timestamp())?.as_ref())?;
x509.set_not_after(Asn1Time::from_unix(not_after.unix_timestamp())?.as_ref())?;
x509.set_pubkey(&private_key)?;
let mut serial = BigNum::new()?;
serial.rand(64, MsbOption::MAYBE_ZERO, false)?;
x509.set_serial_number(Asn1Integer::from_bn(&serial)?.as_ref())?;
x509.set_version(
3 - 1, // zero-indexed
)?;
let ctx = x509.x509v3_context(None, Some(&conf));
let exts = [
BasicConstraints::new().critical().ca().build()?,
SubjectKeyIdentifier::new().build(&ctx)?,
AuthorityKeyIdentifier::new()
.issuer(false)
.keyid(false)
.build(&ctx)?,
KeyUsage::new()
.critical()
.digital_signature()
.key_cert_sign()
.crl_sign()
.build()?,
];
for ext in exts {
x509.append_extension(ext)?;
}
x509.sign(&private_key, MessageDigest::sha256())?;
Ok(x509)
})
.context(BuildCertificateSnafu)?
.build();
Ok(Self {
private_key: Unloggable(private_key),
certificate,
not_after,
})
}
/// Loads an existing CA from the data of a [`Secret`].
fn from_secret_data(
secret_data: &BTreeMap<String, ByteString>,
secret_ref: &SecretReference,
key_certificate: &str,
key_private_key: &str,
) -> Result<Self> {
let certificate = X509::from_pem(
&secret_data
.get(key_certificate)
.context(MissingCertificateSnafu {
key: key_certificate,
secret: secret_ref,
})?
.0,
)
.with_context(|_| LoadCertificateSnafu {
key: key_certificate,
object: secret_ref,
})?;
let private_key = PKey::private_key_from_pem(
&secret_data
.get(key_private_key)
.context(MissingCertificateSnafu {
key: key_private_key,
secret: secret_ref,
})?
.0,
)
.with_context(|_| LoadCertificateSnafu {
key: key_private_key,
object: secret_ref,
})?;
Ok(CertificateAuthority {
not_after: asn1time_to_offsetdatetime(certificate.not_after()).with_context(|_| {
ParseLifetimeSnafu {
key: key_certificate,
secret: secret_ref,
}
})?,
certificate,
private_key: Unloggable(private_key),
})
}
}
/// Manages multiple [`CertificateAuthorities`](`CertificateAuthority`), rotating them as needed.
#[derive(Debug)]
pub struct Manager {
source_secret: ObjectRef<Secret>,
certificate_authorities: Vec<CertificateAuthority>,
additional_trusted_certificates: Vec<X509>,
ca_certificate_retirement_duration: Duration,
}
impl Manager {
pub async fn load_or_create(
client: &stackable_operator::client::Client,
secret_ref: &SecretReference,
additional_trust_roots: &[v1alpha2::AdditionalTrustRoot],
config: &Config,
) -> Result<Self> {
// Use entry API rather than apply so that we crash and retry on conflicts (to avoid creating spurious certs that we throw away immediately)
let secrets_api = &client.get_api::<Secret>(&secret_ref.namespace);
let mut ca_secret = secrets_api
.entry(&secret_ref.name)
.await
.with_context(|_| FindCertificateAuthoritySnafu { secret: secret_ref })?;
let mut update_ca_secret = false;
let mut certificate_authorities = match &ca_secret {
Entry::Occupied(ca_secret) => {
// Existing CA has been found, load and use this
let empty = BTreeMap::new();
let ca_data = ca_secret.get().data.as_ref().unwrap_or(&empty);
if ca_data.contains_key(secret_v1_keys::CERTIFICATE) {
if config.manage_ca {
update_ca_secret = true;
info!(
secret = %secret_ref,
"Migrating CA secret from legacy naming scheme"
);
} else {
warn!(
secret = %secret_ref,
"CA secret uses legacy certificate naming ({v1}), please rename to 0{v2}",
v1 = secret_v1_keys::CERTIFICATE,
v2 = secret_v2_key_suffixes::CERTIFICATE,
);
}
vec![CertificateAuthority::from_secret_data(
ca_data,
secret_ref,
secret_v1_keys::CERTIFICATE,
secret_v1_keys::PRIVATE_KEY,
)?]
} else {
ca_data
.keys()
.filter_map(|cert_key| {
Some(CertificateAuthority::from_secret_data(
ca_data,
secret_ref,
cert_key,
&cert_key
.ends_with(secret_v2_key_suffixes::CERTIFICATE)
.then(|| {
cert_key.replace(
secret_v2_key_suffixes::CERTIFICATE,
secret_v2_key_suffixes::PRIVATE_KEY,
)
})?,
))
})
.collect::<Result<_>>()?
}
}
Entry::Vacant(_) if config.manage_ca => {
update_ca_secret = true;
let ca = CertificateAuthority::new_self_signed(config)?;
info!(
secret = %secret_ref,
%ca,
%ca.not_after,
"Provisioning a new CA certificate, because it could not be found"
);
vec![ca]
}
Entry::Vacant(_) => {
return CaNotFoundAndGenDisabledSnafu { secret: secret_ref }.fail();
}
};
// Check whether CA should be rotated
let newest_ca = certificate_authorities.iter().max_by_key(|ca| ca.not_after);
if let (Some(cutoff_duration), Some(newest_ca)) =
(config.rotate_if_ca_expires_before, newest_ca)
{
let cutoff = OffsetDateTime::now_utc() + cutoff_duration;
let _span = info_span!(
"ca_rotation",
secret = %secret_ref,
%cutoff,
cutoff.duration = %cutoff_duration,
%newest_ca,
%newest_ca.not_after,
)
.entered();
if newest_ca.not_after < cutoff {
if config.manage_ca {
update_ca_secret = true;
info!(
"Provisioning a new CA certificate, because the old one will soon expire"
);
certificate_authorities.push(CertificateAuthority::new_self_signed(config)?);
} else {
warn!("CA certificate will soon expire, please provision a new one");
}
} else {
info!("CA is not close to expiring, will not initiate rotation");
}
}
if update_ca_secret {
if config.manage_ca {
info!(secret = %secret_ref, "CA has been modified, saving");
// Sort CAs by age to avoid spurious writes
certificate_authorities.sort_by_key(|ca| ca.not_after);
let mut occupied_ca_secret = ca_secret.or_insert(Secret::default);
occupied_ca_secret.get_mut().data = Some(
certificate_authorities
.iter()
.enumerate()
.flat_map(|(i, ca)| {
[
ca.certificate
.to_pem()
.context(SerializeCertificateSnafu)
.map(|cert| {
(
format!("{i}{}", secret_v2_key_suffixes::CERTIFICATE),
ByteString(cert),
)
}),
ca.private_key
.private_key_to_pem_pkcs8()
.context(SerializeCertificateSnafu)
.map(|key| {
(
format!("{i}{}", secret_v2_key_suffixes::PRIVATE_KEY),
ByteString(key),
)
}),
]
})
.collect::<Result<_>>()?,
);
occupied_ca_secret
.commit(&PostParams::default())
.await
.context(SaveCaCertificateSnafu { secret: secret_ref })?;
ca_secret = Entry::Occupied(occupied_ca_secret);
} else {
return SaveRequestedButForbiddenSnafu.fail();
}
}
let mut additional_trusted_certificates = vec![];
for entry in additional_trust_roots {
let certs = match entry {
v1alpha2::AdditionalTrustRoot::ConfigMap(config_map) => {
Self::read_extra_trust_roots_from_config_map(client, config_map).await?
}
v1alpha2::AdditionalTrustRoot::Secret(secret) => {
Self::read_extra_trust_roots_from_secret(client, secret).await?
}
};
additional_trusted_certificates.extend(certs);
}
Ok(Self {
certificate_authorities,
additional_trusted_certificates,
source_secret: ca_secret
.get()
.map(|secret| secret.to_object_ref(()))
.unwrap_or_else(|| secret_ref.into()),
ca_certificate_retirement_duration: config.ca_certificate_retirement_duration,
})
}
/// Read certificates from the given ConfigMap
///
/// The keys are assumed to be filenames and their extensions denote the expected format of the
/// certificate.
async fn read_extra_trust_roots_from_config_map(
client: &stackable_operator::client::Client,
config_map_ref: &ConfigMapReference,
) -> Result<Vec<X509>> {
let mut certificates = vec![];
let config_map = client
.get::<ConfigMap>(&config_map_ref.name, &config_map_ref.namespace)
.await
.context(FindExtraTrustRootSnafu {
object: config_map_ref,
})?;
let config_map_data = config_map.data.unwrap_or_default();
let config_map_binary_data = config_map.binary_data.unwrap_or_default();
let data = config_map_data
.iter()
.map(|(key, value)| (key, value.as_bytes()))
.chain(
config_map_binary_data
.iter()
.map(|(key, ByteString(value))| (key, value.as_ref())),
);
for (key, value) in data {
let certs = Self::deserialize_certificate(key, value, config_map_ref)?;
info!(
?certs,
%config_map_ref,
%key,
"adding certificates from additional trust root",
);
certificates.extend(certs);
}
Ok(certificates)
}
/// Read certificates from the given Secret
///
/// The keys are assumed to be filenames and their extensions denote the expected format of the
/// certificate.
async fn read_extra_trust_roots_from_secret(
client: &stackable_operator::client::Client,
secret_ref: &SecretReference,
) -> Result<Vec<X509>> {
let mut certificates = vec![];
let secret = client
.get::<Secret>(&secret_ref.name, &secret_ref.namespace)
.await
.context(FindExtraTrustRootSnafu { object: secret_ref })?;
let secret_data = secret.data.unwrap_or_default();
for (key, ByteString(value)) in &secret_data {
let certs = Self::deserialize_certificate(key, value, secret_ref)?;
info!(
?certs,
%secret_ref,
%key,
"adding certificates from additional trust root",
);
certificates.extend(certs);
}
Ok(certificates)
}
/// Deserialize a certificate from the given value. The format is determined by the extension
/// of the key.
fn deserialize_certificate(
key: &str,
value: &[u8],
object_ref: impl Into<ObjectRef<DynamicObject>>,
) -> Result<Vec<X509>> {
let extension = Path::new(key).extension().and_then(OsStr::to_str);
match extension {
Some("crt") => X509::stack_from_pem(value),
Some("der") => X509::from_der(value).map(|cert| vec![cert]),
_ => {
return UnsupportedCertificateFormatSnafu {
key,
object: object_ref,
}
.fail();
}
}
.context(LoadCertificateSnafu {
key,
object: object_ref,
})
}
/// Get an appropriate [`CertificateAuthority`] for signing a given certificate.
pub fn find_certificate_authority_for_signing(
&self,
active_until_at_least: OffsetDateTime,
) -> Result<&CertificateAuthority, GetCaError> {
use get_ca_error::*;
self.active_certificate_authorities(active_until_at_least)
.into_iter()
// pick the oldest valid CA, since it will be trusted by the most peers
.min_by_key(|ca| ca.not_after)
.with_context(|| NoCaLivesLongEnoughSnafu {
cutoff: active_until_at_least,
secret: self.source_secret.clone(),
})
}
/// Get all active trust root certificates.
pub fn trust_roots(
&self,
active_until_at_least: OffsetDateTime,
) -> impl IntoIterator<Item = &X509> + '_ {
self.active_certificate_authorities(active_until_at_least)
.into_iter()
.map(|ca| &ca.certificate)
.chain(self.active_additional_trusted_certificates(active_until_at_least))
}
/// Returns all certificate authorities which are not retired or expired
fn active_certificate_authorities(
&self,
active_until_at_least: OffsetDateTime,
) -> impl IntoIterator<Item = &CertificateAuthority> {
self.certificate_authorities.iter().filter(move |ca| {
ca.not_after - self.ca_certificate_retirement_duration >= active_until_at_least
})
}
/// Returns all additional trusted certificates which are not retired or expired
fn active_additional_trusted_certificates(
&self,
active_until_at_least: OffsetDateTime,
) -> impl IntoIterator<Item = &X509> + '_ {
self.additional_trusted_certificates
.iter()
.filter(move |cert| {
asn1time_to_offsetdatetime(cert.not_after()).is_ok_and(|not_after| {
not_after - self.ca_certificate_retirement_duration >= active_until_at_least
})
})
}
}
#[cfg(test)]
mod tests {
use kube_runtime::reflector::ObjectRef;
use openssl::{
asn1::{Asn1Integer, Asn1Time},
bn::BigNum,
hash::MessageDigest,
pkey::{PKey, Private},
rsa::Rsa,
x509::{X509, X509Builder},
};
use stackable_operator::{
k8s_openapi::{ByteString, api::core::v1::Secret},
shared::time::Duration,
};
use stackable_secret_operator_utils::crd::SecretReference;
use time::{OffsetDateTime, macros::datetime};
use super::{CertificateAuthority, Manager};
fn create_certificate(
serial_number: u32,
not_before: OffsetDateTime,
not_after: OffsetDateTime,
) -> Result<(X509, PKey<Private>), openssl::error::ErrorStack> {
let key_pair = Rsa::generate(512)?;
let pkey = PKey::try_from(key_pair)?;
let mut x509_builder = X509Builder::new()?;
x509_builder.set_serial_number(
Asn1Integer::from_bn(BigNum::from_u32(serial_number)?.as_ref())?.as_ref(),
)?;
x509_builder.set_not_before(Asn1Time::from_unix(not_before.unix_timestamp())?.as_ref())?;
x509_builder.set_not_after(Asn1Time::from_unix(not_after.unix_timestamp())?.as_ref())?;
x509_builder.set_pubkey(&pkey)?;
x509_builder.sign(&pkey, MessageDigest::sha256())?;
let x509 = x509_builder.build();
Ok((x509, pkey))
}
fn create_certificate_authority(
serial_number: u32,
not_before: OffsetDateTime,
not_after: OffsetDateTime,
) -> Result<CertificateAuthority, openssl::error::ErrorStack> {
let (certificate, pkey) = create_certificate(serial_number, not_before, not_after)?;
let key_certificate = "crt";
let key_private_key = "key";
Ok(CertificateAuthority::from_secret_data(
&[
(
key_certificate.to_owned(),
ByteString(certificate.to_pem()?),
),
(
key_private_key.to_owned(),
ByteString(pkey.private_key_to_pem_pkcs8()?),
),
]
.into(),
&SecretReference {
namespace: "default".to_owned(),
name: "secret-provisioner-tls-ca".to_owned(),
},
key_certificate,
key_private_key,
)
.expect("should load the valid certificates from the given Secret data"))
}
#[test]
fn test_find_certificate_authority_for_signing() {
let ca_certificate_retirement_duration = Duration::from_hours_unchecked(1);
let ca1 = create_certificate_authority(
1,
datetime!(2025-01-01 0:00 UTC),
datetime!(2025-01-01 12:00 UTC),
)
.expect("must be able to create a valid certificate");
let ca2 = create_certificate_authority(
2,
datetime!(2025-01-01 6:00 UTC),
datetime!(2025-01-01 18:00 UTC),
)
.expect("must be able to create a valid certificate");
let manager = Manager {
source_secret: ObjectRef::<Secret>::new("secret-provisioner-tls-ca"),
certificate_authorities: vec![ca1, ca2],
additional_trusted_certificates: vec![],
ca_certificate_retirement_duration,
};
let signing_ca_at_11_00 =
manager.find_certificate_authority_for_signing(datetime!(2025-01-01 11:00 UTC));
assert_eq!(
Some("CertificateAuthority(serial=1)".to_owned()),
signing_ca_at_11_00.ok().map(|ca| format!("{}", ca))
);
let signing_ca_at_11_01 =
manager.find_certificate_authority_for_signing(datetime!(2025-01-01 11:01 UTC));
assert_eq!(
Some("CertificateAuthority(serial=2)".to_owned()),
signing_ca_at_11_01.ok().map(|ca| format!("{}", ca))
);
}
#[test]
fn test_trust_roots() {
let ca_certificate_retirement_duration = Duration::from_hours_unchecked(1);
let ca1 = create_certificate_authority(
1,
datetime!(2025-01-01 0:00 UTC),
datetime!(2025-01-01 12:00 UTC),
)
.expect("must be able to create a valid certificate");
let ca1_certificate = ca1.certificate.clone();
let ca2 = create_certificate_authority(
2,
datetime!(2025-01-01 6:00 UTC),
datetime!(2025-01-01 18:00 UTC),
)
.expect("must be able to create a valid certificate");
let ca2_certificate = ca2.certificate.clone();
let (trust_root1, _) = create_certificate(
3,
datetime!(2025-01-01 0:00 UTC),
datetime!(2025-01-01 12:00 UTC),
)
.expect("must be able to create a valid certificate");
let (trust_root2, _) = create_certificate(
4,
datetime!(2025-01-01 6:00 UTC),
datetime!(2025-01-01 18:00 UTC),
)
.expect("must be able to create a valid certificate");
let manager = Manager {
source_secret: ObjectRef::<Secret>::new("secret-provisioner-tls-ca"),
certificate_authorities: vec![ca1, ca2],
additional_trusted_certificates: vec![trust_root1.clone(), trust_root2.clone()],
ca_certificate_retirement_duration,
};
let trust_roots_at_11_00: Vec<&X509> = manager
.trust_roots(datetime!(2025-01-01 11:00 UTC))
.into_iter()
.collect();
assert_eq!(
vec![
&ca1_certificate,
&ca2_certificate,
&trust_root1,
&trust_root2
],
trust_roots_at_11_00
);
let trust_roots_at_11_01: Vec<&X509> = manager
.trust_roots(datetime!(2025-01-01 11:01 UTC))
.into_iter()
.collect();
assert_eq!(vec![&ca2_certificate, &trust_root2], trust_roots_at_11_01);
}
}