Skip to content

feat!(stackable-certs): Use builder pattern and support SAN entries #1044

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 22 commits into from
Closed
Show file tree
Hide file tree
Changes from 7 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ repository = "https://github.com/stackabletech/operator-rs"
product-config = { git = "https://github.com/stackabletech/product-config.git", tag = "0.7.0" }

axum = { version = "0.8.1", features = ["http2"] }
bon = "3.6.3"
chrono = { version = "0.4.38", default-features = false }
clap = { version = "4.5.17", features = ["derive", "cargo", "env"] }
const_format = "0.2.33"
Expand Down
12 changes: 12 additions & 0 deletions crates/stackable-certs/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,25 @@ All notable changes to this project will be documented in this file.

## [Unreleased]

### Added

- Support adding SAN entries to generated certificates, this is needed for basically all modern TLS
certificate validations when used with HTTPS ([#1044]).

### Changed

- GIGA BREAKING: Rewrite entire CA and cert generation to use a builder pattern ([#1044]).
- BREAKING: The constant `DEFAULT_CA_VALIDITY_SECONDS` has been renamed to `DEFAULT_CA_VALIDITY` and now is of type `stackable_operator::time::Duration`.
Also, the constant `ROOT_CA_SUBJECT` has been renamed to `SDP_ROOT_CA_SUBJECT` ([#1044]).

## [0.3.1] - 2024-07-10

### Changed

- Bump rust-toolchain to 1.79.0 ([#822]).

[#822]: https://github.com/stackabletech/operator-rs/pull/822
[#1044]: https://github.com/stackabletech/operator-rs/pull/1044

## [0.3.0] - 2024-05-08

Expand Down
1 change: 1 addition & 0 deletions crates/stackable-certs/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ rustls = ["dep:tokio-rustls"]
[dependencies]
stackable-operator = { path = "../stackable-operator" }

bon.workspace = true
const-oid.workspace = true
ecdsa.workspace = true
k8s-openapi.workspace = true
Expand Down
240 changes: 240 additions & 0 deletions crates/stackable-certs/src/ca/ca_builder.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,240 @@
use bon::Builder;
use rsa::pkcs8::EncodePublicKey;
use snafu::{ResultExt, Snafu};
use stackable_operator::time::Duration;
use tracing::debug;
use x509_cert::{
builder::{Builder, CertificateBuilder, Profile},
der::{DecodePem, referenced::OwnedToRef},
ext::pkix::AuthorityKeyIdentifier,
name::Name,
serial_number::SerialNumber,
spki::SubjectPublicKeyInfoOwned,
time::Validity,
};

use super::CertificateAuthority;
use crate::{
CertificatePair,
ca::{DEFAULT_CA_VALIDITY, PEM_LINE_ENDING, SDP_ROOT_CA_SUBJECT},
keys::CertificateKeypair,
};

/// Defines all error variants which can occur when creating a CA
#[derive(Debug, Snafu)]
pub enum CreateCertificateAuthorityError<E>
where
E: std::error::Error + 'static,
{
#[snafu(display("failed to parse validity"))]
ParseValidity { source: x509_cert::der::Error },

#[snafu(display("failed to parse \"{subject}\" as subject"))]
ParseSubject {
source: x509_cert::der::Error,
subject: String,
},

#[snafu(display("failed to create signing key pair"))]
CreateSigningKeyPair { source: E },

#[snafu(display("failed to serialize public key as PEM"))]
SerializePublicKey { source: x509_cert::spki::Error },

#[snafu(display("failed to decode SPKI from PEM"))]
DecodeSpkiFromPem { source: x509_cert::der::Error },

#[snafu(display("failed to parse AuthorityKeyIdentifier"))]
ParseAuthorityKeyIdentifier { source: x509_cert::der::Error },

#[snafu(display("failed to create certificate builder"))]
CreateCertificateBuilder { source: x509_cert::builder::Error },

#[snafu(display("failed to add certificate extension"))]
AddCertificateExtension { source: x509_cert::builder::Error },

#[snafu(display("failed to build certificate"))]
BuildCertificate { source: x509_cert::builder::Error },
}

/// This builder builds certificate authorities of type [`CertificateAuthority`].
///
/// Example code to construct a CA:
///
/// ```no_run
/// use stackable_certs::{
/// keys::ecdsa,
/// ca::{CertificateAuthority, CertificateAuthorityBuilder},
/// };
///
/// let ca: CertificateAuthority<ecdsa::SigningKey> = CertificateAuthorityBuilder::builder()
/// .build()
/// .build_ca()
Copy link
Member

@NickLarsenNZ NickLarsenNZ May 23, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This feels a little awkward to me. I'm not (yet) sure what the two build methods do differently?

It looks like the build() method still returns a builder, and build_ca() self-signs and returns a CertificateAuthority.

Point is, I don't find it intuitive and I think it should be.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I worked it out below, and recommended renaming the struct.

/// .expect("failed to build CA");
/// ```
#[derive(Builder)]
pub struct CertificateAuthorityBuilder<'a, SKP>
Copy link
Member

@NickLarsenNZ NickLarsenNZ May 23, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this should be:

Suggested change
pub struct CertificateAuthorityBuilder<'a, SKP>
pub struct CertificateAuthority<'a, SKP>

So when we call build(), we get back a CA and not a CA Builder.

Note, the Builder macro would otherwise generate CertificateAuthorityBuilderBuilder (ie: it generates the Builder, not us).

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

To illustrate further:

  • CertificateAuthority::builder() -> CertificateAuthorityBuilder
  • CertificateAuthorityBuilder::build() -> a valid CertificateAuthority

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh, but we already have a struct: CertificateAuthority<SK> at

pub struct CertificateAuthority<SK>

in my mind, that one should be the one that derives Builder. Otherwise we need to revise what each struct is, because the current CertificateAuthorityBuilder is not a builder (per previous message above).

where
SKP: CertificateKeypair,
<SKP::SigningKey as signature::Keypair>::VerifyingKey: EncodePublicKey,
{
/// Required subject of the certificate authority, usually starts with `CN=`.
#[builder(default = SDP_ROOT_CA_SUBJECT)]
subject: &'a str,

/// Validity/lifetime of the certificate.
///
/// If not specified the default of [`DEFAULT_CA_VALIDITY`] will be used.
#[builder(default = DEFAULT_CA_VALIDITY)]
validity: Duration,

/// Serial number of the generated certificate.
///
/// If not specified a random serial will be generated.
serial_number: Option<u64>,
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

note: This is an internal detail we shouldn't allow being customized by the user of this library. I'm sure there is something like

Suggested change
/// Serial number of the generated certificate.
///
/// If not specified a random serial will be generated.
serial_number: Option<u64>,
/// Serial number of the generated certificate.
#[builder(skip)]
serial_number: Option<u64>,

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed. On that topic, if we want to have proper CAs... then serial should increment.
So, if we restore a CA (eg: on startup, read from a secret to get the CA keypair), we also need information for the certs that have been issued (not by reading available signed certs, since they might be gone already). We basically need an atomic counter.

I'm not 100% certain of the downside if we just always issue the same version though.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I copied the builder to mimic the current api, in which users can specify the serial:

pub fn new_with(signing_key_pair: S, serial_number: u64, validity: Duration) -> Result<Self> {

secret-op generates random serials for cas and certs (https://github.com/stackabletech/secret-operator/blob/00909cfb92e61539a4baab9190235cd33b33a61b/rust/operator-binary/src/backend/tls/ca.rs#L258 and https://github.com/stackabletech/secret-operator/blob/00909cfb92e61539a4baab9190235cd33b33a61b/rust/operator-binary/src/backend/tls/mod.rs#L306), this seems to be fine.
I will update the PR to not let users choose the serial

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.


/// Cryptographic keypair used to sign leaf certificates.
///
/// If not specified a random keypair will be generated.
signing_key_pair: Option<SKP>,
Comment on lines +114 to +117
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

note: I would like to see the same high-level functions to create a RSA or ECDSA based CA.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added in fd19a03

}

impl<SKP> CertificateAuthorityBuilder<'_, SKP>
where
SKP: CertificateKeypair,
<SKP::SigningKey as signature::Keypair>::VerifyingKey: EncodePublicKey,
{
pub fn build_ca(
self,
) -> Result<CertificateAuthority<SKP>, CreateCertificateAuthorityError<SKP::Error>> {
let serial_number =
SerialNumber::from(self.serial_number.unwrap_or_else(|| rand::random::<u64>()));
let validity = Validity::from_now(*self.validity).context(ParseValiditySnafu)?;
let subject: Name = self.subject.parse().context(ParseSubjectSnafu {
subject: self.subject,
})?;
let signing_key_pair = match self.signing_key_pair {
Some(signing_key_pair) => signing_key_pair,
None => SKP::new().context(CreateSigningKeyPairSnafu)?,
};

let spki_pem = signing_key_pair
.verifying_key()
.to_public_key_pem(PEM_LINE_ENDING)
.context(SerializePublicKeySnafu)?;

let spki = SubjectPublicKeyInfoOwned::from_pem(spki_pem.as_bytes())
.context(DecodeSpkiFromPemSnafu)?;

// There are multiple default extensions included in the profile. For
// the root profile, these are:
//
// - BasicConstraints marked as critical and CA = true
// - SubjectKeyIdentifier with the 160-bit SHA-1 hash of the subject
// public key.
// - KeyUsage with KeyCertSign and CRLSign bits set. Ideally we also
// want to include the DigitalSignature bit, which for example is
// required for CA certs which want to sign an OCSP response.
// Currently, the root profile doesn't include that bit.
//
// The root profile doesn't add the AuthorityKeyIdentifier extension.
// We manually add it below by using the 160-bit SHA-1 hash of the
// subject public key. This conforms to one of the outlined methods for
// generating key identifiers outlined in RFC 5280, section 4.2.1.2.
//
// Prepare extensions so we can avoid clones.
let aki = AuthorityKeyIdentifier::try_from(spki.owned_to_ref())
.context(ParseAuthorityKeyIdentifierSnafu)?;

let signer = signing_key_pair.signing_key();
let mut builder = CertificateBuilder::new(
Profile::Root,
serial_number,
validity,
subject,
spki,
signer,
)
.context(CreateCertificateBuilderSnafu)?;

builder
.add_extension(&aki)
.context(AddCertificateExtensionSnafu)?;

debug!("creating and signing CA certificate");
let certificate = builder.build().context(BuildCertificateSnafu)?;

Ok(CertificateAuthority {
certificate_pair: CertificatePair {
certificate,
key_pair: signing_key_pair,
},
})
}
}

#[cfg(test)]
mod tests {
use x509_cert::certificate::TbsCertificateInner;

use super::*;
use crate::keys::{ecdsa, rsa};

#[test]
fn minimal_ca() {
let ca: CertificateAuthority<ecdsa::SigningKey> = CertificateAuthorityBuilder::builder()
.build()
.build_ca()
.expect("failed to build CA");

assert_ca_cert_attributes(
&ca.ca_cert().tbs_certificate,
SDP_ROOT_CA_SUBJECT,
DEFAULT_CA_VALIDITY,
None,
)
}

#[test]
fn customized_ca() {
let ca = CertificateAuthorityBuilder::builder()
.subject("CN=Test")
.serial_number(42)
.signing_key_pair(rsa::SigningKey::new().unwrap())
.validity(Duration::from_days_unchecked(13))
.build()
.build_ca()
.expect("failed to build CA");

assert_ca_cert_attributes(
&ca.ca_cert().tbs_certificate,
"CN=Test",
Duration::from_days_unchecked(13),
Some(42),
)
}

fn assert_ca_cert_attributes(
ca_cert: &TbsCertificateInner,
subject: &str,
validity: Duration,
serial_number: Option<u64>,
) {
assert_eq!(ca_cert.subject, subject.parse().unwrap());

let not_before = ca_cert.validity.not_before.to_system_time();
let not_after = ca_cert.validity.not_after.to_system_time();
assert_eq!(
not_after
.duration_since(not_before)
.expect("Failed to calculate duration between notBefore and notAfter"),
*validity
);

if let Some(serial_number) = serial_number {
assert_eq!(ca_cert.serial_number, SerialNumber::from(serial_number))
} else {
assert_ne!(ca_cert.serial_number, SerialNumber::from(0_u64))
}
}
}
15 changes: 12 additions & 3 deletions crates/stackable-certs/src/ca/consts.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,14 @@
/// The default CA validity time span of one hour (3600 seconds).
pub const DEFAULT_CA_VALIDITY_SECONDS: u64 = 3600;
use rsa::pkcs8::LineEnding;
use stackable_operator::time::Duration;

/// The default CA validity time span of one hour.
pub const DEFAULT_CA_VALIDITY: Duration = Duration::from_hours_unchecked(1);

/// The default certificate validity time span of one hour.
pub const DEFAULT_CERTIFICATE_VALIDITY: Duration = Duration::from_hours_unchecked(1);

/// The root CA subject name containing only the common name.
pub const ROOT_CA_SUBJECT: &str = "CN=Stackable Data Platform Internal CA";
pub const SDP_ROOT_CA_SUBJECT: &str = "CN=Stackable Data Platform Internal CA";

/// As we are mostly on Unix systems, we are using `\ņ`.
pub const PEM_LINE_ENDING: LineEnding = LineEnding::LF;
Loading
Loading