diff --git a/pkg/controller/certs/certs.go b/pkg/controller/certs/certs.go index 3085959065..bd97d8b005 100644 --- a/pkg/controller/certs/certs.go +++ b/pkg/controller/certs/certs.go @@ -81,7 +81,7 @@ func GenerateCA(notAfter time.Time, organization string) (*KeyPair, error) { BasicConstraintsValid: true, } - privateKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + privateKey, err := ecdsa.GenerateKey(elliptic.P384(), rand.Reader) if err != nil { return nil, err } @@ -134,7 +134,7 @@ func CreateSignedServingPair(notAfter time.Time, organization string, ca *KeyPai DNSNames: hosts, } - privateKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + privateKey, err := ecdsa.GenerateKey(elliptic.P384(), rand.Reader) if err != nil { return nil, err } @@ -158,6 +158,37 @@ func CreateSignedServingPair(notAfter time.Time, organization string, ca *KeyPai return servingCert, nil } +// IsP384 reports whether the given certificate's public key is an ECDSA key on +// the P-384 curve, the curve OLM generates all of its CA and serving cert key +// material with. Certificates using any other algorithm or curve (for example, +// the P-256 material generated by older versions of OLM) should be rotated. +func IsP384(cert *x509.Certificate) bool { + if cert == nil { + return false + } + if cert.PublicKeyAlgorithm != x509.ECDSA { + return false + } + publicKey, ok := cert.PublicKey.(*ecdsa.PublicKey) + if !ok { + return false + } + return publicKey.Curve == elliptic.P384() +} + +// CurrentCAPEM returns the PEM encoding of the first certificate in the given +// PEM bundle. OLM always writes the current CA first in any multi-CA bundle it +// produces (for example, while trust is transitioned from a previous CA to the +// current one), so the first certificate of a bundle is the current CA. It +// returns nil if the bundle does not contain a PEM block. +func CurrentCAPEM(bundle []byte) []byte { + block, _ := pem.Decode(bundle) + if block == nil { + return nil + } + return pem.EncodeToMemory(block) +} + // PEMToCert converts the PEM block of the given byte array to an x509 certificate func PEMToCert(certPEM []byte) (*x509.Certificate, error) { block, _ := pem.Decode(certPEM) diff --git a/pkg/controller/certs/certs_test.go b/pkg/controller/certs/certs_test.go index 29945643bc..5e0ad73cff 100644 --- a/pkg/controller/certs/certs_test.go +++ b/pkg/controller/certs/certs_test.go @@ -2,6 +2,9 @@ package certs import ( "crypto/ecdsa" + "crypto/elliptic" + "crypto/rand" + "crypto/rsa" "crypto/x509" "encoding/pem" "errors" @@ -40,7 +43,9 @@ func TestGenerateCA(t *testing.T) { require.Equal(t, []string{testOrganization}, ca.Cert.Subject.Organization) require.Contains(t, ca.Cert.Subject.CommonName, "olm-selfsigned-") require.True(t, ca.Cert.NotAfter.Equal(notAfter), "notAfter should be the requested value") - require.Equal(t, "P-256", ca.Priv.Curve.Params().Name) + require.Equal(t, "P-384", ca.Priv.Curve.Params().Name) + require.True(t, IsP384(ca.Cert), "generated CA should use P-384") + require.Equal(t, x509.ECDSAWithSHA384, ca.Cert.SignatureAlgorithm) require.True(t, Active(ca.Cert), "freshly generated CA should be active") // The CA is self-signed: it should verify against a pool containing itself @@ -70,7 +75,9 @@ func TestCreateSignedServingPair(t *testing.T) { require.Equal(t, []string{testOrganization}, pair.Cert.Subject.Organization) require.Equal(t, []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}, pair.Cert.ExtKeyUsage) require.True(t, pair.Cert.NotAfter.Equal(notAfter), "notAfter should be the requested value") - require.Equal(t, "P-256", pair.Priv.Curve.Params().Name) + require.Equal(t, "P-384", pair.Priv.Curve.Params().Name) + require.True(t, IsP384(pair.Cert), "generated serving cert should use P-384") + require.Equal(t, x509.ECDSAWithSHA384, pair.Cert.SignatureAlgorithm) require.True(t, Active(pair.Cert)) // The serving cert chains to the given CA and is valid for every requested host. @@ -88,6 +95,32 @@ func TestCreateSignedServingPair(t *testing.T) { } } +func TestIsP384(t *testing.T) { + p384CA := mustGenerateCA(t) + require.True(t, IsP384(p384CA.Cert)) + + p256Key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + require.NoError(t, err) + p256Cert := &x509.Certificate{ + PublicKeyAlgorithm: x509.ECDSA, + PublicKey: &p256Key.PublicKey, + } + require.False(t, IsP384(p256Cert), "P-256 certificates should not be reported as P-384") + + rsaKey, err := rsa.GenerateKey(rand.Reader, 2048) + require.NoError(t, err) + rsaCert := &x509.Certificate{ + PublicKeyAlgorithm: x509.RSA, + PublicKey: &rsaKey.PublicKey, + } + require.False(t, IsP384(rsaCert), "RSA certificates should not be reported as P-384") + + require.False(t, IsP384(nil), "nil certificates should not be reported as P-384") + + ecdsaCertWithMissingKey := &x509.Certificate{PublicKeyAlgorithm: x509.ECDSA} + require.False(t, IsP384(ecdsaCertWithMissingKey)) +} + func TestVerifyCert(t *testing.T) { ca := mustGenerateCA(t) otherCA := mustGenerateCA(t) @@ -191,6 +224,27 @@ func TestPEMToCert(t *testing.T) { } } +func TestCurrentCAPEM(t *testing.T) { + currentCA := mustGenerateCA(t) + previousCA := mustGenerateCA(t) + currentCAPEM, _, err := currentCA.ToPEM() + require.NoError(t, err) + previousCAPEM, _, err := previousCA.ToPEM() + require.NoError(t, err) + + // A single-cert bundle round-trips to the exact same bytes, so hashing the + // result is stable whether or not a transition is in flight. + require.Equal(t, currentCAPEM, CurrentCAPEM(currentCAPEM)) + + // In a multi-CA bundle the current CA is always first. + bundle := append(append([]byte{}, currentCAPEM...), previousCAPEM...) + require.Equal(t, currentCAPEM, CurrentCAPEM(bundle)) + require.NotEqual(t, previousCAPEM, CurrentCAPEM(bundle)) + + require.Nil(t, CurrentCAPEM(nil)) + require.Nil(t, CurrentCAPEM([]byte("not pem"))) +} + func TestPEMSHA256(t *testing.T) { // Well-known SHA-256 digest of the string "hello". require.Equal(t, "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824", PEMSHA256([]byte("hello"))) diff --git a/pkg/controller/install/certresources.go b/pkg/controller/install/certresources.go index 825eee5e24..4c52d99aff 100644 --- a/pkg/controller/install/certresources.go +++ b/pkg/controller/install/certresources.go @@ -36,6 +36,13 @@ const ( DefaultCertValidFor = time.Hour * 24 * 730 // OLMCAPEMKey is the CAPEM OLMCAPEMKey = "olmCAKey" + // OLMPreviousCAPEMKey is the key under which the PEM of the previous CA is + // stored in a cert Secret while a CA trust transition is in flight. Its + // presence indicates that the transition has not been finalized yet: the + // previous CA is kept in the CABundles of webhook configurations, CRD + // conversions and APIServices until the rollout onto the current CA has + // completed. + OLMPreviousCAPEMKey = "olmPreviousCAKey" // OLMCAHashAnnotationKey is the label key used to store the hash of the CA cert OLMCAHashAnnotationKey = "olmcahash" // Organization is the organization name used in the generation of x509 certs @@ -228,6 +235,30 @@ func (i *StrategyDeploymentInstaller) CertsRotateAt() time.Time { return CalculateCertRotatesAt(i.certificateExpirationTime) } +// caPEMWithPreviousCA returns the given current CA PEM extended with the +// previous CA stored in the given Secret when a CA trust transition is in +// flight, marking the transition on the installer so that cert resources are +// updated before any deployment is rolled out. +func (i *StrategyDeploymentInstaller) caPEMWithPreviousCA(currentCAPEM []byte, secret *corev1.Secret) []byte { + previousCAPEM, ok := secret.Data[OLMPreviousCAPEMKey] + if !ok || len(previousCAPEM) == 0 { + return currentCAPEM + } + i.caTransition = true + return caPEMBundle(currentCAPEM, previousCAPEM) +} + +// caPEMBundle returns a PEM bundle with the current CA followed by the +// previous CA. The current CA is always written first so that hashing the +// first certificate of a bundle (see certs.CurrentCAPEM) yields the hash of +// the current CA, and removing the previous CA from the bundle does not +// change it. +func caPEMBundle(currentCAPEM, previousCAPEM []byte) []byte { + bundle := make([]byte, 0, len(currentCAPEM)+len(previousCAPEM)) + bundle = append(bundle, currentCAPEM...) + return append(bundle, previousCAPEM...) +} + func (i *StrategyDeploymentInstaller) CertsRotated() bool { return i.certificatesRotated } @@ -258,6 +289,12 @@ func shouldRotateCerts(certSecret *corev1.Secret, hosts []string) bool { return true } + // Rotate CA and serving certs that do not use ECDSA P-384, e.g. the P-256 + // material generated by older versions of OLM. + if !certs.IsP384(ca) || !certs.IsP384(cert) { + return true + } + // check for cert freshness if !certs.Active(ca) || now.Time.After(CalculateCertRotatesAt(ca.NotAfter)) || !certs.Active(cert) || now.Time.After(CalculateCertRotatesAt(cert.NotAfter)) { @@ -300,6 +337,88 @@ func (i *StrategyDeploymentInstaller) ShouldRotateCerts(s Strategy) (bool, error return false, nil } +// FinalizeCATransition completes an in-flight CA trust transition once every +// deployment has rolled out onto the current CA: the CABundles of the +// generated cert resources (webhook configurations, CRD conversions and +// APIServices) are rewritten with only the current CA and the transition +// state (the olmPreviousCAKey entry) is cleared from the cert Secrets. +// +// It returns true when a transition was in flight and has been finalized. The +// previous CA is only dropped once each deployment that owns cert resources +// is up-to-date and available and carries an olmcahash annotation matching +// the current CA of its cert Secret, so that no pod still serves a +// certificate trusted only via the previous CA. Removing the previous CA does +// not change the olmcahash (which hashes the current CA only) and therefore +// does not trigger an additional rollout. +func (i *StrategyDeploymentInstaller) FinalizeCATransition(s Strategy) (bool, error) { + strategy, ok := s.(*v1alpha1.StrategyDetailsDeployment) + if !ok { + return false, fmt.Errorf("failed to finalize CA transition with deployment installer: unsupported deployment install strategy: %s", s.GetStrategyName()) + } + + // Collect the cert Secrets with an in-flight transition and point every + // cert resource at the current CA of its deployment's Secret, so that the + // CABundles are rewritten without the previous CA. + inFlight := map[string]*corev1.Secret{} + for _, sddSpec := range strategy.DeploymentSpecs { + if len(i.certResourcesForDeployment(sddSpec.Name)) == 0 { + continue + } + secret, err := i.strategyClient.GetOpLister().CoreV1().SecretLister().Secrets(i.owner.GetNamespace()).Get(SecretName(ServiceName(sddSpec.Name))) + if err != nil { + if apierrors.IsNotFound(err) { + // The cert Secret is managed by the install path. If it is + // missing, the CSV is reinstalled and the transition restarts. + return false, nil + } + return false, err + } + if len(secret.Data[OLMPreviousCAPEMKey]) > 0 { + inFlight[sddSpec.Name] = secret + } + i.updateCertResourcesForDeployment(sddSpec.Name, secret.Data[OLMCAPEMKey]) + } + if len(inFlight) == 0 { + return false, nil + } + + // Wait for the rollout onto the current CA to complete before dropping + // trust in the previous CA. + for deploymentName, secret := range inFlight { + deployment, err := i.strategyClient.GetOpLister().AppsV1().DeploymentLister().Deployments(i.owner.GetNamespace()).Get(deploymentName) + if err != nil { + return false, err + } + reason, ready, err := DeploymentStatus(deployment) + if err != nil { + return false, err + } + if !ready { + log.Infof("waiting for deployment %s to roll out onto the current CA before finalizing the CA transition: %s", deploymentName, reason) + return false, nil + } + if hash, ok := deployment.Spec.Template.GetAnnotations()[OLMCAHashAnnotationKey]; !ok || hash != secret.GetAnnotations()[OLMCAHashAnnotationKey] { + log.Infof("waiting for deployment %s to pick up the current CA hash before finalizing the CA transition", deploymentName) + return false, nil + } + } + + // Rewrite the CABundles with only the current CA, then clear the + // transition state. Neither step changes the olmcahash, so no additional + // rollout is triggered. + if err := i.createOrUpdateCertResourcesForDeployment(); err != nil { + return false, err + } + for _, secret := range inFlight { + updated := secret.DeepCopy() + delete(updated.Data, OLMPreviousCAPEMKey) + if _, err := i.strategyClient.GetOpClient().UpdateSecret(updated); err != nil { + return false, err + } + } + return true, nil +} + func CalculateCertExpiration(startingFrom time.Time) time.Time { return startingFrom.Add(DefaultCertValidFor) } @@ -384,12 +503,32 @@ func (i *StrategyDeploymentInstaller) installCertRequirementsForDeployment(deplo secret = existingSecret caPEM = existingSecret.Data[OLMCAPEMKey] caHash = certs.PEMSHA256(caPEM) + caPEM = i.caPEMWithPreviousCA(caPEM, existingSecret) } else { + // Start a CA trust transition when the existing CA is still + // active: remember it in the secret so that it remains trusted in + // the CABundles until the rollout onto the current CA has + // completed and the transition is finalized. + previousCAPEM := existingSecret.Data[OLMCAPEMKey] + previousCA, prevErr := certs.PEMToCert(previousCAPEM) + switch { + case prevErr != nil: + logger.Warnf("existing CA for Service %s is malformed, rotating without a trust transition: %v", serviceName, prevErr) + case !certs.Active(previousCA): + logger.Warnf("existing CA for Service %s is no longer active, rotating without a trust transition", serviceName) + default: + secret.Data[OLMPreviousCAPEMKey] = previousCAPEM + } + if _, err := i.strategyClient.GetOpClient().UpdateSecret(secret); err != nil { logger.Warnf("could not update secret %s", secret.GetName()) return nil, nil, err } i.certificatesRotated = true + if _, ok := secret.Data[OLMPreviousCAPEMKey]; ok { + i.caTransition = true + caPEM = caPEMBundle(caPEM, previousCAPEM) + } } } else if apierrors.IsNotFound(err) { // Create the secret diff --git a/pkg/controller/install/certresources_test.go b/pkg/controller/install/certresources_test.go index 2c7de44bd5..e0190a2774 100644 --- a/pkg/controller/install/certresources_test.go +++ b/pkg/controller/install/certresources_test.go @@ -1,7 +1,14 @@ package install import ( + "crypto/ecdsa" + "crypto/elliptic" + "crypto/rand" + "crypto/x509" + "crypto/x509/pkix" "fmt" + "math" + "math/big" "reflect" "testing" "time" @@ -15,9 +22,12 @@ import ( rbacv1 "k8s.io/api/rbac/v1" "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/labels" "k8s.io/apimachinery/pkg/runtime/schema" corev1ac "k8s.io/client-go/applyconfigurations/core/v1" rbacv1ac "k8s.io/client-go/applyconfigurations/rbac/v1" + appslisters "k8s.io/client-go/listers/apps/v1" + apiregistrationv1 "k8s.io/kube-aggregator/pkg/apis/apiregistration/v1" "github.com/operator-framework/api/pkg/operators/v1alpha1" "github.com/operator-framework/operator-lifecycle-manager/pkg/api/wrappers" @@ -34,6 +44,60 @@ func keyPair(t *testing.T, expiration time.Time) *certs.KeyPair { return p } +// keyPairWithCurve generates a self-signed CA on the given curve, for building +// fixtures that mimic key material generated by older versions of OLM. +func keyPairWithCurve(t *testing.T, curve elliptic.Curve, notAfter time.Time) *certs.KeyPair { + t.Helper() + serial, err := rand.Int(rand.Reader, new(big.Int).SetInt64(math.MaxInt64)) + require.NoError(t, err) + caDetails := &x509.Certificate{ + SerialNumber: serial, + Subject: pkix.Name{ + CommonName: fmt.Sprintf("olm-selfsigned-%x", serial), + Organization: []string{Organization}, + }, + NotBefore: time.Now().Add(-time.Hour), + NotAfter: notAfter, + IsCA: true, + KeyUsage: x509.KeyUsageCertSign, + BasicConstraintsValid: true, + } + priv, err := ecdsa.GenerateKey(curve, rand.Reader) + require.NoError(t, err) + certRaw, err := x509.CreateCertificate(rand.Reader, caDetails, caDetails, &priv.PublicKey, priv) + require.NoError(t, err) + cert, err := x509.ParseCertificate(certRaw) + require.NoError(t, err) + return &certs.KeyPair{Cert: cert, Priv: priv} +} + +// signedPairWithCurve generates a serving pair on the given curve, for building +// fixtures that mimic key material generated by older versions of OLM. +func signedPairWithCurve(t *testing.T, curve elliptic.Curve, ca *certs.KeyPair, notAfter time.Time, hosts []string) *certs.KeyPair { + t.Helper() + serial, err := rand.Int(rand.Reader, new(big.Int).SetInt64(math.MaxInt64)) + require.NoError(t, err) + certDetails := &x509.Certificate{ + SerialNumber: serial, + Subject: pkix.Name{ + CommonName: hosts[0], + Organization: []string{Organization}, + }, + NotBefore: time.Now().Add(-time.Hour), + NotAfter: notAfter, + ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}, + BasicConstraintsValid: true, + DNSNames: hosts, + } + priv, err := ecdsa.GenerateKey(curve, rand.Reader) + require.NoError(t, err) + certRaw, err := x509.CreateCertificate(rand.Reader, certDetails, ca.Cert, &priv.PublicKey, ca.Priv) + require.NoError(t, err) + cert, err := x509.ParseCertificate(certRaw) + require.NoError(t, err) + return &certs.KeyPair{Cert: cert, Priv: priv} +} + func selector(t *testing.T, selector string) *metav1.LabelSelector { s, err := metav1.ParseToLabelSelector(selector) assert.NoError(t, err) @@ -996,3 +1060,790 @@ func TestInstallCertRequirementsForDeployment(t *testing.T) { }) } } + +func TestShouldRotateCertsKeyAlgorithm(t *testing.T) { + hosts := HostnamesForService("test-service", "test-namespace") + notAfter := time.Now().Add(730 * 24 * time.Hour) + + p384CA := keyPair(t, notAfter) + p384Pair, err := certs.CreateSignedServingPair(notAfter, Organization, p384CA, hosts) + require.NoError(t, err) + p384CAPEM, _, err := p384CA.ToPEM() + require.NoError(t, err) + p384ServingCertPEM, _, err := p384Pair.ToPEM() + require.NoError(t, err) + + p256CA := keyPairWithCurve(t, elliptic.P256(), notAfter) + p256Pair := signedPairWithCurve(t, elliptic.P256(), p256CA, notAfter, hosts) + p256CAPEM, _, err := p256CA.ToPEM() + require.NoError(t, err) + p256ServingCertPEM, _, err := p256Pair.ToPEM() + require.NoError(t, err) + + certSecret := func(caPEM, certPEM []byte) *corev1.Secret { + return &corev1.Secret{ + Data: map[string][]byte{ + OLMCAPEMKey: caPEM, + "tls.crt": certPEM, + }, + } + } + + tests := []struct { + name string + secret *corev1.Secret + rotation bool + }{ + { + name: "P-384 CA and serving cert are reused", + secret: certSecret(p384CAPEM, p384ServingCertPEM), + rotation: false, + }, + { + name: "P-256 CA is rotated", + secret: certSecret(p256CAPEM, p256ServingCertPEM), + rotation: true, + }, + { + name: "P-256 serving cert is rotated", + secret: certSecret(p384CAPEM, p256ServingCertPEM), + rotation: true, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + require.Equal(t, tt.rotation, shouldRotateCerts(tt.secret, hosts)) + }) + } +} + +// expectCertResourceRBAC mocks the Role, RoleBinding, auth-delegator +// ClusterRoleBinding and auth-reader RoleBinding interactions performed by +// installCertRequirementsForDeployment for a secret named "test-service-cert" +// used by the "test-sa" service account. +func expectCertResourceRBAC(t *testing.T, mockOpClient *operatorclientmocks.MockClientInterface, owner ownerutil.Owner, namespace string) { + t.Helper() + + secretRole := &rbacv1.Role{ + ObjectMeta: metav1.ObjectMeta{ + Name: "test-service-cert", + Namespace: namespace, + Labels: map[string]string{OLMManagedLabelKey: OLMManagedLabelValue}, + }, + Rules: []rbacv1.PolicyRule{ + { + Verbs: []string{"get"}, + APIGroups: []string{""}, + Resources: []string{"secrets"}, + ResourceNames: []string{"test-service-cert"}, + }, + }, + } + mockOpClient.EXPECT().UpdateRole(secretRole).Return(secretRole, nil) + + roleBinding := &rbacv1.RoleBinding{ + ObjectMeta: metav1.ObjectMeta{ + Name: "test-service-cert", + Namespace: namespace, + Labels: map[string]string{OLMManagedLabelKey: OLMManagedLabelValue}, + }, + Subjects: []rbacv1.Subject{ + { + Kind: "ServiceAccount", + APIGroup: "", + Name: "test-sa", + Namespace: namespace, + }, + }, + RoleRef: rbacv1.RoleRef{ + APIGroup: "rbac.authorization.k8s.io", + Kind: "Role", + Name: secretRole.GetName(), + }, + } + mockOpClient.EXPECT().UpdateRoleBinding(roleBinding).Return(roleBinding, nil) + + authDelegatorClusterRoleBinding := &rbacv1.ClusterRoleBinding{ + ObjectMeta: metav1.ObjectMeta{ + Name: "test-service-system:auth-delegator", + Labels: map[string]string{OLMManagedLabelKey: OLMManagedLabelValue}, + }, + RoleRef: rbacv1.RoleRef{ + APIGroup: "rbac.authorization.k8s.io", + Kind: "ClusterRole", + Name: "system:auth-delegator", + }, + } + + crbLabels := map[string]string{OLMManagedLabelKey: OLMManagedLabelValue} + for key, val := range ownerutil.OwnerLabel(owner, owner.GetObjectKind().GroupVersionKind().Kind) { + crbLabels[key] = val + } + crbApplyConfig := rbacv1ac.ClusterRoleBinding(AuthDelegatorClusterRoleBindingName("test-service")). + WithSubjects(rbacv1ac.Subject(). + WithKind("ServiceAccount"). + WithAPIGroup(""). + WithName("test-sa"). + WithNamespace(namespace)). + WithRoleRef(rbacv1ac.RoleRef(). + WithAPIGroup("rbac.authorization.k8s.io"). + WithKind("ClusterRole"). + WithName("system:auth-delegator")). + WithLabels(crbLabels) + mockOpClient.EXPECT().ApplyClusterRoleBinding(crbApplyConfig, metav1.ApplyOptions{Force: true, FieldManager: "olm.install"}).Return(authDelegatorClusterRoleBinding, nil) + + authReaderRoleBinding := &rbacv1.RoleBinding{ + ObjectMeta: metav1.ObjectMeta{ + Name: AuthReaderRoleBindingName("test-service"), + Namespace: KubeSystem, + Labels: map[string]string{OLMManagedLabelKey: OLMManagedLabelValue}, + }, + RoleRef: rbacv1.RoleRef{ + APIGroup: "rbac.authorization.k8s.io", + Kind: "Role", + Name: "extension-apiserver-authentication-reader", + }, + } + + authReaderRoleBindingApplyConfig := rbacv1ac.RoleBinding(AuthReaderRoleBindingName("test-service"), KubeSystem). + WithLabels(map[string]string{OLMManagedLabelKey: OLMManagedLabelValue}). + WithSubjects(rbacv1ac.Subject(). + WithKind("ServiceAccount"). + WithAPIGroup(""). + WithName("test-sa"). + WithNamespace(namespace)). + WithRoleRef(rbacv1ac.RoleRef(). + WithAPIGroup("rbac.authorization.k8s.io"). + WithKind("Role"). + WithName("extension-apiserver-authentication-reader")) + mockOpClient.EXPECT().ApplyRoleBinding(authReaderRoleBindingApplyConfig, metav1.ApplyOptions{Force: true, FieldManager: "olm.install"}).Return(authReaderRoleBinding, nil) +} + +func TestInstallCertRequirementsForDeploymentCATransition(t *testing.T) { + namespace := "test-namespace" + owner := ownerutil.Owner(&v1alpha1.ClusterServiceVersion{ + TypeMeta: metav1.TypeMeta{ + Kind: v1alpha1.ClusterServiceVersionKind, + APIVersion: v1alpha1.ClusterServiceVersionAPIVersion, + }, + ObjectMeta: metav1.ObjectMeta{ + Name: "owner", + Namespace: namespace, + UID: "123-uid", + }, + }) + + hosts := HostnamesForService(ServiceName("test"), namespace) + notAfter := time.Now().Add(730 * 24 * time.Hour) + + // P-256 material as generated by older versions of OLM. + previousCA := keyPairWithCurve(t, elliptic.P256(), notAfter) + previousCAPEM, _, err := previousCA.ToPEM() + require.NoError(t, err) + previousPair := signedPairWithCurve(t, elliptic.P256(), previousCA, notAfter, hosts) + previousCertPEM, previousPrivPEM, err := previousPair.ToPEM() + require.NoError(t, err) + + baseDepSpec := appsv1.DeploymentSpec{ + Selector: selector(t, "test=label"), + Template: corev1.PodTemplateSpec{ + Spec: corev1.PodSpec{ + ServiceAccountName: "test-sa", + }, + }, + } + + t.Run("RotationFromP256StoresPreviousCAAndReturnsDualCABundle", func(t *testing.T) { + ctrl := gomock.NewController(t) + defer ctrl.Finish() + + certGenerator = certs.CertGeneratorFunc(staticCertGenerator) + staticCerts = nil + + currentCA := keyPair(t, notAfter) + currentCAPEM, _, err := currentCA.ToPEM() + require.NoError(t, err) + + mockOpClient := operatorclientmocks.NewMockClientInterface(ctrl) + state := fakeState{ + existingSecret: &corev1.Secret{ + ObjectMeta: metav1.ObjectMeta{}, + Data: map[string][]byte{ + OLMCAPEMKey: previousCAPEM, + "tls.crt": previousCertPEM, + "tls.key": previousPrivPEM, + }, + }, + existingRole: &rbacv1.Role{ObjectMeta: metav1.ObjectMeta{}}, + existingRoleBinding: &rbacv1.RoleBinding{ObjectMeta: metav1.ObjectMeta{}}, + } + fakeLister := newFakeLister(state) + + service := corev1.Service{ + ObjectMeta: metav1.ObjectMeta{ + Name: "test-service", + Namespace: namespace, + Labels: map[string]string{OLMManagedLabelKey: OLMManagedLabelValue}, + OwnerReferences: []metav1.OwnerReference{ + ownerutil.NonBlockingOwner(owner), + }, + }, + Spec: corev1.ServiceSpec{ + Selector: selector(t, "test=label").MatchLabels, + }, + } + svcApplyConfig := corev1ac.Service(service.Name, service.Namespace). + WithSpec(corev1ac.ServiceSpec(). + WithSelector(selector(t, "test=label").MatchLabels)). + WithOwnerReferences(ownerutil.NonBlockingOwnerApplyConfiguration(owner)). + WithLabels(map[string]string{OLMManagedLabelKey: OLMManagedLabelValue}) + mockOpClient.EXPECT().ApplyService(svcApplyConfig, metav1.ApplyOptions{Force: true, FieldManager: "olm.install"}).Return(&service, nil) + + servingPair, err := certGenerator.Generate(notAfter, Organization, currentCA, hosts) + require.NoError(t, err) + certPEM, privPEM, err := servingPair.ToPEM() + require.NoError(t, err) + + expectedSecret := &corev1.Secret{ + ObjectMeta: metav1.ObjectMeta{ + Name: "test-service-cert", + Namespace: namespace, + Annotations: map[string]string{OLMCAHashAnnotationKey: certs.PEMSHA256(currentCAPEM)}, + Labels: map[string]string{OLMManagedLabelKey: OLMManagedLabelValue}, + }, + Data: map[string][]byte{ + "tls.crt": certPEM, + "tls.key": privPEM, + OLMCAPEMKey: currentCAPEM, + OLMPreviousCAPEMKey: previousCAPEM, + }, + Type: corev1.SecretTypeTLS, + } + mockOpClient.EXPECT().UpdateSecret(expectedSecret).Return(expectedSecret, nil) + + expectCertResourceRBAC(t, mockOpClient, owner, namespace) + + client := wrappers.NewInstallStrategyDeploymentClient(mockOpClient, fakeLister, namespace) + i := &StrategyDeploymentInstaller{ + strategyClient: client, + owner: owner, + apiServiceDescriptions: []certResource{}, + webhookDescriptions: []certResource{}, + } + + depSpec, caPEM, err := i.installCertRequirementsForDeployment("test", currentCA, notAfter, baseDepSpec, []corev1.ServicePort{}) + require.NoError(t, err) + + // The CA PEM written to webhook configurations and APIServices is a + // dual-trust bundle of the current and previous CA... + require.Equal(t, caPEMBundle(currentCAPEM, previousCAPEM), caPEM) + // ...but the olmcahash annotation hashes only the current CA, so + // removing the previous CA later will not trigger another rollout. + require.Equal(t, certs.PEMSHA256(currentCAPEM), depSpec.Template.GetAnnotations()[OLMCAHashAnnotationKey]) + require.True(t, i.caTransition) + require.True(t, i.certificatesRotated) + }) + + t.Run("ReuseKeepsDualCABundleWhileTransitionIsInFlight", func(t *testing.T) { + ctrl := gomock.NewController(t) + defer ctrl.Finish() + + certGenerator = certs.CertGeneratorFunc(staticCertGenerator) + staticCerts = nil + + currentCA := keyPair(t, notAfter) + currentCAPEM, _, err := currentCA.ToPEM() + require.NoError(t, err) + currentPair, err := certs.CreateSignedServingPair(notAfter, Organization, currentCA, hosts) + require.NoError(t, err) + currentCertPEM, currentPrivPEM, err := currentPair.ToPEM() + require.NoError(t, err) + + mockOpClient := operatorclientmocks.NewMockClientInterface(ctrl) + state := fakeState{ + existingSecret: &corev1.Secret{ + ObjectMeta: metav1.ObjectMeta{ + Name: "test-service-cert", + Namespace: namespace, + Annotations: map[string]string{OLMCAHashAnnotationKey: certs.PEMSHA256(currentCAPEM)}, + }, + Data: map[string][]byte{ + OLMCAPEMKey: currentCAPEM, + OLMPreviousCAPEMKey: previousCAPEM, + "tls.crt": currentCertPEM, + "tls.key": currentPrivPEM, + }, + }, + existingRole: &rbacv1.Role{ObjectMeta: metav1.ObjectMeta{}}, + existingRoleBinding: &rbacv1.RoleBinding{ObjectMeta: metav1.ObjectMeta{}}, + } + fakeLister := newFakeLister(state) + + service := corev1.Service{ + ObjectMeta: metav1.ObjectMeta{ + Name: "test-service", + Namespace: namespace, + Labels: map[string]string{OLMManagedLabelKey: OLMManagedLabelValue}, + OwnerReferences: []metav1.OwnerReference{ + ownerutil.NonBlockingOwner(owner), + }, + }, + Spec: corev1.ServiceSpec{ + Selector: selector(t, "test=label").MatchLabels, + }, + } + svcApplyConfig := corev1ac.Service(service.Name, service.Namespace). + WithSpec(corev1ac.ServiceSpec(). + WithSelector(selector(t, "test=label").MatchLabels)). + WithOwnerReferences(ownerutil.NonBlockingOwnerApplyConfiguration(owner)). + WithLabels(map[string]string{OLMManagedLabelKey: OLMManagedLabelValue}) + mockOpClient.EXPECT().ApplyService(svcApplyConfig, metav1.ApplyOptions{Force: true, FieldManager: "olm.install"}).Return(&service, nil) + + // The existing certs are valid P-384 material: the secret is not + // rewritten, only the RBAC is reconciled. + expectCertResourceRBAC(t, mockOpClient, owner, namespace) + + client := wrappers.NewInstallStrategyDeploymentClient(mockOpClient, fakeLister, namespace) + i := &StrategyDeploymentInstaller{ + strategyClient: client, + owner: owner, + apiServiceDescriptions: []certResource{}, + webhookDescriptions: []certResource{}, + } + + depSpec, caPEM, err := i.installCertRequirementsForDeployment("test", currentCA, notAfter, baseDepSpec, []corev1.ServicePort{}) + require.NoError(t, err) + + // The dual-trust bundle is kept while the transition is in flight... + require.Equal(t, caPEMBundle(currentCAPEM, previousCAPEM), caPEM) + // ...and the olmcahash still hashes only the current CA. + require.Equal(t, certs.PEMSHA256(currentCAPEM), depSpec.Template.GetAnnotations()[OLMCAHashAnnotationKey]) + require.True(t, i.caTransition) + require.False(t, i.certificatesRotated) + }) +} + +// stubAPIServiceLister implements the kube-aggregator APIServiceLister +// interface for a single APIService. +type stubAPIServiceLister struct { + apiService *apiregistrationv1.APIService + err error +} + +func (s stubAPIServiceLister) List(labels.Selector) ([]*apiregistrationv1.APIService, error) { + return nil, nil +} + +func (s stubAPIServiceLister) Get(name string) (*apiregistrationv1.APIService, error) { + return s.apiService, s.err +} + +func TestInstallDeploymentsCATransitionOrdering(t *testing.T) { + namespace := "test-namespace" + owner := ownerutil.Owner(&v1alpha1.ClusterServiceVersion{ + TypeMeta: metav1.TypeMeta{ + Kind: v1alpha1.ClusterServiceVersionKind, + APIVersion: v1alpha1.ClusterServiceVersionAPIVersion, + }, + ObjectMeta: metav1.ObjectMeta{ + Name: "owner", + Namespace: namespace, + UID: "123-uid", + }, + }) + + currentCAPEM, _, err := keyPair(t, time.Now().Add(730*24*time.Hour)).ToPEM() + require.NoError(t, err) + previousCAPEM, _, err := keyPairWithCurve(t, elliptic.P256(), time.Now().Add(730*24*time.Hour)).ToPEM() + require.NoError(t, err) + bundle := caPEMBundle(currentCAPEM, previousCAPEM) + + depSpec := appsv1.DeploymentSpec{ + Selector: selector(t, "test=label"), + Template: corev1.PodTemplateSpec{ + ObjectMeta: metav1.ObjectMeta{ + Labels: map[string]string{"app": "test"}, + }, + Spec: corev1.PodSpec{ + ServiceAccountName: "test-sa", + Containers: []corev1.Container{ + {Name: "test-c1", Image: "docker.io/nginx:1.7.9"}, + }, + }, + }, + } + + existingAPIService := &apiregistrationv1.APIService{ + ObjectMeta: metav1.ObjectMeta{ + Name: "v1.g1", + Namespace: namespace, + Labels: map[string]string{ + ownerutil.OwnerKind: v1alpha1.ClusterServiceVersionKind, + ownerutil.OwnerKey: owner.GetName(), + ownerutil.OwnerNamespaceKey: namespace, + }, + }, + } + + notFound := func(resource, name string) error { + return errors.NewNotFound(schema.GroupResource{Group: "", Resource: resource}, name) + } + + newInstaller := func(t *testing.T, mockOpClient *operatorclientmocks.MockClientInterface, caTransition bool) *StrategyDeploymentInstaller { + t.Helper() + + fakeLister := &operatorlisterfakes.FakeOperatorLister{} + fakeAPIRegistrationV1Lister := &operatorlisterfakes.FakeAPIRegistrationV1Lister{} + fakeAPIRegistrationV1Lister.APIServiceListerReturns(stubAPIServiceLister{apiService: existingAPIService}) + fakeLister.APIRegistrationV1Returns(fakeAPIRegistrationV1Lister) + + csvNotFound := notFound("clusterserviceversions", "owner") + fakeCSVLister := &operatorlisterfakes.FakeClusterServiceVersionLister{} + fakeCSVNamespaceLister := &operatorlisterfakes.FakeClusterServiceVersionNamespaceLister{} + fakeCSVNamespaceLister.GetReturns(nil, csvNotFound) + fakeCSVLister.ClusterServiceVersionsReturns(fakeCSVNamespaceLister) + fakeOperatorsV1alpha1Lister := &operatorlisterfakes.FakeOperatorsV1alpha1Lister{} + fakeOperatorsV1alpha1Lister.ClusterServiceVersionListerReturns(fakeCSVLister) + fakeLister.OperatorsV1alpha1Returns(fakeOperatorsV1alpha1Lister) + + client := wrappers.NewInstallStrategyDeploymentClient(mockOpClient, fakeLister, namespace) + return &StrategyDeploymentInstaller{ + strategyClient: client, + owner: owner, + apiServiceDescriptions: []certResource{ + &apiServiceDescriptionsWithCAPEM{ + apiServiceDescription: v1alpha1.APIServiceDescription{ + Name: "v1.g1", + Group: "g1", + Version: "v1", + DeploymentName: "test", + ContainerPort: 443, + }, + caPEM: bundle, + }, + }, + webhookDescriptions: []certResource{}, + caTransition: caTransition, + } + } + + // expectLegacyAPIServiceCleanup mocks the lookups for resources created by + // older OLM versions for the "v1.g1" APIService; none of them exist. + expectLegacyAPIServiceCleanup := func(mockOpClient *operatorclientmocks.MockClientInterface) { + mockOpClient.EXPECT().GetService(namespace, "v1-g1").Return(nil, notFound("services", "v1-g1")) + mockOpClient.EXPECT().GetSecret(namespace, "v1.g1-cert").Return(nil, notFound("secrets", "v1.g1-cert")) + mockOpClient.EXPECT().GetRole(namespace, "v1.g1-cert").Return(nil, notFound("roles", "v1.g1-cert")) + mockOpClient.EXPECT().GetRoleBinding(namespace, "v1.g1-cert").Return(nil, notFound("rolebindings", "v1.g1-cert")) + mockOpClient.EXPECT().GetClusterRoleBinding("v1.g1-system:auth-delegator").Return(nil, notFound("clusterrolebindings", "v1.g1-system:auth-delegator")) + mockOpClient.EXPECT().GetRoleBinding(KubeSystem, "v1.g1-auth-reader").Return(nil, notFound("rolebindings", "v1.g1-auth-reader")) + } + + t.Run("CertResourcesAreUpdatedBeforeTheDeploymentDuringATransition", func(t *testing.T) { + ctrl := gomock.NewController(t) + defer ctrl.Finish() + + mockOpClient := operatorclientmocks.NewMockClientInterface(ctrl) + expectLegacyAPIServiceCleanup(mockOpClient) + + gomock.InOrder( + // Phase 1: the dual-trust CABundle is written to the APIService... + mockOpClient.EXPECT().UpdateAPIService(gomock.Any()).DoAndReturn(func(apiService *apiregistrationv1.APIService) (*apiregistrationv1.APIService, error) { + require.Equal(t, bundle, apiService.Spec.CABundle) + return apiService, nil + }), + // ...before phase 2 rolls the deployment onto the new CA. + mockOpClient.EXPECT().GetDeployment(namespace, "test").Return(nil, notFound("deployments", "test")), + mockOpClient.EXPECT().CreateDeployment(gomock.Any()).DoAndReturn(func(deployment *appsv1.Deployment) (*appsv1.Deployment, error) { + return deployment, nil + }), + ) + + i := newInstaller(t, mockOpClient, true) + require.NoError(t, i.installDeployments([]v1alpha1.StrategyDeploymentSpec{{Name: "test", Spec: depSpec}})) + }) + + t.Run("DeploymentIsUpdatedBeforeCertResourcesOutsideATransition", func(t *testing.T) { + ctrl := gomock.NewController(t) + defer ctrl.Finish() + + mockOpClient := operatorclientmocks.NewMockClientInterface(ctrl) + expectLegacyAPIServiceCleanup(mockOpClient) + + gomock.InOrder( + mockOpClient.EXPECT().GetDeployment(namespace, "test").Return(nil, notFound("deployments", "test")), + mockOpClient.EXPECT().CreateDeployment(gomock.Any()).DoAndReturn(func(deployment *appsv1.Deployment) (*appsv1.Deployment, error) { + return deployment, nil + }), + mockOpClient.EXPECT().UpdateAPIService(gomock.Any()).DoAndReturn(func(apiService *apiregistrationv1.APIService) (*apiregistrationv1.APIService, error) { + require.Equal(t, bundle, apiService.Spec.CABundle) + return apiService, nil + }), + ) + + i := newInstaller(t, mockOpClient, false) + require.NoError(t, i.installDeployments([]v1alpha1.StrategyDeploymentSpec{{Name: "test", Spec: depSpec}})) + }) +} + +// stubDeploymentNamespaceLister implements the client-go apps/v1 +// DeploymentNamespaceLister interface for a fixed set of deployments. +type stubDeploymentNamespaceLister struct { + deployments map[string]*appsv1.Deployment +} + +func (s stubDeploymentNamespaceLister) List(labels.Selector) ([]*appsv1.Deployment, error) { + return nil, nil +} + +func (s stubDeploymentNamespaceLister) Get(name string) (*appsv1.Deployment, error) { + deployment, ok := s.deployments[name] + if !ok { + return nil, errors.NewNotFound(schema.GroupResource{Group: "apps", Resource: "deployments"}, name) + } + return deployment, nil +} + +// stubDeploymentLister implements the client-go apps/v1 DeploymentLister +// interface for a fixed set of deployments. +type stubDeploymentLister struct { + stubDeploymentNamespaceLister +} + +func (s stubDeploymentLister) Deployments(string) appslisters.DeploymentNamespaceLister { + return s.stubDeploymentNamespaceLister +} + +func TestFinalizeCATransition(t *testing.T) { + namespace := "test-namespace" + owner := ownerutil.Owner(&v1alpha1.ClusterServiceVersion{ + TypeMeta: metav1.TypeMeta{ + Kind: v1alpha1.ClusterServiceVersionKind, + APIVersion: v1alpha1.ClusterServiceVersionAPIVersion, + }, + ObjectMeta: metav1.ObjectMeta{ + Name: "owner", + Namespace: namespace, + UID: "123-uid", + }, + }) + + notAfter := time.Now().Add(730 * 24 * time.Hour) + currentCA := keyPair(t, notAfter) + currentCAPEM, _, err := currentCA.ToPEM() + require.NoError(t, err) + currentCAHash := certs.PEMSHA256(currentCAPEM) + + previousCA := keyPairWithCurve(t, elliptic.P256(), notAfter) + previousCAPEM, _, err := previousCA.ToPEM() + require.NoError(t, err) + + currentPair, err := certs.CreateSignedServingPair(notAfter, Organization, currentCA, HostnamesForService(ServiceName("test"), namespace)) + require.NoError(t, err) + currentCertPEM, currentPrivPEM, err := currentPair.ToPEM() + require.NoError(t, err) + + existingAPIService := &apiregistrationv1.APIService{ + ObjectMeta: metav1.ObjectMeta{ + Name: "v1.g1", + Namespace: namespace, + Labels: map[string]string{ + ownerutil.OwnerKind: v1alpha1.ClusterServiceVersionKind, + ownerutil.OwnerKey: owner.GetName(), + ownerutil.OwnerNamespaceKey: namespace, + }, + }, + } + + deploymentAnnotations := func(caHash string) map[string]string { + return map[string]string{OLMCAHashAnnotationKey: caHash} + } + + readyDeployment := func(caHash string) *appsv1.Deployment { + replicas := int32(1) + deployment := &appsv1.Deployment{ + ObjectMeta: metav1.ObjectMeta{ + Name: "test", + Namespace: namespace, + }, + Spec: appsv1.DeploymentSpec{ + Replicas: &replicas, + }, + Status: appsv1.DeploymentStatus{ + ObservedGeneration: 1, + Replicas: 1, + UpdatedReplicas: 1, + AvailableReplicas: 1, + Conditions: []appsv1.DeploymentCondition{{ + Type: appsv1.DeploymentAvailable, + Status: corev1.ConditionTrue, + }}, + }, + } + deployment.Spec.Template.SetAnnotations(deploymentAnnotations(caHash)) + return deployment + } + + newFakeListerForFinalize := func(t *testing.T, secret *corev1.Secret, deployments map[string]*appsv1.Deployment) *operatorlisterfakes.FakeOperatorLister { + t.Helper() + + fakeLister := &operatorlisterfakes.FakeOperatorLister{} + + fakeSecretLister := &listerfakes.FakeSecretLister{} + fakeCoreV1Lister := &operatorlisterfakes.FakeCoreV1Lister{} + fakeCoreV1Lister.SecretListerReturns(fakeSecretLister) + fakeSecretNamespacedLister := &listerfakes.FakeSecretNamespaceLister{} + fakeSecretLister.SecretsReturns(fakeSecretNamespacedLister) + fakeSecretNamespacedLister.GetReturns(secret, nil) + fakeLister.CoreV1Returns(fakeCoreV1Lister) + + fakeAppsV1Lister := &operatorlisterfakes.FakeAppsV1Lister{} + fakeAppsV1Lister.DeploymentListerReturns(stubDeploymentLister{stubDeploymentNamespaceLister{deployments: deployments}}) + fakeLister.AppsV1Returns(fakeAppsV1Lister) + + fakeAPIRegistrationV1Lister := &operatorlisterfakes.FakeAPIRegistrationV1Lister{} + fakeAPIRegistrationV1Lister.APIServiceListerReturns(stubAPIServiceLister{apiService: existingAPIService}) + fakeLister.APIRegistrationV1Returns(fakeAPIRegistrationV1Lister) + + csvNotFound := errors.NewNotFound(schema.GroupResource{Group: "operators.coreos.com", Resource: "clusterserviceversions"}, "owner") + fakeCSVLister := &operatorlisterfakes.FakeClusterServiceVersionLister{} + fakeCSVNamespaceLister := &operatorlisterfakes.FakeClusterServiceVersionNamespaceLister{} + fakeCSVNamespaceLister.GetReturns(nil, csvNotFound) + fakeCSVLister.ClusterServiceVersionsReturns(fakeCSVNamespaceLister) + fakeOperatorsV1alpha1Lister := &operatorlisterfakes.FakeOperatorsV1alpha1Lister{} + fakeOperatorsV1alpha1Lister.ClusterServiceVersionListerReturns(fakeCSVLister) + fakeLister.OperatorsV1alpha1Returns(fakeOperatorsV1alpha1Lister) + + return fakeLister + } + + newFinalizerInstaller := func(mockOpClient *operatorclientmocks.MockClientInterface, fakeLister *operatorlisterfakes.FakeOperatorLister) *StrategyDeploymentInstaller { + client := wrappers.NewInstallStrategyDeploymentClient(mockOpClient, fakeLister, namespace) + return &StrategyDeploymentInstaller{ + strategyClient: client, + owner: owner, + apiServiceDescriptions: []certResource{ + &apiServiceDescriptionsWithCAPEM{ + apiServiceDescription: v1alpha1.APIServiceDescription{ + Name: "v1.g1", + Group: "g1", + Version: "v1", + DeploymentName: "test", + ContainerPort: 443, + }, + }, + }, + webhookDescriptions: []certResource{}, + } + } + + strategy := &v1alpha1.StrategyDetailsDeployment{ + DeploymentSpecs: []v1alpha1.StrategyDeploymentSpec{ + { + Name: "test", + Spec: appsv1.DeploymentSpec{ + Selector: selector(t, "test=label"), + Template: corev1.PodTemplateSpec{ + ObjectMeta: metav1.ObjectMeta{ + Labels: map[string]string{"app": "test"}, + }, + Spec: corev1.PodSpec{ + ServiceAccountName: "test-sa", + Containers: []corev1.Container{ + {Name: "test-c1", Image: "docker.io/nginx:1.7.9"}, + }, + }, + }, + }, + }, + }, + } + + transitionSecret := func() *corev1.Secret { + return &corev1.Secret{ + ObjectMeta: metav1.ObjectMeta{ + Name: "test-service-cert", + Namespace: namespace, + Annotations: map[string]string{OLMCAHashAnnotationKey: currentCAHash}, + }, + Data: map[string][]byte{ + OLMCAPEMKey: currentCAPEM, + OLMPreviousCAPEMKey: previousCAPEM, + "tls.crt": currentCertPEM, + "tls.key": currentPrivPEM, + }, + } + } + + t.Run("NoTransitionInFlight", func(t *testing.T) { + ctrl := gomock.NewController(t) + defer ctrl.Finish() + + secret := transitionSecret() + delete(secret.Data, OLMPreviousCAPEMKey) + fakeLister := newFakeListerForFinalize(t, secret, map[string]*appsv1.Deployment{}) + + finalized, err := newFinalizerInstaller(operatorclientmocks.NewMockClientInterface(ctrl), fakeLister).FinalizeCATransition(strategy) + require.NoError(t, err) + require.False(t, finalized) + }) + + t.Run("WaitsForDeploymentRollout", func(t *testing.T) { + ctrl := gomock.NewController(t) + defer ctrl.Finish() + + deployment := readyDeployment(currentCAHash) + deployment.Status.UpdatedReplicas = 0 + fakeLister := newFakeListerForFinalize(t, transitionSecret(), map[string]*appsv1.Deployment{"test": deployment}) + + finalized, err := newFinalizerInstaller(operatorclientmocks.NewMockClientInterface(ctrl), fakeLister).FinalizeCATransition(strategy) + require.NoError(t, err) + require.False(t, finalized) + }) + + t.Run("WaitsForDeploymentCAHash", func(t *testing.T) { + ctrl := gomock.NewController(t) + defer ctrl.Finish() + + deployment := readyDeployment(certs.PEMSHA256(previousCAPEM)) + fakeLister := newFakeListerForFinalize(t, transitionSecret(), map[string]*appsv1.Deployment{"test": deployment}) + + finalized, err := newFinalizerInstaller(operatorclientmocks.NewMockClientInterface(ctrl), fakeLister).FinalizeCATransition(strategy) + require.NoError(t, err) + require.False(t, finalized) + }) + + t.Run("FinalizesTransition", func(t *testing.T) { + ctrl := gomock.NewController(t) + defer ctrl.Finish() + + mockOpClient := operatorclientmocks.NewMockClientInterface(ctrl) + + notFound := func(resource, name string) error { + return errors.NewNotFound(schema.GroupResource{Group: "", Resource: resource}, name) + } + // Lookups for resources created by older OLM versions; none exist. + mockOpClient.EXPECT().GetService(namespace, "v1-g1").Return(nil, notFound("services", "v1-g1")) + mockOpClient.EXPECT().GetSecret(namespace, "v1.g1-cert").Return(nil, notFound("secrets", "v1.g1-cert")) + mockOpClient.EXPECT().GetRole(namespace, "v1.g1-cert").Return(nil, notFound("roles", "v1.g1-cert")) + mockOpClient.EXPECT().GetRoleBinding(namespace, "v1.g1-cert").Return(nil, notFound("rolebindings", "v1.g1-cert")) + mockOpClient.EXPECT().GetClusterRoleBinding("v1.g1-system:auth-delegator").Return(nil, notFound("clusterrolebindings", "v1.g1-system:auth-delegator")) + mockOpClient.EXPECT().GetRoleBinding(KubeSystem, "v1.g1-auth-reader").Return(nil, notFound("rolebindings", "v1.g1-auth-reader")) + + // The APIService CABundle is rewritten with only the current CA. + mockOpClient.EXPECT().UpdateAPIService(gomock.Any()).DoAndReturn(func(apiService *apiregistrationv1.APIService) (*apiregistrationv1.APIService, error) { + require.Equal(t, currentCAPEM, apiService.Spec.CABundle) + return apiService, nil + }) + + // The transition state is cleared from the secret. + expectedSecret := transitionSecret() + delete(expectedSecret.Data, OLMPreviousCAPEMKey) + mockOpClient.EXPECT().UpdateSecret(expectedSecret).Return(expectedSecret, nil) + + fakeLister := newFakeListerForFinalize(t, transitionSecret(), map[string]*appsv1.Deployment{"test": readyDeployment(currentCAHash)}) + + finalized, err := newFinalizerInstaller(mockOpClient, fakeLister).FinalizeCATransition(strategy) + require.NoError(t, err) + require.True(t, finalized) + }) +} diff --git a/pkg/controller/install/deployment.go b/pkg/controller/install/deployment.go index 714badb2ea..636abb5877 100644 --- a/pkg/controller/install/deployment.go +++ b/pkg/controller/install/deployment.go @@ -30,6 +30,13 @@ type StrategyDeploymentInstaller struct { webhookDescriptions []certResource certificateExpirationTime time.Time certificatesRotated bool + // caTransition tracks whether a CA trust transition is in flight for any + // of the cert Secrets managed by this installer, either started or + // observed during this install. While set, cert resources (webhook + // configurations, CRD conversions and APIServices) are updated before the + // deployments, so that the dual-CA bundles are trusted by the API server + // before pods roll onto certs signed by the current CA. + caTransition bool } var _ Strategy = &v1alpha1.StrategyDetailsDeployment{} @@ -97,12 +104,24 @@ func (i *StrategyDeploymentInstaller) installDeployments(deps []v1alpha1.Strateg return err } - if _, err := i.strategyClient.CreateOrUpdateDeployment(deployment); err != nil { - return err - } - - if err := i.createOrUpdateCertResourcesForDeployment(); err != nil { - return err + if i.caTransition { + // A CA trust transition is in flight: the dual-CA CABundles must + // be written to the webhook configurations, CRD conversions and + // APIServices before the deployment update rolls pods onto certs + // signed by the current CA. + if err := i.createOrUpdateCertResourcesForDeployment(); err != nil { + return err + } + if _, err := i.strategyClient.CreateOrUpdateDeployment(deployment); err != nil { + return err + } + } else { + if _, err := i.strategyClient.CreateOrUpdateDeployment(deployment); err != nil { + return err + } + if err := i.createOrUpdateCertResourcesForDeployment(); err != nil { + return err + } } } return nil diff --git a/pkg/controller/install/resolver.go b/pkg/controller/install/resolver.go index 3e762fefe4..afe932db24 100644 --- a/pkg/controller/install/resolver.go +++ b/pkg/controller/install/resolver.go @@ -26,6 +26,15 @@ type StrategyInstaller interface { CertsRotated() bool } +// CATransitionFinalizer is implemented by StrategyInstallers that can finalize +// an in-flight CA trust transition: removing the previous CA from the +// CABundles of the generated cert resources once the rollout onto the current +// CA has completed. It is an optional capability, checked for with a type +// assertion, so that alternative installers are not required to implement it. +type CATransitionFinalizer interface { + FinalizeCATransition(strategy Strategy) (bool, error) +} + type StrategyResolverInterface interface { UnmarshalStrategy(s v1alpha1.NamedInstallStrategy) (strategy Strategy, err error) InstallerForStrategy(strategyName string, opClient operatorclient.ClientInterface, opLister operatorlister.OperatorLister, owner ownerutil.Owner, annotations map[string]string, apiServiceDescriptions []v1alpha1.APIServiceDescription, webhookDescriptions []v1alpha1.WebhookDescription, previousStrategy Strategy) StrategyInstaller diff --git a/pkg/controller/operators/olm/apiservices.go b/pkg/controller/operators/olm/apiservices.go index f0deae1706..21a873e3e6 100644 --- a/pkg/controller/operators/olm/apiservices.go +++ b/pkg/controller/operators/olm/apiservices.go @@ -122,8 +122,10 @@ func (a *Operator) checkAPIServiceResources(csv *v1alpha1.ClusterServiceVersion, continue } - // Check if CA hash matches expected - caHash := hashFunc(caBundle) + // Check if CA hash matches expected. The bundle may contain a previous + // CA while a trust transition is in flight; only the current CA (always + // written first) is hashed. + caHash := hashFunc(certs.CurrentCAPEM(caBundle)) if hash, ok := secret.GetAnnotations()[install.OLMCAHashAnnotationKey]; !ok || hash != caHash { logger.WithField("secret", secretName).Warnf("secret CA cert hash does not match expected") errs = append(errs, fmt.Errorf("secret %s CA cert hash does not match expected", secretName)) @@ -456,7 +458,9 @@ func (a *Operator) updateDeploymentSpecsWithAPIServiceData(csv *v1alpha1.Cluster if err != nil { return nil, fmt.Errorf("could not retrieve caBundle for owned APIServices %s: %v", fmt.Sprintf("%s.%s", desc.Version, desc.Group), err) } - caHash := certs.PEMSHA256(caBundle) + // The bundle may contain a previous CA while a trust transition is in + // flight; only the current CA (always written first) is hashed. + caHash := certs.PEMSHA256(certs.CurrentCAPEM(caBundle)) depSpec, ok := depSpecs[desc.DeploymentName] if !ok { @@ -483,7 +487,9 @@ func (a *Operator) updateDeploymentSpecsWithAPIServiceData(csv *v1alpha1.Cluster if err != nil { return nil, fmt.Errorf("could not retrieve caBundle for WebhookDescription %s: %v", desc.GenerateName, err) } - caHash := certs.PEMSHA256(caBundle) + // The bundle may contain a previous CA while a trust transition is in + // flight; only the current CA (always written first) is hashed. + caHash := certs.PEMSHA256(certs.CurrentCAPEM(caBundle)) depSpec, ok := depSpecs[desc.DeploymentName] if !ok { diff --git a/pkg/controller/operators/olm/operator.go b/pkg/controller/operators/olm/operator.go index f7e68724c2..b6e61a0803 100644 --- a/pkg/controller/operators/olm/operator.go +++ b/pkg/controller/operators/olm/operator.go @@ -2462,6 +2462,25 @@ func (a *Operator) transitionCSVState(in v1alpha1.ClusterServiceVersion) (out *v return } + // Finalize an in-flight CA trust transition (e.g. from P-256 to P-384 + // key material) now that every deployment has rolled out onto the + // current CA: drop the previous CA from the CABundles of the generated + // cert resources and clear the transition state. This does not change + // the CA hash, so no additional rollout is triggered. + if finalizer, ok := installer.(install.CATransitionFinalizer); ok { + finalized, err := finalizer.FinalizeCATransition(strategy) + if err != nil { + logger.WithError(err).Info("CA transition finalization") + syncError = err + return + } + if finalized { + if err := a.csvQueueSet.Requeue(out.GetNamespace(), out.GetName()); err != nil { + a.logger.Warn(err.Error()) + } + } + } + // Ensure cluster roles exist for using provided apis if err := a.ensureClusterRolesForCSV(out); err != nil { logger.WithError(err).Info("couldn't ensure clusterroles for provided api types") diff --git a/pkg/controller/operators/olm/operator_test.go b/pkg/controller/operators/olm/operator_test.go index 595f1cf3ca..53f8365ab4 100644 --- a/pkg/controller/operators/olm/operator_test.go +++ b/pkg/controller/operators/olm/operator_test.go @@ -606,6 +606,46 @@ func signedServingPair(notAfter time.Time, ca *certs.KeyPair, hosts []string) *c return servingPair } +// signedServingPairWithCurve generates a serving pair on the given curve, for +// building fixtures that mimic the key material generated by older versions +// of OLM (which used P-256). +func signedServingPairWithCurve(curve elliptic.Curve, notAfter time.Time, ca *certs.KeyPair, hosts []string) *certs.KeyPair { + serial, err := rand.Int(rand.Reader, new(big.Int).SetInt64(math.MaxInt64)) + if err != nil { + panic(err) + } + + certDetails := &x509.Certificate{ + SerialNumber: serial, + Subject: pkix.Name{ + CommonName: hosts[0], + Organization: []string{install.Organization}, + }, + NotBefore: time.Now().Add(-time.Hour), + NotAfter: notAfter, + ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}, + BasicConstraintsValid: true, + DNSNames: hosts, + } + + privateKey, err := ecdsa.GenerateKey(curve, rand.Reader) + if err != nil { + panic(err) + } + + certRaw, err := x509.CreateCertificate(rand.Reader, certDetails, ca.Cert, &privateKey.PublicKey, ca.Priv) + if err != nil { + panic(err) + } + + cert, err := x509.ParseCertificate(certRaw) + if err != nil { + panic(err) + } + + return &certs.KeyPair{Cert: cert, Priv: privateKey} +} + func withAnnotations(obj runtime.Object, annotations map[string]string) runtime.Object { meta, ok := obj.(metav1.Object) if !ok { @@ -920,6 +960,13 @@ func crd(name, version, group string) *apiextensionsv1.CustomResourceDefinition } func generateCA(notAfter time.Time, organization string) (*certs.KeyPair, error) { + return generateCAWithCurve(elliptic.P384(), notAfter, organization) +} + +// generateCAWithCurve generates a self-signed CA on the given curve, for +// building fixtures that mimic the key material generated by older versions +// of OLM (which used P-256). +func generateCAWithCurve(curve elliptic.Curve, notAfter time.Time, organization string) (*certs.KeyPair, error) { notBefore := time.Now() serial, err := rand.Int(rand.Reader, new(big.Int).SetInt64(math.MaxInt64)) @@ -940,7 +987,7 @@ func generateCA(notAfter time.Time, organization string) (*certs.KeyPair, error) BasicConstraintsValid: true, } - privateKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + privateKey, err := ecdsa.GenerateKey(curve, rand.Reader) if err != nil { return nil, err } @@ -6301,6 +6348,290 @@ func TestCARotation(t *testing.T) { } } +// TestCATransition walks a CSV with an owned APIService through a full CA +// trust transition: an install with key material as generated by an older +// version of OLM (P-256) is rotated onto fresh P-384 material with the +// previous CA kept in a dual-CA CABundle until the rollout completes, after +// which the previous CA is dropped and the transition state cleared. +func TestCATransition(t *testing.T) { + logrus.SetLevel(logrus.DebugLevel) + namespace := "ns" + + defaultOperatorGroup := &operatorsv1.OperatorGroup{ + TypeMeta: metav1.TypeMeta{ + Kind: "OperatorGroup", + APIVersion: operatorsv1.SchemeGroupVersion.String(), + }, + ObjectMeta: metav1.ObjectMeta{ + Name: "default", + Namespace: namespace, + }, + Spec: operatorsv1.OperatorGroupSpec{}, + Status: operatorsv1.OperatorGroupStatus{ + Namespaces: []string{namespace}, + }, + } + + defaultTemplateAnnotations := map[string]string{ + operatorsv1.OperatorGroupTargetsAnnotationKey: namespace, + operatorsv1.OperatorGroupNamespaceAnnotationKey: namespace, + operatorsv1.OperatorGroupAnnotationKey: defaultOperatorGroup.GetName(), + } + + csv1 := withUID(withAPIServices(csvWithAnnotations(csv("csv1", + namespace, + "0.0.0", + "", + installStrategy("a1", nil, nil), + []*apiextensionsv1.CustomResourceDefinition{crd("c1", "v1", "g1")}, + []*apiextensionsv1.CustomResourceDefinition{}, + v1alpha1.CSVPhaseNone, + ), defaultTemplateAnnotations), apis("a1.v1.a1Kind"), nil), types.UID("csv-uid")).(*v1alpha1.ClusterServiceVersion) + + // The APIService is seeded so that its GVK is present in api discovery and + // so that its availability condition can be simulated; OLM adopts and + // updates it during install. + seededAPIService := apiService("a1", "v1", "a1-service", namespace, "a1", nil, apiregistrationv1.ConditionTrue, ownerLabelFromCSV("csv1", namespace)) + + ctx, cancel := context.WithCancel(context.TODO()) + defer cancel() + op, err := NewFakeOperator( + ctx, + withNamespaces(namespace, "kube-system"), + withClientObjs( + addAnnotation(defaultOperatorGroup, operatorsv1.OperatorGroupProvidedAPIsAnnotationKey, "c1.v1.g1,a1Kind.v1.a1"), + csv1, + ), + withK8sObjs( + // The rolebinding, service, and clusterRoleBinding have been added here as a workaround to fake client not supporting SSA + roleBinding("a1-service-auth-reader", "kube-system", "extension-apiserver-authentication-reader", "sa", namespace), + service("a1-service", namespace, "a1", 80, metav1.OwnerReference{Kind: v1alpha1.ClusterServiceVersionKind, UID: "csv-uid"}), + clusterRoleBinding("a1-service-system:auth-delegator", "system:auth-delegator", "sa", namespace), + serviceAccount("sa", namespace), + ), + withExtObjs(crd("c1", "v1", "g1")), + withRegObjs(seededAPIService), + withPartialMetadata( + &metav1.PartialObjectMetadata{ + TypeMeta: metav1.TypeMeta{ + Kind: "ClusterServiceVersion", + APIVersion: v1alpha1.SchemeGroupVersion.String(), + }, + ObjectMeta: csv1.ObjectMeta, + }, + &metav1.PartialObjectMetadata{ + TypeMeta: metav1.TypeMeta{ + Kind: "CustomResourceDefinition", + APIVersion: apiextensionsv1.SchemeGroupVersion.String(), + }, + ObjectMeta: crd("c1", "v1", "g1").ObjectMeta, + }, + ), + withOperatorNamespace(namespace), + ) + require.NoError(t, err) + + // simulateAvailability marks the CSV's deployment as rolled out and its + // owned APIService as available, as the respective controllers would in a + // real cluster. + simulateAvailability := func() { + dep, err := op.opClient.GetDeployment(namespace, "a1") + if err == nil { + dep.Status = appsv1.DeploymentStatus{ + ObservedGeneration: dep.GetGeneration(), + Replicas: 1, + UpdatedReplicas: 1, + AvailableReplicas: 1, + Conditions: []appsv1.DeploymentCondition{{ + Type: appsv1.DeploymentAvailable, + Status: corev1.ConditionTrue, + }}, + } + _, err = op.opClient.KubernetesInterface().AppsV1().Deployments(namespace).UpdateStatus(ctx, dep, metav1.UpdateOptions{}) + require.NoError(t, err) + } + + apiService, err := op.opClient.GetAPIService("v1.a1") + if err == nil && !install.IsAPIServiceAvailable(apiService) { + apiService.Status.Conditions = []apiregistrationv1.APIServiceCondition{{ + Type: apiregistrationv1.Available, + Status: apiregistrationv1.ConditionTrue, + }} + _, err = op.opClient.ApiregistrationV1Interface().ApiregistrationV1().APIServices().UpdateStatus(ctx, apiService, metav1.UpdateOptions{}) + require.NoError(t, err) + } + } + + // syncCSVUntil repeatedly syncs the CSV (simulating availability between + // syncs) until the given condition holds for the CSV as stored in the + // cluster. + syncCSVUntil := func(cond func(csv *v1alpha1.ClusterServiceVersion) bool) *v1alpha1.ClusterServiceVersion { + var last *v1alpha1.ClusterServiceVersion + var lastSyncErr error + pollErr := wait.PollUntilContextTimeout(ctx, 10*time.Millisecond, 30*time.Second, true, func(ctx context.Context) (bool, error) { + simulateAvailability() + csv, err := op.client.OperatorsV1alpha1().ClusterServiceVersions(namespace).Get(ctx, "csv1", metav1.GetOptions{}) + if err != nil { + return false, err + } + last = csv + if cond(csv) { + return true, nil + } + if err := op.syncClusterServiceVersion(csv); err != nil { + // Reconcile errors are expected while the CSV settles; keep + // trying and surface the last error on timeout. + lastSyncErr = err + } + return false, nil + }) + require.NoError(t, pollErr, "timed out waiting for CSV condition, last phase: %s, last sync error: %v", last.Status.Phase, lastSyncErr) + return last + } + + getSecret := func() *corev1.Secret { + secret, err := op.opClient.GetSecret(namespace, "a1-service-cert") + require.NoError(t, err) + return secret + } + + getAPIService := func() *apiregistrationv1.APIService { + apiService, err := op.opClient.GetAPIService("v1.a1") + require.NoError(t, err) + return apiService + } + + getDeployment := func() *appsv1.Deployment { + dep, err := op.opClient.GetDeployment(namespace, "a1") + require.NoError(t, err) + return dep + } + + // Install the CSV: OLM generates fresh P-384 key material and the CSV + // settles in the Succeeded phase. + syncCSVUntil(func(csv *v1alpha1.ClusterServiceVersion) bool { + return csv.Status.Phase == v1alpha1.CSVPhaseSucceeded + }) + + // Simulate the cluster state as an older version of OLM (which generated + // P-256 key material) would have left it: a P-256 CA and serving pair in + // the cert Secret, a single P-256 CA in the APIService CABundle and the + // P-256 CA hash on the deployment's pod template. The deployment's + // spec-hash label is left as-is: the cert rotation check in the Succeeded + // phase reconcile runs before any deployment spec comparison. + expiration := install.CalculateCertExpiration(time.Now()) + p256CA, err := generateCAWithCurve(elliptic.P256(), expiration, install.Organization) + require.NoError(t, err) + p256CAPEM, _, err := p256CA.ToPEM() + require.NoError(t, err) + p256CAHash := certs.PEMSHA256(p256CAPEM) + p256Pair := signedServingPairWithCurve(elliptic.P256(), expiration, p256CA, []string{"a1-service.ns", "a1-service.ns.svc"}) + p256CertPEM, p256PrivPEM, err := p256Pair.ToPEM() + require.NoError(t, err) + + secret := getSecret() + secret.Data[install.OLMCAPEMKey] = p256CAPEM + secret.Data["tls.crt"] = p256CertPEM + secret.Data["tls.key"] = p256PrivPEM + secret.SetAnnotations(map[string]string{install.OLMCAHashAnnotationKey: p256CAHash}) + _, err = op.opClient.UpdateSecret(secret) + require.NoError(t, err) + + apiService := getAPIService() + apiService.Spec.CABundle = p256CAPEM + _, err = op.opClient.UpdateAPIService(apiService) + require.NoError(t, err) + + dep := getDeployment() + dep.Spec.Template.Annotations[install.OLMCAHashAnnotationKey] = p256CAHash + _, err = op.opClient.KubernetesInterface().AppsV1().Deployments(namespace).Update(ctx, dep, metav1.UpdateOptions{}) + require.NoError(t, err) + + // Wait for the lister cache to reflect the simulated state. + require.NoError(t, wait.PollUntilContextTimeout(ctx, 10*time.Millisecond, 30*time.Second, true, func(ctx context.Context) (bool, error) { + cachedSecret, err := op.lister.CoreV1().SecretLister().Secrets(namespace).Get("a1-service-cert") + if err != nil { + return false, err + } + if hash, ok := cachedSecret.GetAnnotations()[install.OLMCAHashAnnotationKey]; !ok || hash != p256CAHash { + return false, nil + } + cachedAPIService, err := op.lister.APIRegistrationV1().APIServiceLister().Get("v1.a1") + if err != nil { + return false, err + } + if !reflect.DeepEqual(cachedAPIService.Spec.CABundle, p256CAPEM) { + return false, nil + } + cachedDep, err := op.lister.AppsV1().DeploymentLister().Deployments(namespace).Get("a1") + if err != nil { + return false, err + } + hash, ok := cachedDep.Spec.Template.GetAnnotations()[install.OLMCAHashAnnotationKey] + return ok && hash == p256CAHash, nil + })) + + // Rotate onto fresh P-384 key material: the CSV notices the P-256 certs, + // re-enters the install phases, and settles in Succeeded with a dual-CA + // CABundle while the transition is in flight. + syncCSVUntil(func(csv *v1alpha1.ClusterServiceVersion) bool { + return csv.Status.Phase == v1alpha1.CSVPhaseSucceeded && len(getSecret().Data[install.OLMPreviousCAPEMKey]) > 0 + }) + + // While the transition is in flight, the previous CA is kept alongside the + // current CA... + secret = getSecret() + currentCAPEM := secret.Data[install.OLMCAPEMKey] + require.Equal(t, p256CAPEM, secret.Data[install.OLMPreviousCAPEMKey]) + // ...but the olmcahash annotation hashes only the current CA, so dropping + // the previous CA will not trigger an additional rollout. + require.Equal(t, certs.PEMSHA256(currentCAPEM), secret.GetAnnotations()[install.OLMCAHashAnnotationKey]) + + apiService = getAPIService() + expectedBundle := append(append([]byte{}, currentCAPEM...), p256CAPEM...) + require.Equal(t, expectedBundle, apiService.Spec.CABundle) + + dep = getDeployment() + require.Equal(t, certs.PEMSHA256(currentCAPEM), dep.Spec.Template.Annotations[install.OLMCAHashAnnotationKey]) + depResourceVersion := dep.GetResourceVersion() + + // Once the CSV is synced again in the Succeeded phase, the transition is + // finalized: the previous CA is dropped from the CABundle and the + // transition state is cleared from the Secret. + require.NoError(t, wait.PollUntilContextTimeout(ctx, 10*time.Millisecond, 30*time.Second, true, func(ctx context.Context) (bool, error) { + csv, err := op.client.OperatorsV1alpha1().ClusterServiceVersions(namespace).Get(ctx, "csv1", metav1.GetOptions{}) + if err != nil { + return false, err + } + if csv.Status.Phase != v1alpha1.CSVPhaseSucceeded { + require.Failf(t, "CSV left the Succeeded phase while the CA transition was being finalized", + "phase: %s, reason: %s, conditions: %v", csv.Status.Phase, csv.Status.Reason, csv.Status.Conditions) + } + if err := op.syncClusterServiceVersion(csv); err != nil { + return false, err + } + return reflect.DeepEqual(getAPIService().Spec.CABundle, currentCAPEM), nil + })) + + apiService = getAPIService() + require.Equal(t, currentCAPEM, apiService.Spec.CABundle) + + secret = getSecret() + require.NotContains(t, secret.Data, install.OLMPreviousCAPEMKey) + require.Equal(t, currentCAPEM, secret.Data[install.OLMCAPEMKey]) + require.Equal(t, certs.PEMSHA256(currentCAPEM), secret.GetAnnotations()[install.OLMCAHashAnnotationKey]) + + // Removing the previous CA did not roll the deployment again. + dep = getDeployment() + require.Equal(t, depResourceVersion, dep.GetResourceVersion()) + require.Equal(t, certs.PEMSHA256(currentCAPEM), dep.Spec.Template.Annotations[install.OLMCAHashAnnotationKey]) + + // And the CSV remained Succeeded throughout. + csv, err := op.client.OperatorsV1alpha1().ClusterServiceVersions(namespace).Get(ctx, "csv1", metav1.GetOptions{}) + require.NoError(t, err) + require.Equal(t, v1alpha1.CSVPhaseSucceeded, csv.Status.Phase) +} + func GetServiceCertificaValidityPeriod(serviceSecret *corev1.Secret) (start *time.Time, end *time.Time, err error) { // Extract certificate root := x509.NewCertPool() diff --git a/test/e2e/webhook_e2e_test.go b/test/e2e/webhook_e2e_test.go index 5cb3b01c8f..bc19221d45 100644 --- a/test/e2e/webhook_e2e_test.go +++ b/test/e2e/webhook_e2e_test.go @@ -1,6 +1,7 @@ package e2e import ( + "bytes" "context" "crypto/ecdsa" "crypto/elliptic" @@ -520,6 +521,129 @@ var _ = Describe("CSVs with a Webhook", Label("Webhooks"), func() { newWebhookCABundle := actualWebhook.Webhooks[0].ClientConfig.CABundle Expect(newWebhookCABundle).ShouldNot(Equal(oldWebhookCABundle)) }) + + It("Rotates P-256 key material to P-384 with a zero-downtime trust transition", func() { + sideEffect := admissionregistrationv1.SideEffectClassNone + webhook := operatorsv1alpha1.WebhookDescription{ + GenerateName: webhookName, + Type: operatorsv1alpha1.ValidatingAdmissionWebhook, + DeploymentName: genName("webhook-dep-"), + ContainerPort: 443, + AdmissionReviewVersions: []string{"v1beta1", "v1"}, + SideEffects: &sideEffect, + } + + csv := createCSVWithWebhook(generatedNamespace.GetName(), webhook) + + var err error + cleanupCSV, err = createCSV(c, crc, csv, generatedNamespace.GetName(), false, false) + Expect(err).Should(BeNil()) + + _, err = fetchCSV(crc, generatedNamespace.GetName(), csv.Name, csvSucceededChecker) + Expect(err).Should(BeNil()) + + By(`Get the deployment`) + dep, err := c.KubernetesInterface().AppsV1().Deployments(generatedNamespace.GetName()).Get(context.TODO(), csv.Spec.WebhookDefinitions[0].DeploymentName, metav1.GetOptions{}) + Expect(err).Should(BeNil()) + + // Store the ca hash annotation + oldCAAnnotation, ok := dep.Spec.Template.GetAnnotations()[install.OLMCAHashAnnotationKey] + Expect(ok).Should(BeTrue()) + + caSecret, err := c.KubernetesInterface().CoreV1().Secrets(generatedNamespace.GetName()).Get(context.TODO(), install.SecretName(install.ServiceName(dep.Name)), metav1.GetOptions{}) + Expect(err).Should(BeNil()) + + By(`Patch the Secret with valid P-256 key material, as an older version of OLM would have generated`) + p256CAPEM, p256CertPEM, p256PrivPEM := generateCertsOnCurve(elliptic.P256(), install.HostnamesForService(install.ServiceName(dep.Name), generatedNamespace.GetName()), time.Now().Add(-time.Hour), time.Now().Add(10*365*24*time.Hour)) + Eventually(Apply(caSecret, func(caSecret *corev1.Secret) error { + caSecret.Data[install.OLMCAPEMKey] = p256CAPEM + caSecret.Data["tls.crt"] = p256CertPEM + caSecret.Data["tls.key"] = p256PrivPEM + return nil + })).Should(Succeed()) + + By(`Wait for OLM to rotate onto fresh P-384 key material while the previous CA remains trusted`) + var currentCAPEM []byte + var newCAAnnotation string + Eventually(func() error { + By(`Should remember the previous CA in the Secret`) + secret, err := c.KubernetesInterface().CoreV1().Secrets(generatedNamespace.GetName()).Get(context.TODO(), caSecret.GetName(), metav1.GetOptions{}) + if err != nil { + return err + } + previousCAPEM, ok := secret.Data[install.OLMPreviousCAPEMKey] + if !ok { + return fmt.Errorf("previous CA not yet stored in Secret %s", secret.GetName()) + } + if !bytes.Equal(previousCAPEM, p256CAPEM) { + return fmt.Errorf("unexpected previous CA stored in Secret %s", secret.GetName()) + } + currentCAPEM = secret.Data[install.OLMCAPEMKey] + + By(`Should serve a dual-CA CABundle in the webhook configuration while the transition is in flight`) + actualWebhook, err := getWebhookWithGenerateName(c, webhook.GenerateName) + if err != nil { + return err + } + if bundle := actualWebhook.Webhooks[0].ClientConfig.CABundle; !bytes.Equal(bundle, append(append([]byte{}, currentCAPEM...), p256CAPEM...)) { + return fmt.Errorf("webhook CABundle is not the expected dual-CA bundle") + } + + By(`Should roll the deployment onto the new CA, hashed without the previous CA`) + rolledDep, err := c.KubernetesInterface().AppsV1().Deployments(generatedNamespace.GetName()).Get(context.TODO(), dep.GetName(), metav1.GetOptions{}) + if err != nil { + return err + } + newCAAnnotation, ok = rolledDep.Spec.Template.GetAnnotations()[install.OLMCAHashAnnotationKey] + if !ok { + return fmt.Errorf("deployment %s has no CA hash annotation", rolledDep.GetName()) + } + if newCAAnnotation == oldCAAnnotation { + return fmt.Errorf("deployment %s not yet rolled onto the new CA", rolledDep.GetName()) + } + if newCAAnnotation != certs.PEMSHA256(currentCAPEM) { + return fmt.Errorf("deployment %s CA hash annotation does not hash the current CA only", rolledDep.GetName()) + } + return nil + }).Should(Succeed()) + + By(`Wait for the transition to be finalized once the rollout has completed`) + Eventually(func() error { + By(`Should drop the previous CA from the Secret`) + secret, err := c.KubernetesInterface().CoreV1().Secrets(generatedNamespace.GetName()).Get(context.TODO(), caSecret.GetName(), metav1.GetOptions{}) + if err != nil { + return err + } + if _, ok := secret.Data[install.OLMPreviousCAPEMKey]; ok { + return fmt.Errorf("previous CA still stored in Secret %s", secret.GetName()) + } + if caPEM := secret.Data[install.OLMCAPEMKey]; !bytes.Equal(caPEM, currentCAPEM) { + return fmt.Errorf("current CA changed in Secret %s", secret.GetName()) + } + if secret.GetAnnotations()[install.OLMCAHashAnnotationKey] != certs.PEMSHA256(currentCAPEM) { + return fmt.Errorf("Secret %s CA hash annotation changed", secret.GetName()) + } + + By(`Should drop the previous CA from the webhook CABundle`) + actualWebhook, err := getWebhookWithGenerateName(c, webhook.GenerateName) + if err != nil { + return err + } + if bundle := actualWebhook.Webhooks[0].ClientConfig.CABundle; !bytes.Equal(bundle, currentCAPEM) { + return fmt.Errorf("webhook CABundle still contains the previous CA") + } + return nil + }).Should(Succeed()) + + By(`Should not roll the deployment again to drop the previous CA`) + rolledDep, err := c.KubernetesInterface().AppsV1().Deployments(generatedNamespace.GetName()).Get(context.TODO(), dep.GetName(), metav1.GetOptions{}) + Expect(err).Should(BeNil()) + Expect(rolledDep.Spec.Template.GetAnnotations()[install.OLMCAHashAnnotationKey]).Should(Equal(newCAAnnotation)) + + By(`Should leave the CSV succeeded`) + _, err = fetchCSV(crc, generatedNamespace.GetName(), csv.Name, csvSucceededChecker) + Expect(err).Should(BeNil()) + }) }) When("Installed in a Global OperatorGroup", func() { var cleanupCSV cleanupFunc @@ -1259,6 +1383,13 @@ func newV1CRD(plural string) apiextensionsv1.CustomResourceDefinition { } func generateExpiredCerts(hosts []string) ([]byte, []byte, []byte) { + return generateCertsOnCurve(elliptic.P256(), hosts, time.Now().Add(-5*time.Minute), time.Now().Add(-5*time.Minute)) +} + +// generateCertsOnCurve generates a CA and a serving pair signed by it on the +// given curve, for mimicking the key material generated by older versions of +// OLM (which used P-256). +func generateCertsOnCurve(curve elliptic.Curve, hosts []string, notBefore, notAfter time.Time) ([]byte, []byte, []byte) { caSerial, err := rand.Int(rand.Reader, new(big.Int).SetInt64(math.MaxInt64)) Expect(err).Should(BeNil()) @@ -1268,14 +1399,14 @@ func generateExpiredCerts(hosts []string) ([]byte, []byte, []byte) { CommonName: fmt.Sprintf("olm-selfsigned-%x", caSerial), Organization: []string{install.Organization}, }, - NotBefore: time.Now().Add(-5 * time.Minute), - NotAfter: time.Now().Add(-5 * time.Minute), + NotBefore: notBefore, + NotAfter: notAfter, IsCA: true, KeyUsage: x509.KeyUsageCertSign, BasicConstraintsValid: true, } - caKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + caKey, err := ecdsa.GenerateKey(curve, rand.Reader) Expect(err).Should(BeNil()) caRaw, err := x509.CreateCertificate(rand.Reader, caDetails, caDetails, &caKey.PublicKey, caKey) @@ -1299,14 +1430,14 @@ func generateExpiredCerts(hosts []string) ([]byte, []byte, []byte) { CommonName: hosts[0], Organization: []string{install.Organization}, }, - NotBefore: time.Now(), - NotAfter: time.Now(), + NotBefore: notBefore, + NotAfter: notAfter, ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}, BasicConstraintsValid: true, DNSNames: hosts, } - privateKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + privateKey, err := ecdsa.GenerateKey(curve, rand.Reader) Expect(err).Should(BeNil()) publicKey := &privateKey.PublicKey