forked from github/dynamiclistener
Compare commits
22 Commits
v0.3.3
...
v0.3.6-rc3
Author | SHA1 | Date | |
---|---|---|---|
|
ad32b99079 | ||
|
706df9c790 | ||
|
3e7612c2c9 | ||
|
e6585da47a | ||
|
6cc9a670e1 | ||
|
8f13b193a1 | ||
|
02304047cf | ||
|
4c1ac9bd4b | ||
|
2b62d5cc69 | ||
|
2ac221e5d6 | ||
|
b7a028fe3f | ||
|
a150115362 | ||
|
7001abfa1f | ||
|
3adafb7edb | ||
|
e73d5f2fca | ||
|
401fafb7e6 | ||
|
bad953b9f0 | ||
|
8ebd77f8a4 | ||
|
fdf983a935 | ||
|
7b5997cee9 | ||
|
42d72c2ef2 | ||
|
5e81b14c1f |
15
.drone.yml
Normal file
15
.drone.yml
Normal 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
|
||||
|
9
.github/renovate.json
vendored
Normal file
9
.github/renovate.json
vendored
Normal file
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"extends": [
|
||||
"github>rancher/renovate-config#release"
|
||||
],
|
||||
"baseBranches": [
|
||||
"master"
|
||||
],
|
||||
"prHourlyLimit": 2
|
||||
}
|
25
.github/workflows/renovate.yml
vendored
Normal file
25
.github/workflows/renovate.yml
vendored
Normal file
@@ -0,0 +1,25 @@
|
||||
name: Renovate
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
logLevel:
|
||||
description: "Override default log level"
|
||||
required: false
|
||||
default: "info"
|
||||
type: string
|
||||
overrideSchedule:
|
||||
description: "Override all schedules"
|
||||
required: false
|
||||
default: "false"
|
||||
type: string
|
||||
# Run twice in the early morning (UTC) for initial and follow up steps (create pull request and merge)
|
||||
schedule:
|
||||
- cron: '30 4,6 * * *'
|
||||
|
||||
jobs:
|
||||
call-workflow:
|
||||
uses: rancher/renovate-config/.github/workflows/renovate.yml@release
|
||||
with:
|
||||
logLevel: ${{ inputs.logLevel || 'info' }}
|
||||
overrideSchedule: ${{ github.event.inputs.overrideSchedule == 'true' && '{''schedule'':null}' || '' }}
|
||||
secrets: inherit
|
13
cert/cert.go
13
cert/cert.go
@@ -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{
|
||||
|
@@ -25,18 +25,28 @@ func GenCA() (*x509.Certificate, crypto.Signer, error) {
|
||||
return caCert, caKey, nil
|
||||
}
|
||||
|
||||
// Deprecated: Use LoadOrGenCAChain instead as it supports intermediate CAs
|
||||
func LoadOrGenCA() (*x509.Certificate, crypto.Signer, error) {
|
||||
cert, key, err := loadCA()
|
||||
if err == nil {
|
||||
return cert, key, nil
|
||||
}
|
||||
|
||||
cert, key, err = GenCA()
|
||||
chain, signer, err := LoadOrGenCAChain()
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
return chain[0], signer, err
|
||||
}
|
||||
|
||||
certBytes, keyBytes, err := Marshal(cert, key)
|
||||
func LoadOrGenCAChain() ([]*x509.Certificate, crypto.Signer, error) {
|
||||
certs, key, err := loadCA()
|
||||
if err == nil {
|
||||
return certs, key, nil
|
||||
}
|
||||
|
||||
cert, key, err := GenCA()
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
certs = []*x509.Certificate{cert}
|
||||
|
||||
certBytes, keyBytes, err := MarshalChain(key, certs...)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
@@ -53,14 +63,22 @@ func LoadOrGenCA() (*x509.Certificate, crypto.Signer, error) {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
return cert, key, nil
|
||||
return certs, key, nil
|
||||
}
|
||||
|
||||
func loadCA() (*x509.Certificate, crypto.Signer, error) {
|
||||
return LoadCerts("./certs/ca.pem", "./certs/ca.key")
|
||||
func loadCA() ([]*x509.Certificate, crypto.Signer, error) {
|
||||
return LoadCertsChain("./certs/ca.pem", "./certs/ca.key")
|
||||
}
|
||||
|
||||
func LoadCA(caPem, caKey []byte) (*x509.Certificate, crypto.Signer, error) {
|
||||
chain, signer, err := LoadCAChain(caPem, caKey)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
return chain[0], signer, nil
|
||||
}
|
||||
|
||||
func LoadCAChain(caPem, caKey []byte) ([]*x509.Certificate, crypto.Signer, error) {
|
||||
key, err := cert.ParsePrivateKeyPEM(caKey)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
@@ -70,15 +88,24 @@ func LoadCA(caPem, caKey []byte) (*x509.Certificate, crypto.Signer, error) {
|
||||
return nil, nil, fmt.Errorf("key is not a crypto.Signer")
|
||||
}
|
||||
|
||||
cert, err := ParseCertPEM(caPem)
|
||||
certs, err := cert.ParseCertsPEM(caPem)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
return cert, signer, nil
|
||||
return certs, signer, nil
|
||||
}
|
||||
|
||||
// Deprecated: Use LoadCertsChain instead as it supports intermediate CAs
|
||||
func LoadCerts(certFile, keyFile string) (*x509.Certificate, crypto.Signer, error) {
|
||||
chain, signer, err := LoadCertsChain(certFile, keyFile)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
return chain[0], signer, err
|
||||
}
|
||||
|
||||
func LoadCertsChain(certFile, keyFile string) ([]*x509.Certificate, crypto.Signer, error) {
|
||||
caPem, err := ioutil.ReadFile(certFile)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
@@ -88,5 +115,5 @@ func LoadCerts(certFile, keyFile string) (*x509.Certificate, crypto.Signer, erro
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
return LoadCA(caPem, caKey)
|
||||
return LoadCAChain(caPem, caKey)
|
||||
}
|
||||
|
@@ -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...)
|
||||
}
|
||||
|
||||
@@ -175,7 +178,7 @@ func (t *TLS) generateCert(secret *v1.Secret, cn ...string) (*v1.Secret, bool, e
|
||||
return nil, false, err
|
||||
}
|
||||
|
||||
keyBytes, certBytes, err := MarshalChain(privateKey, newCert, t.CACert)
|
||||
keyBytes, certBytes, err := MarshalChain(privateKey, append([]*x509.Certificate{newCert}, t.CACert...)...)
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
@@ -191,6 +194,21 @@ 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 {
|
||||
@@ -208,14 +226,16 @@ func (t *TLS) Verify(secret *v1.Secret) error {
|
||||
x509.ExtKeyUsageAny,
|
||||
},
|
||||
}
|
||||
verifyOpts.Roots.AddCert(t.CACert)
|
||||
for _, c := range t.CACert {
|
||||
verifyOpts.Roots.AddCert(c)
|
||||
}
|
||||
|
||||
_, 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)
|
||||
return NewSignedCert(privateKey, t.CACert[0], t.CAKey, t.CN, t.Organization, domains, ips)
|
||||
}
|
||||
|
||||
func populateCN(secret *v1.Secret, cn ...string) *v1.Secret {
|
||||
|
65
go.mod
65
go.mod
@@ -1,12 +1,63 @@
|
||||
module github.com/rancher/dynamiclistener
|
||||
|
||||
go 1.12
|
||||
go 1.20
|
||||
|
||||
require (
|
||||
github.com/rancher/wrangler v0.8.9
|
||||
github.com/sirupsen/logrus v1.4.2
|
||||
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
|
||||
github.com/rancher/wrangler v1.1.1-0.20230831050635-df1bd5aae9df
|
||||
github.com/sirupsen/logrus v1.9.3
|
||||
github.com/stretchr/testify v1.8.4
|
||||
golang.org/x/crypto v0.11.0
|
||||
k8s.io/api v0.27.4
|
||||
k8s.io/apimachinery v0.27.4
|
||||
k8s.io/client-go v0.27.4
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/beorn7/perks v1.0.1 // indirect
|
||||
github.com/cespare/xxhash/v2 v2.1.2 // indirect
|
||||
github.com/davecgh/go-spew v1.1.1 // indirect
|
||||
github.com/emicklei/go-restful/v3 v3.9.0 // indirect
|
||||
github.com/evanphx/json-patch v4.12.0+incompatible // indirect
|
||||
github.com/go-logr/logr v1.2.3 // indirect
|
||||
github.com/go-openapi/jsonpointer v0.19.6 // indirect
|
||||
github.com/go-openapi/jsonreference v0.20.1 // indirect
|
||||
github.com/go-openapi/swag v0.22.3 // indirect
|
||||
github.com/gogo/protobuf v1.3.2 // indirect
|
||||
github.com/golang/protobuf v1.5.3 // indirect
|
||||
github.com/google/gnostic v0.5.7-v3refs // indirect
|
||||
github.com/google/go-cmp v0.5.9 // indirect
|
||||
github.com/google/gofuzz v1.2.0 // indirect
|
||||
github.com/google/uuid v1.3.0 // indirect
|
||||
github.com/josharian/intern v1.0.0 // indirect
|
||||
github.com/json-iterator/go v1.1.12 // indirect
|
||||
github.com/mailru/easyjson v0.7.7 // indirect
|
||||
github.com/matttproud/golang_protobuf_extensions v1.0.2 // indirect
|
||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
|
||||
github.com/modern-go/reflect2 v1.0.2 // indirect
|
||||
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect
|
||||
github.com/pkg/errors v0.9.1 // indirect
|
||||
github.com/pmezard/go-difflib v1.0.0 // indirect
|
||||
github.com/prometheus/client_golang v1.14.0 // indirect
|
||||
github.com/prometheus/client_model v0.3.0 // indirect
|
||||
github.com/prometheus/common v0.37.0 // indirect
|
||||
github.com/prometheus/procfs v0.8.0 // indirect
|
||||
github.com/rancher/lasso v0.0.0-20230830164424-d684fdeb6f29 // indirect
|
||||
golang.org/x/net v0.12.0 // indirect
|
||||
golang.org/x/oauth2 v0.10.0 // indirect
|
||||
golang.org/x/sync v0.1.0 // indirect
|
||||
golang.org/x/sys v0.10.0 // indirect
|
||||
golang.org/x/term v0.10.0 // indirect
|
||||
golang.org/x/text v0.11.0 // indirect
|
||||
golang.org/x/time v0.3.0 // indirect
|
||||
google.golang.org/appengine v1.6.7 // indirect
|
||||
google.golang.org/protobuf v1.31.0 // indirect
|
||||
gopkg.in/inf.v0 v0.9.1 // indirect
|
||||
gopkg.in/yaml.v2 v2.4.0 // indirect
|
||||
gopkg.in/yaml.v3 v3.0.1 // indirect
|
||||
k8s.io/klog/v2 v2.90.1 // indirect
|
||||
k8s.io/kube-openapi v0.0.0-20230501164219-8b0f38b5fd1f // indirect
|
||||
k8s.io/utils v0.0.0-20230209194617-a36077c30491 // indirect
|
||||
sigs.k8s.io/json v0.0.0-20221116044647-bc3834ca7abd // indirect
|
||||
sigs.k8s.io/structured-merge-diff/v4 v4.2.3 // indirect
|
||||
sigs.k8s.io/yaml v1.3.0 // indirect
|
||||
)
|
||||
|
57
listener.go
57
listener.go
@@ -7,7 +7,6 @@ import (
|
||||
"crypto/x509"
|
||||
"net"
|
||||
"net/http"
|
||||
"runtime"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
@@ -35,7 +34,12 @@ type SetFactory interface {
|
||||
SetFactory(tls TLSFactory)
|
||||
}
|
||||
|
||||
// Deprecated: Use NewListenerWithChain instead as it supports intermediate CAs
|
||||
func NewListener(l net.Listener, storage TLSStorage, caCert *x509.Certificate, caKey crypto.Signer, config Config) (net.Listener, http.Handler, error) {
|
||||
return NewListenerWithChain(l, storage, []*x509.Certificate{caCert}, caKey, config)
|
||||
}
|
||||
|
||||
func NewListenerWithChain(l net.Listener, storage TLSStorage, caCert []*x509.Certificate, caKey crypto.Signer, config Config) (net.Listener, http.Handler, error) {
|
||||
if config.CN == "" {
|
||||
config.CN = "dynamic"
|
||||
}
|
||||
@@ -45,16 +49,21 @@ 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,
|
||||
certReady: make(chan struct{}),
|
||||
storage: &nonNil{storage: storage},
|
||||
sans: config.SANs,
|
||||
maxSANs: config.MaxSANs,
|
||||
@@ -82,10 +91,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
|
||||
@@ -155,6 +160,7 @@ type listener struct {
|
||||
version string
|
||||
tlsConfig *tls.Config
|
||||
cert *tls.Certificate
|
||||
certReady chan struct{}
|
||||
sans []string
|
||||
maxSANs int
|
||||
init sync.Once
|
||||
@@ -163,9 +169,12 @@ 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
|
||||
for l.cert == nil {
|
||||
runtime.Gosched()
|
||||
|
||||
// wait for cert to be set, this will unblock when the channel is closed
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-l.certReady:
|
||||
}
|
||||
|
||||
for {
|
||||
@@ -346,8 +355,20 @@ func (l *listener) getCertificate(hello *tls.ClientHelloInfo) (*tls.Certificate,
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
return l.loadCert(newConn)
|
||||
connCert, err := l.loadCert(newConn)
|
||||
if connCert != nil && err == nil && newConn != nil && l.conns != nil {
|
||||
// if we were successfully able to load a cert and are closing connections on cert changes, mark newConn ready
|
||||
// this will allow us to close the connection if a future connection forces the cert to re-load
|
||||
wrapper, ok := newConn.(*closeWrapper)
|
||||
if !ok {
|
||||
logrus.Debugf("will not mark non-close wrapper connection from %s to %s as ready", newConn.RemoteAddr(), newConn.LocalAddr())
|
||||
return connCert, err
|
||||
}
|
||||
l.connLock.Lock()
|
||||
l.conns[wrapper.id].ready = true
|
||||
l.connLock.Unlock()
|
||||
}
|
||||
return connCert, err
|
||||
}
|
||||
|
||||
func (l *listener) updateCert(cn ...string) error {
|
||||
@@ -434,11 +455,15 @@ func (l *listener) loadCert(currentConn net.Conn) (*tls.Certificate, error) {
|
||||
}
|
||||
_ = conn.close()
|
||||
}
|
||||
l.conns[currentConn.(*closeWrapper).id].ready = true
|
||||
l.connLock.Unlock()
|
||||
}
|
||||
|
||||
// we can only close the ready channel once when the cert is first assigned
|
||||
canClose := l.cert == nil
|
||||
l.cert = &cert
|
||||
if canClose {
|
||||
close(l.certReady)
|
||||
}
|
||||
l.version = secret.ResourceVersion
|
||||
return l.cert, nil
|
||||
}
|
||||
|
225
listener_test.go
Normal file
225
listener_test.go
Normal file
@@ -0,0 +1,225 @@
|
||||
package dynamiclistener
|
||||
|
||||
import (
|
||||
"crypto/tls"
|
||||
"net"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/rancher/dynamiclistener/factory"
|
||||
"github.com/stretchr/testify/assert"
|
||||
v1 "k8s.io/api/core/v1"
|
||||
apiError "k8s.io/apimachinery/pkg/api/errors"
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
"k8s.io/apimachinery/pkg/runtime/schema"
|
||||
)
|
||||
|
||||
func Test_getCertificate(t *testing.T) {
|
||||
beforeKey, beforeCert, err := newCertificate()
|
||||
assert.NoError(t, err, "Error when setting up test - unable to construct before key for test")
|
||||
beforeTLSCert, err := tls.X509KeyPair(beforeCert, beforeKey)
|
||||
assert.NoError(t, err, "Error when setting up test - unable to convert before to tls.Certificate")
|
||||
afterKey, afterCert, err := newCertificate()
|
||||
assert.NoError(t, err, "Error when setting up test - unable to construct after key for test")
|
||||
afterTLSCert, err := tls.X509KeyPair(afterCert, afterKey)
|
||||
assert.NoError(t, err, "Error when setting up test - unable to convert after to tls.Certificate")
|
||||
tests := []struct {
|
||||
// input test vars
|
||||
name string
|
||||
secret *v1.Secret
|
||||
secretErr error
|
||||
cachedCert *tls.Certificate
|
||||
cachedVersion string
|
||||
currentConn *closeWrapper
|
||||
otherConns map[int]*closeWrapper
|
||||
|
||||
// output/result test vars
|
||||
closedConns []int
|
||||
expectedCert *tls.Certificate
|
||||
wantError bool
|
||||
}{
|
||||
{
|
||||
name: "no secret found",
|
||||
secret: nil,
|
||||
secretErr: apiError.NewNotFound(schema.GroupResource{
|
||||
Group: "",
|
||||
Resource: "Secret",
|
||||
}, "testSecret"),
|
||||
currentConn: &closeWrapper{id: 0},
|
||||
otherConns: map[int]*closeWrapper{},
|
||||
|
||||
expectedCert: nil,
|
||||
wantError: true,
|
||||
},
|
||||
{
|
||||
name: "secret found, and is up to date",
|
||||
secret: &v1.Secret{
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
ResourceVersion: "1",
|
||||
Name: "testSecret",
|
||||
Namespace: "test",
|
||||
},
|
||||
Data: map[string][]byte{
|
||||
v1.TLSCertKey: beforeCert,
|
||||
v1.TLSPrivateKeyKey: beforeKey,
|
||||
},
|
||||
},
|
||||
cachedVersion: "1",
|
||||
cachedCert: &beforeTLSCert,
|
||||
currentConn: &closeWrapper{id: 0},
|
||||
otherConns: map[int]*closeWrapper{},
|
||||
|
||||
expectedCert: &beforeTLSCert,
|
||||
wantError: false,
|
||||
},
|
||||
{
|
||||
name: "secret found, is not up to date, but k8s secret is not valid",
|
||||
secret: &v1.Secret{
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
ResourceVersion: "2",
|
||||
Name: "testSecret",
|
||||
Namespace: "test",
|
||||
},
|
||||
Data: map[string][]byte{
|
||||
v1.TLSPrivateKeyKey: []byte("strawberry"),
|
||||
},
|
||||
},
|
||||
cachedVersion: "1",
|
||||
cachedCert: &beforeTLSCert,
|
||||
currentConn: &closeWrapper{id: 0},
|
||||
otherConns: map[int]*closeWrapper{},
|
||||
|
||||
expectedCert: &beforeTLSCert,
|
||||
wantError: false,
|
||||
},
|
||||
{
|
||||
name: "secret found, but is not up to date",
|
||||
secret: &v1.Secret{
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
ResourceVersion: "2",
|
||||
Name: "testSecret",
|
||||
Namespace: "test",
|
||||
},
|
||||
Data: map[string][]byte{
|
||||
v1.TLSCertKey: afterCert,
|
||||
v1.TLSPrivateKeyKey: afterKey,
|
||||
},
|
||||
},
|
||||
cachedVersion: "1",
|
||||
cachedCert: &beforeTLSCert,
|
||||
currentConn: &closeWrapper{id: 0},
|
||||
otherConns: map[int]*closeWrapper{},
|
||||
|
||||
expectedCert: &afterTLSCert,
|
||||
wantError: false,
|
||||
},
|
||||
{
|
||||
name: "secret found, is not up to date, and we have conns using current cert",
|
||||
secret: &v1.Secret{
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
ResourceVersion: "2",
|
||||
Name: "testSecret",
|
||||
Namespace: "test",
|
||||
},
|
||||
Data: map[string][]byte{
|
||||
v1.TLSCertKey: afterCert,
|
||||
v1.TLSPrivateKeyKey: afterKey,
|
||||
},
|
||||
},
|
||||
cachedVersion: "1",
|
||||
cachedCert: &beforeTLSCert,
|
||||
currentConn: &closeWrapper{id: 0},
|
||||
otherConns: map[int]*closeWrapper{
|
||||
1: {
|
||||
id: 1,
|
||||
ready: false,
|
||||
Conn: &fakeConn{},
|
||||
},
|
||||
2: {
|
||||
id: 2,
|
||||
ready: true,
|
||||
Conn: &fakeConn{},
|
||||
},
|
||||
},
|
||||
|
||||
closedConns: []int{2},
|
||||
expectedCert: &afterTLSCert,
|
||||
wantError: false,
|
||||
},
|
||||
}
|
||||
for i := range tests {
|
||||
test := tests[i]
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
testConns := test.otherConns
|
||||
if testConns != nil {
|
||||
testConns[test.currentConn.id] = test.currentConn
|
||||
// make sure our conn is listed as one of the current connections
|
||||
}
|
||||
l := listener{
|
||||
cert: test.cachedCert,
|
||||
version: test.cachedVersion,
|
||||
storage: &MockTLSStorage{
|
||||
Secret: test.secret,
|
||||
SecretErr: test.secretErr,
|
||||
},
|
||||
conns: testConns,
|
||||
}
|
||||
for _, conn := range testConns {
|
||||
conn.l = &l
|
||||
}
|
||||
newCert, err := l.getCertificate(&tls.ClientHelloInfo{Conn: test.currentConn})
|
||||
if test.wantError {
|
||||
assert.Errorf(t, err, "expected an error but none was provdied")
|
||||
} else {
|
||||
assert.NoError(t, err, "did not expect an error but got one")
|
||||
}
|
||||
assert.Equal(t, test.expectedCert, newCert, "expected cert did not match actual cert")
|
||||
if test.expectedCert != nil && test.wantError == false && test.currentConn != nil && test.otherConns != nil {
|
||||
assert.True(t, test.currentConn.ready, "expected connection to be ready but it was not")
|
||||
} else {
|
||||
if test.currentConn != nil {
|
||||
assert.False(t, test.currentConn.ready, "did not expect connection to be ready")
|
||||
}
|
||||
}
|
||||
for _, closedConn := range test.closedConns {
|
||||
_, ok := l.conns[closedConn]
|
||||
assert.False(t, ok, "closed conns should not be found")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func newCertificate() ([]byte, []byte, error) {
|
||||
cert, key, err := factory.GenCA()
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
return factory.MarshalChain(key, cert)
|
||||
}
|
||||
|
||||
type MockTLSStorage struct {
|
||||
Secret *v1.Secret
|
||||
SecretErr error
|
||||
}
|
||||
|
||||
func (m *MockTLSStorage) Get() (*v1.Secret, error) {
|
||||
return m.Secret, m.SecretErr
|
||||
}
|
||||
|
||||
func (m *MockTLSStorage) Update(secret *v1.Secret) error {
|
||||
panic("Not implemented")
|
||||
}
|
||||
|
||||
// adapted from k8s.io/apimachinery@v0.18.8/pkg/util.proxy/ugradeaware_test.go
|
||||
type fakeConn struct{}
|
||||
|
||||
func (f *fakeConn) Read([]byte) (int, error) { return 0, nil }
|
||||
func (f *fakeConn) Write([]byte) (int, error) { return 0, nil }
|
||||
func (f *fakeConn) Close() error { return nil }
|
||||
func (fakeConn) LocalAddr() net.Addr { return nil }
|
||||
func (fakeConn) RemoteAddr() net.Addr { return nil }
|
||||
func (fakeConn) SetDeadline(t time.Time) error { return nil }
|
||||
func (fakeConn) SetReadDeadline(t time.Time) error { return nil }
|
||||
func (fakeConn) SetWriteDeadline(t time.Time) error { return nil }
|
@@ -21,6 +21,8 @@ import (
|
||||
)
|
||||
|
||||
type ListenOpts struct {
|
||||
CAChain []*x509.Certificate
|
||||
// Deprecated: Use CAChain instead
|
||||
CA *x509.Certificate
|
||||
CAKey crypto.Signer
|
||||
Storage dynamiclistener.TLSStorage
|
||||
@@ -132,7 +134,7 @@ func getTLSListener(ctx context.Context, tcp net.Listener, handler http.Handler,
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
listener, dynHandler, err := dynamiclistener.NewListener(tcp, storage, caCert, caKey, opts.TLSListenerConfig)
|
||||
listener, dynHandler, err := dynamiclistener.NewListenerWithChain(tcp, storage, caCert, caKey, opts.TLSListenerConfig)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
@@ -140,13 +142,17 @@ func getTLSListener(ctx context.Context, tcp net.Listener, handler http.Handler,
|
||||
return listener, wrapHandler(dynHandler, handler), nil
|
||||
}
|
||||
|
||||
func getCA(opts ListenOpts) (*x509.Certificate, crypto.Signer, error) {
|
||||
if opts.CA != nil && opts.CAKey != nil {
|
||||
return opts.CA, opts.CAKey, nil
|
||||
func getCA(opts ListenOpts) ([]*x509.Certificate, crypto.Signer, error) {
|
||||
if opts.CAKey != nil {
|
||||
if opts.CAChain != nil {
|
||||
return opts.CAChain, opts.CAKey, nil
|
||||
} else if opts.CA != nil {
|
||||
return []*x509.Certificate{opts.CA}, opts.CAKey, nil
|
||||
}
|
||||
}
|
||||
|
||||
if opts.Secrets == nil {
|
||||
return factory.LoadOrGenCA()
|
||||
return factory.LoadOrGenCAChain()
|
||||
}
|
||||
|
||||
if opts.CAName == "" {
|
||||
@@ -161,7 +167,7 @@ func getCA(opts ListenOpts) (*x509.Certificate, crypto.Signer, error) {
|
||||
opts.CANamespace = "kube-system"
|
||||
}
|
||||
|
||||
return kubernetes.LoadOrGenCA(opts.Secrets, opts.CANamespace, opts.CAName)
|
||||
return kubernetes.LoadOrGenCAChain(opts.Secrets, opts.CANamespace, opts.CAName)
|
||||
}
|
||||
|
||||
func newStorage(ctx context.Context, opts ListenOpts) dynamiclistener.TLSStorage {
|
||||
|
@@ -11,12 +11,21 @@ import (
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
)
|
||||
|
||||
// Deprecated: Use LoadOrGenCAChain instead as it supports intermediate CAs
|
||||
func LoadOrGenCA(secrets v1controller.SecretClient, namespace, name string) (*x509.Certificate, crypto.Signer, error) {
|
||||
chain, signer, err := LoadOrGenCAChain(secrets, namespace, name)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
return chain[0], signer, err
|
||||
}
|
||||
|
||||
func LoadOrGenCAChain(secrets v1controller.SecretClient, namespace, name string) ([]*x509.Certificate, crypto.Signer, error) {
|
||||
secret, err := getSecret(secrets, namespace, name)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
return factory.LoadCA(secret.Data[v1.TLSCertKey], secret.Data[v1.TLSPrivateKeyKey])
|
||||
return factory.LoadCAChain(secret.Data[v1.TLSCertKey], secret.Data[v1.TLSPrivateKeyKey])
|
||||
}
|
||||
|
||||
func LoadOrGenClient(secrets v1controller.SecretClient, namespace, name, cn string, ca *x509.Certificate, key crypto.Signer) (*x509.Certificate, crypto.Signer, error) {
|
||||
|
Reference in New Issue
Block a user