Compare commits

..

46 Commits

Author SHA1 Message Date
Caleb Bron
401fafb7e6 Merge pull request #64 from w13915984028/fix63
fix63 use sleep instead of force scheduling
2022-07-28 13:43:07 -07:00
Jian Wang
bad953b9f0 fix63 use sleep instead of force scheduling 2022-07-27 08:59:22 +02:00
Brad Davidson
8ebd77f8a4 Raise default ExpirationDaysCheck to 90 and extend into cert factory
Most of our products actually renew at 90 days, so make that the default.

Signed-off-by: Brad Davidson <brad.davidson@rancher.com>
2022-07-21 14:08:16 -07:00
Brad Davidson
fdf983a935 Don't merge expired certs over the top of an unexpired cert
Fixes an issue where an expired Kubernetes secret would replace the renewed locally-cached cert after cluster startup.

Signed-off-by: Brad Davidson <brad.davidson@rancher.com>
2022-07-21 14:08:16 -07:00
Flavio Grossi
7b5997cee9 always use CATTLE_NEW_SIGNED_CERT_EXPIRATION_DAYS when generating a certificate 2022-07-20 12:07:31 -07:00
Lucas Ramage
42d72c2ef2 Merge pull request #56 from rancher/fossa
Implement drone-plugin-fossa
2022-07-01 10:58:54 -04:00
Brad Davidson
d2b7e2aaa6 We support IPv6 now, don't skip adding IPv6 address SANs
Signed-off-by: Brad Davidson <brad.davidson@rancher.com>
2022-05-20 12:21:30 -07:00
Brad Davidson
a30741bb53 Send complete certificate chain, not just the leaf cert
Also, print a warning when signing may change the issuer.

Signed-off-by: Brad Davidson <brad.davidson@rancher.com>
2022-05-20 12:21:30 -07:00
Brad Davidson
4df376813d Improve log messages and warn if no cert is available
Signed-off-by: Brad Davidson <brad.davidson@rancher.com>
2022-05-20 12:21:30 -07:00
Brad Davidson
9b92d13bcb Fix initial secret not being written to Kubernetes
Updates to the secret that occurred before the controller was done
syncing were not being written to Kubernetes. Subsequent updates to the
secret would eventually get it written, but Rancher requires that the
cert be written immediately. This was probably an unnecessary
optimization anyway, so back it out in favor of just checking to see if
the secrets controller is available.

Also fixed improper handling of multiple goroutines attempting to create
the Kubernetes secret at the same time; this was also handled eventually
but caused an unnecessary round of extra writes to the secret.

Signed-off-by: Brad Davidson <brad.davidson@rancher.com>
2022-05-20 12:21:30 -07:00
Brad Davidson
b1d65efb6f Move Kubernetes Secrets storage update to goroutine
Fixes issue where apiserver outages can block dynamiclistener from accepting new connections.

Signed-off-by: Brad Davidson <brad.davidson@rancher.com>
2022-05-02 18:48:48 -07:00
Lucas Ramage
5e81b14c1f Implement drone-plugin-fossa 2022-03-31 16:28:22 -04:00
Brian Downs
148d38076d update config to allow for specifying experiation in days (#53) 2021-12-21 15:38:04 -07:00
Brad Davidson
43f9c3ae0a Fix handling of IPv6 addresses and long hostnames
Signed-off-by: Brad Davidson <brad.davidson@rancher.com>
2021-11-23 23:38:49 -08:00
Brad Davidson
284cc004e8 Fix listenAndServe certificate expiration by preloading certs
Signed-off-by: Brad Davidson <brad.davidson@rancher.com>
2021-11-23 23:38:49 -08:00
Kinara Shah
120a37b97a Merge pull request #51 from nickgerace/quick-fix
Add README
2021-11-19 14:29:09 -08:00
Nick Gerace
bbac29e0fa Add README 2021-11-19 13:50:48 -05:00
Kinara Shah
962b635269 Merge pull request #50 from nickgerace/quick-fix
Fix defaultNewSignedCertExpirationDays const
2021-11-19 10:28:49 -08:00
Nick Gerace
f147aa4166 Fix defaultNewSignedCertExpirationDays const
This a quick fix for 2644a6ed16
2021-11-19 12:31:47 -05:00
Kinara Shah
63157c59ce Merge pull request #46 from nickgerace/days
Allow for default expiration days to be loaded from env
2021-11-19 08:59:57 -08:00
Nick Gerace
2644a6ed16 Allow for default expiration days to be loaded from env 2021-11-18 12:38:35 -05:00
Brian Downs
27f4642299 Add ability to force cert regeneration (#43)
* add ability to force cert regeneration
2021-11-15 13:50:26 -07:00
Caleb Bron
cd5d71f2fe Merge pull request #44 from cmurphy/fix-type
Fix net.Conn type assertion
2021-11-04 13:09:48 -07:00
Colleen Murphy
fb66484384 Fix net.Conn type assertion
Don't assert that all connections are wrapped, as they won't be if
the CloseConnOnCertChange setting is false. Only run the assertion
within a conditional for wrapped connections, where it is safe. This
prevents a panic from happening when CloseConnOnCertChange is not used.
2021-10-29 11:03:02 -07:00
Darren Shepherd
6b37dc1212 Merge pull request #42 from cmurphy/fix-close-conn
Skip closing an initializing connection
2021-10-27 08:35:21 -07:00
Colleen Murphy
c7dd355394 Skip closing an initializing connection
Without this change, if a cert is updated (e.g. to add CNs) while the
listener is in the middle of Accept()ing a new connection, the
connection gets dropped, we'll see a message like this in the server
logs:

  http: TLS handshake error from 127.0.0.1:51232: write tcp 127.0.7.1:8443->127.0.0.1:51232: use of closed network connection

and the client (like a browser) won't necessarily reconnect. This change
modifies the GetCertificate routine in the listener's tls.Config to
keep track of the state of the incoming connections and only close
connections that have completed GetCertificate and therefore are
finished with their TLS handshake, so that only old established
connections are closed.
2021-10-25 13:17:24 -07:00
Darren Shepherd
94e22490cf Merge pull request #41 from weihanglo/nil-defer-storage-tls
Merge TLS only if TLS factory is set
2021-08-03 10:23:59 -07:00
Weihang Lo
b45d8a455e Merge TLS only if TLS factory is set
Since `storage.tls` is optional, we should check it existence before
calling its methods.
2021-07-12 18:25:01 +08:00
Darren Shepherd
9865ae859c Don't reset connections on the first load of the certs 2021-06-16 01:00:09 -07:00
Darren Shepherd
db883ae66a Don't reset connections on the first load of the certs 2021-06-16 00:23:14 -07:00
Darren Shepherd
9dfd7df057 Pass context to http server as BaseContext 2021-06-15 22:42:42 -07:00
Darren Shepherd
ff22834bde Avoid panic when secret is nil 2021-06-15 22:42:42 -07:00
Sjoerd Simons
dc7452dbb8 Accept IPv6 address as CN names
Expand the cnRegexp to also accept ipv6 addresses such as:
  * ::1
  * 2a00:1450:400e:80e::
  * 2a00:1450:400e:80e::200e

Fixes: #37

Signed-off-by: Sjoerd Simons <sjoerd@collabora.com>
2021-06-14 11:07:13 -07:00
Dan Ramich
86af265dcd Merge pull request #35 from dramich/panic
Update IsStatic to check for nil annotations
2021-04-26 09:21:45 -06:00
Dan Ramich
f373fc1c7c Update IsStatic to check for nil annotations 2021-04-23 14:56:14 -06:00
Darren Shepherd
e7b1adba70 Update to wrangler v0.8.0 and merge v0.2.x to master 2021-04-12 15:09:30 -07:00
Darren Shepherd
a60200ab9e Merge tag 'v0.2.3' 2021-04-12 15:00:05 -07:00
Darren Shepherd
9b1b7d3132 Add filter helper method 2020-11-09 21:52:17 -07:00
Darren Shepherd
85f32491cb Add dumb hook to set the organization in the client cert 2020-09-10 13:32:14 -07:00
Darren Shepherd
ebebb82b9b Add LoadOrGenClient to handle client cert generation 2020-08-01 23:37:51 -07:00
Darren Shepherd
bafb051656 Merge pull request #27 from ibuildthecloud/master
Fix error masking issue
2020-07-27 22:48:58 -07:00
Darren Shepherd
3b42c52bec Fix error masking issue
Also don't do an extra lookup of TLS secret after update.
2020-07-27 22:48:13 -07:00
Darren Shepherd
207e8a5c14 Merge pull request #23 from KnicKnic/fix_certpath_windows
fix certpath generation for windows
2020-07-27 22:48:06 -07:00
Darren Shepherd
9c1939da3a Merge pull request #25 from ibuildthecloud/master
Stop using wrangler-api project
2020-07-14 13:10:33 -07:00
Darren Shepherd
5529139fbe Update vendor 2020-07-14 13:09:07 -07:00
Darren Shepherd
bcbb612b24 Stop using wrangler-api project 2020-07-14 13:09:07 -07:00
11 changed files with 228 additions and 73 deletions

15
.drone.yml Normal file
View File

@@ -0,0 +1,15 @@
---
kind: pipeline
name: fossa
steps:
- name: fossa
image: rancher/drone-fossa:latest
settings:
api_key:
from_secret: FOSSA_API_KEY
when:
instance:
- drone-publish.rancher.io

View File

@@ -33,7 +33,9 @@ import (
"math"
"math/big"
"net"
"os"
"path/filepath"
"strconv"
"strings"
"time"
@@ -109,11 +111,18 @@ func NewSignedCert(cfg Config, key crypto.Signer, caCert *x509.Certificate, caKe
if len(cfg.Usages) == 0 {
return nil, errors.New("must specify at least one ExtKeyUsage")
}
var expiresAt time.Duration
expiresAt := duration365d
if cfg.ExpiresAt > 0 {
expiresAt = time.Duration(cfg.ExpiresAt)
} else {
expiresAt = duration365d
envExpirationDays := os.Getenv("CATTLE_NEW_SIGNED_CERT_EXPIRATION_DAYS")
if envExpirationDays != "" {
if envExpirationDaysInt, err := strconv.Atoi(envExpirationDays); err != nil {
logrus.Infof("[NewSignedCert] expiration days from ENV (%s) could not be converted to int (falling back to default value: %d)", envExpirationDays, expiresAt)
} else {
expiresAt = time.Hour * 24 * time.Duration(envExpirationDaysInt)
}
}
}
certTmpl := x509.Certificate{

16
cert/secret.go Normal file
View File

@@ -0,0 +1,16 @@
package cert
import v1 "k8s.io/api/core/v1"
func IsValidTLSSecret(secret *v1.Secret) bool {
if secret == nil {
return false
}
if _, ok := secret.Data[v1.TLSCertKey]; !ok {
return false
}
if _, ok := secret.Data[v1.TLSPrivateKeyKey]; !ok {
return false
}
return true
}

View File

@@ -6,6 +6,7 @@ import (
"fmt"
"io/ioutil"
"os"
"time"
"github.com/rancher/dynamiclistener/cert"
)
@@ -16,7 +17,7 @@ func GenCA() (*x509.Certificate, crypto.Signer, error) {
return nil, nil, err
}
caCert, err := NewSelfSignedCACert(caKey, "dynamiclistener-ca", "dynamiclistener-org")
caCert, err := NewSelfSignedCACert(caKey, fmt.Sprintf("dynamiclistener-ca@%d", time.Now().Unix()), "dynamiclistener-org")
if err != nil {
return nil, nil, err
}

View File

@@ -15,6 +15,7 @@ import (
"regexp"
"sort"
"strings"
"time"
"github.com/rancher/dynamiclistener/cert"
"github.com/sirupsen/logrus"
@@ -32,11 +33,12 @@ var (
)
type TLS struct {
CACert *x509.Certificate
CAKey crypto.Signer
CN string
Organization []string
FilterCN func(...string) []string
CACert *x509.Certificate
CAKey crypto.Signer
CN string
Organization []string
FilterCN func(...string) []string
ExpirationDaysCheck int
}
func cns(secret *v1.Secret) (cns []string) {
@@ -72,7 +74,8 @@ func collectCNs(secret *v1.Secret) (domains []string, ips []net.IP, err error) {
// Merge combines the SAN lists from the target and additional Secrets, and
// returns a potentially modified Secret, along with a bool indicating if the
// returned Secret is not the same as the target Secret.
// returned Secret is not the same as the target Secret. Secrets with expired
// certificates will never be returned.
//
// If the merge would not add any CNs to the additional Secret, the additional
// Secret is returned, to allow for certificate rotation/regeneration.
@@ -93,17 +96,17 @@ func (t *TLS) Merge(target, additional *v1.Secret) (*v1.Secret, bool, error) {
// if the additional secret already has all the CNs, use it in preference to the
// current one. This behavior is required to allow for renewal or regeneration.
if !NeedsUpdate(0, additional, mergedCNs...) {
if !NeedsUpdate(0, additional, mergedCNs...) && !t.IsExpired(additional) {
return additional, true, nil
}
// if the target secret already has all the CNs, continue using it. The additional
// cert had only a subset of the current CNs, so nothing needs to be added.
if !NeedsUpdate(0, target, mergedCNs...) {
if !NeedsUpdate(0, target, mergedCNs...) && !t.IsExpired(target) {
return target, false, nil
}
// neither cert currently has all the necessary CNs; generate a new one.
// neither cert currently has all the necessary CNs or is unexpired; generate a new one.
return t.generateCert(target, mergedCNs...)
}
@@ -154,6 +157,10 @@ func (t *TLS) generateCert(secret *v1.Secret, cn ...string) (*v1.Secret, bool, e
secret = &v1.Secret{}
}
if err := t.Verify(secret); err != nil {
logrus.Warnf("unable to verify existing certificate: %v - signing operation may change certificate issuer", err)
}
secret = populateCN(secret, cn...)
privateKey, err := getPrivateKey(secret)
@@ -171,7 +178,7 @@ func (t *TLS) generateCert(secret *v1.Secret, cn ...string) (*v1.Secret, bool, e
return nil, false, err
}
certBytes, keyBytes, err := Marshal(newCert, privateKey)
keyBytes, certBytes, err := MarshalChain(privateKey, newCert, t.CACert)
if err != nil {
return nil, false, err
}
@@ -179,6 +186,7 @@ func (t *TLS) generateCert(secret *v1.Secret, cn ...string) (*v1.Secret, bool, e
if secret.Data == nil {
secret.Data = map[string][]byte{}
}
secret.Type = v1.SecretTypeTLS
secret.Data[v1.TLSCertKey] = certBytes
secret.Data[v1.TLSPrivateKeyKey] = keyBytes
secret.Annotations[fingerprint] = fmt.Sprintf("SHA1=%X", sha1.Sum(newCert.Raw))
@@ -186,6 +194,44 @@ func (t *TLS) generateCert(secret *v1.Secret, cn ...string) (*v1.Secret, bool, e
return secret, true, nil
}
func (t *TLS) IsExpired(secret *v1.Secret) bool {
certsPem := secret.Data[v1.TLSCertKey]
if len(certsPem) == 0 {
return false
}
certificates, err := cert.ParseCertsPEM(certsPem)
if err != nil || len(certificates) == 0 {
return false
}
expirationDays := time.Duration(t.ExpirationDaysCheck) * time.Hour * 24
return time.Now().Add(expirationDays).After(certificates[0].NotAfter)
}
func (t *TLS) Verify(secret *v1.Secret) error {
certsPem := secret.Data[v1.TLSCertKey]
if len(certsPem) == 0 {
return nil
}
certificates, err := cert.ParseCertsPEM(certsPem)
if err != nil || len(certificates) == 0 {
return err
}
verifyOpts := x509.VerifyOptions{
Roots: x509.NewCertPool(),
KeyUsages: []x509.ExtKeyUsage{
x509.ExtKeyUsageAny,
},
}
verifyOpts.Roots.AddCert(t.CACert)
_, err = certificates[0].Verify(verifyOpts)
return err
}
func (t *TLS) newCert(domains []string, ips []net.IP, privateKey crypto.Signer) (*x509.Certificate, error) {
return NewSignedCert(privateKey, t.CACert, t.CAKey, t.CN, t.Organization, domains, ips)
}
@@ -208,7 +254,10 @@ func populateCN(secret *v1.Secret, cn ...string) *v1.Secret {
// IsStatic returns true if the Secret has an attribute indicating that it contains
// a static (aka user-provided) certificate, which should not be modified.
func IsStatic(secret *v1.Secret) bool {
return secret.Annotations[Static] == "true"
if secret != nil && secret.Annotations != nil {
return secret.Annotations[Static] == "true"
}
return false
}
// NeedsUpdate returns true if any of the CNs are not currently present on the
@@ -246,14 +295,33 @@ func getPrivateKey(secret *v1.Secret) (crypto.Signer, error) {
return NewPrivateKey()
}
// MarshalChain returns given key and certificates as byte slices.
func MarshalChain(privateKey crypto.Signer, certs ...*x509.Certificate) (keyBytes, certChainBytes []byte, err error) {
keyBytes, err = cert.MarshalPrivateKeyToPEM(privateKey)
if err != nil {
return nil, nil, err
}
for _, cert := range certs {
if cert != nil {
certBlock := pem.Block{
Type: CertificateBlockType,
Bytes: cert.Raw,
}
certChainBytes = append(certChainBytes, pem.EncodeToMemory(&certBlock)...)
}
}
return keyBytes, certChainBytes, nil
}
// Marshal returns the given cert and key as byte slices.
func Marshal(x509Cert *x509.Certificate, privateKey crypto.Signer) ([]byte, []byte, error) {
func Marshal(x509Cert *x509.Certificate, privateKey crypto.Signer) (certBytes, keyBytes []byte, err error) {
certBlock := pem.Block{
Type: CertificateBlockType,
Bytes: x509Cert.Raw,
}
keyBytes, err := cert.MarshalPrivateKeyToPEM(privateKey)
keyBytes, err = cert.MarshalPrivateKeyToPEM(privateKey)
if err != nil {
return nil, nil, err
}

3
go.mod
View File

@@ -1,6 +1,6 @@
module github.com/rancher/dynamiclistener
go 1.16
go 1.12
require (
github.com/rancher/wrangler v0.8.9
@@ -8,4 +8,5 @@ require (
golang.org/x/crypto v0.0.0-20210322153248-0c34fe9e7dc2
k8s.io/api v0.18.8
k8s.io/apimachinery v0.18.8
k8s.io/client-go v0.18.8
)

View File

@@ -7,7 +7,6 @@ import (
"crypto/x509"
"net"
"net/http"
"runtime"
"strings"
"sync"
"time"
@@ -45,14 +44,18 @@ func NewListener(l net.Listener, storage TLSStorage, caCert *x509.Certificate, c
if config.TLSConfig == nil {
config.TLSConfig = &tls.Config{}
}
if config.ExpirationDaysCheck == 0 {
config.ExpirationDaysCheck = 90
}
dynamicListener := &listener{
factory: &factory.TLS{
CACert: caCert,
CAKey: caKey,
CN: config.CN,
Organization: config.Organization,
FilterCN: allowDefaultSANs(config.SANs, config.FilterCN),
CACert: caCert,
CAKey: caKey,
CN: config.CN,
Organization: config.Organization,
FilterCN: allowDefaultSANs(config.SANs, config.FilterCN),
ExpirationDaysCheck: config.ExpirationDaysCheck,
},
Listener: l,
storage: &nonNil{storage: storage},
@@ -82,10 +85,6 @@ func NewListener(l net.Listener, storage TLSStorage, caCert *x509.Certificate, c
}
}
if config.ExpirationDaysCheck == 0 {
config.ExpirationDaysCheck = 30
}
tlsListener := tls.NewListener(dynamicListener.WrapExpiration(config.ExpirationDaysCheck), dynamicListener.tlsConfig)
return tlsListener, dynamicListener.cacheHandler(), nil
@@ -163,15 +162,15 @@ type listener struct {
func (l *listener) WrapExpiration(days int) net.Listener {
ctx, cancel := context.WithCancel(context.Background())
go func() {
// busy-wait for certificate preload to complete
// loop on short sleeps until certificate preload completes
for l.cert == nil {
runtime.Gosched()
time.Sleep(time.Millisecond)
}
for {
wait := 6 * time.Hour
if err := l.checkExpiration(days); err != nil {
logrus.Errorf("failed to check and renew dynamic cert: %v", err)
logrus.Errorf("dynamiclistener %s: failed to check and renew dynamic cert: %v", l.Addr(), err)
// Don't go into short retry loop if we're using a static (user-provided) cert.
// We will still check and print an error every six hours until the user updates the secret with
// a cert that is not about to expire. Hopefully this will prompt them to take action.
@@ -263,12 +262,18 @@ func (l *listener) Accept() (net.Conn, error) {
l.init.Do(func() {
if len(l.sans) > 0 {
if err := l.updateCert(l.sans...); err != nil {
logrus.Errorf("failed to update cert with configured SANs: %v", err)
logrus.Errorf("dynamiclistener %s: failed to update cert with configured SANs: %v", l.Addr(), err)
return
}
if _, err := l.loadCert(nil); err != nil {
logrus.Errorf("failed to preload certificate: %v", err)
}
}
if cert, err := l.loadCert(nil); err != nil {
logrus.Errorf("dynamiclistener %s: failed to preload certificate: %v", l.Addr(), err)
} else if cert == nil {
// This should only occur on the first startup when no SANs are configured in the listener config, in which
// case no certificate can be created, as dynamiclistener will not create certificates until at least one IP
// or DNS SAN is set. It will also occur when using the Kubernetes storage without a local File cache.
// For reliable serving of requests, callers should configure a local cache and/or a default set of SANs.
logrus.Warnf("dynamiclistener %s: no cached certificate available for preload - deferring certificate load until storage initialization or first client request", l.Addr())
}
})
@@ -284,14 +289,12 @@ func (l *listener) Accept() (net.Conn, error) {
host, _, err := net.SplitHostPort(addr.String())
if err != nil {
logrus.Errorf("failed to parse network %s: %v", addr.Network(), err)
logrus.Errorf("dynamiclistener %s: failed to parse connection local address %s: %v", l.Addr(), addr, err)
return conn, nil
}
if !strings.Contains(host, ":") {
if err := l.updateCert(host); err != nil {
logrus.Errorf("failed to update cert with listener address: %v", err)
}
if err := l.updateCert(host); err != nil {
logrus.Errorf("dynamiclistener %s: failed to update cert with connection local address: %v", l.Addr(), err)
}
if l.conns != nil {
@@ -338,7 +341,7 @@ func (l *listener) getCertificate(hello *tls.ClientHelloInfo) (*tls.Certificate,
newConn := hello.Conn
if hello.ServerName != "" {
if err := l.updateCert(hello.ServerName); err != nil {
logrus.Errorf("failed to update cert with TLS ServerName: %v", err)
logrus.Errorf("dynamiclistener %s: failed to update cert with TLS ServerName: %v", l.Addr(), err)
return nil, err
}
}
@@ -408,6 +411,9 @@ func (l *listener) loadCert(currentConn net.Conn) (*tls.Certificate, error) {
if err != nil {
return nil, err
}
if !cert.IsValidTLSSecret(secret) {
return l.cert, nil
}
if l.cert != nil && l.version == secret.ResourceVersion && secret.ResourceVersion != "" {
return l.cert, nil
}
@@ -452,7 +458,7 @@ func (l *listener) cacheHandler() http.Handler {
}
if err := l.updateCert(h); err != nil {
logrus.Errorf("failed to update cert with HTTP request Host header: %v", err)
logrus.Errorf("dynamiclistener %s: failed to update cert with HTTP request Host header: %v", l.Addr(), err)
}
}
})

View File

@@ -64,7 +64,10 @@ func ListenAndServe(ctx context.Context, httpsPort, httpPort int, handler http.H
}
tlsServer := http.Server{
Handler: handler,
Handler: handler,
BaseContext: func(listener net.Listener) context.Context {
return ctx
},
ErrorLog: errorLog,
}
@@ -86,6 +89,9 @@ func ListenAndServe(ctx context.Context, httpsPort, httpPort int, handler http.H
Addr: fmt.Sprintf("%s:%d", opts.BindHost, httpPort),
Handler: handler,
ErrorLog: errorLog,
BaseContext: func(listener net.Listener) context.Context {
return ctx
},
}
go func() {
logrus.Infof("Listening on %s:%d", opts.BindHost, httpPort)

View File

@@ -56,7 +56,7 @@ func createAndStoreClientCert(secrets v1controller.SecretClient, namespace strin
return nil, err
}
certPem, keyPem, err := factory.Marshal(cert, key)
keyPem, certPem, err := factory.MarshalChain(key, cert, caCert)
if err != nil {
return nil, err
}

View File

@@ -6,6 +6,7 @@ import (
"time"
"github.com/rancher/dynamiclistener"
"github.com/rancher/dynamiclistener/cert"
"github.com/rancher/wrangler/pkg/generated/controllers/core"
v1controller "github.com/rancher/wrangler/pkg/generated/controllers/core/v1"
"github.com/rancher/wrangler/pkg/start"
@@ -13,6 +14,7 @@ import (
v1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/util/retry"
)
type CoreGetter func() *core.Factory
@@ -39,10 +41,9 @@ func New(ctx context.Context, core CoreGetter, namespace, name string, backing d
// lazy init
go func() {
for {
core := core()
if core != nil {
storage.init(core.Core().V1().Secret())
_ = start.All(ctx, 5, core)
if coreFactory := core(); coreFactory != nil {
storage.init(coreFactory.Core().V1().Secret())
_ = start.All(ctx, 5, coreFactory)
return
}
@@ -58,16 +59,18 @@ func New(ctx context.Context, core CoreGetter, namespace, name string, backing d
}
type storage struct {
sync.Mutex
sync.RWMutex
namespace, name string
storage dynamiclistener.TLSStorage
secrets v1controller.SecretClient
secrets v1controller.SecretController
ctx context.Context
tls dynamiclistener.TLSFactory
}
func (s *storage) SetFactory(tls dynamiclistener.TLSFactory) {
s.Lock()
defer s.Unlock()
s.tls = tls
}
@@ -90,7 +93,7 @@ func (s *storage) init(secrets v1controller.SecretController) {
s.secrets = secrets
secret, err := s.storage.Get()
if err == nil && secret != nil && len(secret.Data) > 0 {
if err == nil && cert.IsValidTLSSecret(secret) {
// local storage had a cached secret, ensure that it exists in Kubernetes
_, err := s.secrets.Create(&v1.Secret{
ObjectMeta: metav1.ObjectMeta{
@@ -108,7 +111,9 @@ func (s *storage) init(secrets v1controller.SecretController) {
// local storage was empty, try to populate it
secret, err := s.secrets.Get(s.namespace, s.name, metav1.GetOptions{})
if err != nil {
logrus.Warnf("Failed to init Kubernetes secret: %v", err)
if !errors.IsNotFound(err) {
logrus.Warnf("Failed to init Kubernetes secret: %v", err)
}
return
}
@@ -119,13 +124,16 @@ func (s *storage) init(secrets v1controller.SecretController) {
}
func (s *storage) Get() (*v1.Secret, error) {
s.Lock()
defer s.Unlock()
s.RLock()
defer s.RUnlock()
return s.storage.Get()
}
func (s *storage) targetSecret() (*v1.Secret, error) {
s.RLock()
defer s.RUnlock()
existingSecret, err := s.secrets.Get(s.namespace, s.name, metav1.GetOptions{})
if errors.IsNotFound(err) {
return &v1.Secret{
@@ -133,13 +141,14 @@ func (s *storage) targetSecret() (*v1.Secret, error) {
Name: s.name,
Namespace: s.namespace,
},
Type: v1.SecretTypeTLS,
}, nil
}
return existingSecret, err
}
func (s *storage) saveInK8s(secret *v1.Secret) (*v1.Secret, error) {
if s.secrets == nil {
if !s.initComplete() {
return secret, nil
}
@@ -152,14 +161,14 @@ func (s *storage) saveInK8s(secret *v1.Secret) (*v1.Secret, error) {
// in favor of just blindly replacing the fields on the Kubernetes secret.
if s.tls != nil {
// merge new secret with secret from backing storage, if one exists
if existing, err := s.storage.Get(); err == nil && existing != nil && len(existing.Data) > 0 {
if existing, err := s.Get(); err == nil && cert.IsValidTLSSecret(existing) {
if newSecret, updated, err := s.tls.Merge(existing, secret); err == nil && updated {
secret = newSecret
}
}
// merge new secret with existing secret from Kubernetes, if one exists
if len(targetSecret.Data) > 0 {
if cert.IsValidTLSSecret(targetSecret) {
if newSecret, updated, err := s.tls.Merge(targetSecret, secret); err != nil {
return nil, err
} else if !updated {
@@ -170,36 +179,60 @@ func (s *storage) saveInK8s(secret *v1.Secret) (*v1.Secret, error) {
}
}
// ensure that the merged secret actually contains data before overwriting the existing fields
if !cert.IsValidTLSSecret(secret) {
logrus.Warnf("Skipping save of TLS secret for %s/%s due to missing certificate data", secret.Namespace, secret.Name)
return targetSecret, nil
}
targetSecret.Annotations = secret.Annotations
targetSecret.Type = v1.SecretTypeTLS
targetSecret.Data = secret.Data
if targetSecret.UID == "" {
logrus.Infof("Creating new TLS secret for %v (count: %d): %v", targetSecret.Name, len(targetSecret.Annotations)-1, targetSecret.Annotations)
logrus.Infof("Creating new TLS secret for %s/%s (count: %d): %v", targetSecret.Namespace, targetSecret.Name, len(targetSecret.Annotations)-1, targetSecret.Annotations)
return s.secrets.Create(targetSecret)
}
logrus.Infof("Updating TLS secret for %v (count: %d): %v", targetSecret.Name, len(targetSecret.Annotations)-1, targetSecret.Annotations)
logrus.Infof("Updating TLS secret for %s/%s (count: %d): %v", targetSecret.Namespace, targetSecret.Name, len(targetSecret.Annotations)-1, targetSecret.Annotations)
return s.secrets.Update(targetSecret)
}
func (s *storage) Update(secret *v1.Secret) (err error) {
s.Lock()
defer s.Unlock()
for i := 0; i < 3; i++ {
secret, err = s.saveInK8s(secret)
if errors.IsConflict(err) {
continue
} else if err != nil {
return err
func (s *storage) Update(secret *v1.Secret) error {
// Asynchronously update the Kubernetes secret, as doing so inline may block the listener from
// accepting new connections if the apiserver becomes unavailable after the Secrets controller
// has been initialized. We're not passing around any contexts here, nor does the controller
// accept any, so there's no good way to soft-fail with a reasonable timeout.
go func() {
if err := s.update(secret); err != nil {
logrus.Errorf("Failed to save TLS secret for %s/%s: %v", secret.Namespace, secret.Name, err)
}
break
}
}()
return nil
}
func isConflictOrAlreadyExists(err error) bool {
return errors.IsConflict(err) || errors.IsAlreadyExists(err)
}
func (s *storage) update(secret *v1.Secret) (err error) {
var newSecret *v1.Secret
err = retry.OnError(retry.DefaultRetry, isConflictOrAlreadyExists, func() error {
newSecret, err = s.saveInK8s(secret)
return err
})
if err != nil {
return err
}
// update underlying storage
return s.storage.Update(secret)
// Only hold the lock while updating underlying storage
s.Lock()
defer s.Unlock()
return s.storage.Update(newSecret)
}
func (s *storage) initComplete() bool {
s.RLock()
defer s.RUnlock()
return s.secrets != nil
}

View File

@@ -39,7 +39,7 @@ func (m *memory) Update(secret *v1.Secret) error {
}
}
logrus.Infof("Active TLS secret %s (ver=%s) (count %d): %v", secret.Name, secret.ResourceVersion, len(secret.Annotations)-1, secret.Annotations)
logrus.Infof("Active TLS secret %s/%s (ver=%s) (count %d): %v", secret.Namespace, secret.Name, secret.ResourceVersion, len(secret.Annotations)-1, secret.Annotations)
m.secret = secret
}
return nil