diff --git a/README.md b/README.md index a038c4b..43b451c 100644 --- a/README.md +++ b/README.md @@ -6,10 +6,10 @@ This branch contains the compatibility runtime used by PastureStack Server to op ## Runtime image -The maintained runtime release for PastureStack HAProxy load-balancer services is `v0.9.37`. It uses HAProxy 3.5.0 with AWS-LC 5.15.0 and Lua 5.4.8. +The maintained runtime release for PastureStack HAProxy load-balancer services is `v0.9.38`. It uses HAProxy 3.5.0 with AWS-LC 5.15.0 and Lua 5.4.8. ```text -ghcr.io/pasturestack/load-balancer-service:v0.9.37 +ghcr.io/pasturestack/load-balancer-service:v0.9.38 ``` The image is intended to be managed by PastureStack Server, not started by itself: @@ -17,7 +17,7 @@ the control plane supplies metadata, API credentials, service links, port rules, and health-check configuration. Selecting this release does not itself upgrade an existing Server installation or its load-balancer services. -The [release page](https://github.com/PastureStack/load-balancer-controller/releases/tag/v0.9.37) +The [release page](https://github.com/PastureStack/load-balancer-controller/releases/tag/v0.9.38) provides the manifest digest, controller archive, SBOMs, checksums, and build provenance. HAProxy links AWS-LC statically. Runtime tools such as curl use Alpine's OpenSSL packages. @@ -48,6 +48,18 @@ It also accepts the generic `CATTLE_ACCESS_KEY` and `CATTLE_SECRET_KEY` pair use The HAProxy logging helper keeps its configuration under the standard `/etc/rsyslog.d` path and does not require a daemon PID file. Logging initialization is validated independently before HAProxy configuration is applied. +### Certificate renewal + +For API-managed certificates, the controller checks only certificates referenced +by its load balancer every 30 seconds (or the configured certificate polling +interval). Changes to the certificate, private key, or chain schedule the normal +configuration apply queue, without requiring a service edit or restart. +Failed, incomplete, or ambiguous reads retain the running configuration and are +retried; failed configuration application uses the existing retry queue. +Certificate material stays in memory and is not logged. Mounted certificate +directories retain their existing polling behavior. The watcher stops with the +controller. + ### Drain weight recovery The controller records each backend's runtime weight before setting it to zero diff --git a/controller/rancher/certificate_fetcher.go b/controller/rancher/certificate_fetcher.go index 25be34c..c0cd4ac 100644 --- a/controller/rancher/certificate_fetcher.go +++ b/controller/rancher/certificate_fetcher.go @@ -23,7 +23,7 @@ const ( type CertificateFetcher interface { FetchCertificates(lbMeta *LBMetadata, isDefaultCert bool) ([]*config.Certificate, error) UpdateEndpoints(lbSvc *metadata.Service, eps []client.PublicEndpoint) error - LookForCertUpdates(do func(string)) + LookForCertUpdates(do func(string), stop <-chan struct{}) } type RCertificateFetcher struct { @@ -46,6 +46,9 @@ type RCertificateFetcher struct { initPollDone bool initPollMu *sync.RWMutex + + apiCertMu sync.Mutex + apiCerts map[string]*config.Certificate } func (fetcher *RCertificateFetcher) checkIfInitPollDone() bool { @@ -95,6 +98,7 @@ func (fetcher *RCertificateFetcher) FetchCertificates(lbMeta *LBMetadata, isDefa } } } else { + fetcher.trackRancherCertificateNames(lbMeta) if !isDefaultCert { for _, certName := range lbMeta.Certs { cert, err := fetcher.FetchRancherCertificate(certName) @@ -121,6 +125,19 @@ func (fetcher *RCertificateFetcher) FetchCertificates(lbMeta *LBMetadata, isDefa } func (fetcher *RCertificateFetcher) FetchRancherCertificate(certName string) (*config.Certificate, error) { + cert, err := fetcher.fetchRancherCertificate(certName) + if err == nil && cert != nil { + fetcher.apiCertMu.Lock() + if _, tracked := fetcher.apiCerts[certName]; tracked { + copy := *cert + fetcher.apiCerts[certName] = © + } + fetcher.apiCertMu.Unlock() + } + return cert, err +} + +func (fetcher *RCertificateFetcher) fetchRancherCertificate(certName string) (*config.Certificate, error) { if certName == "" { return nil, nil } @@ -132,12 +149,14 @@ func (fetcher *RCertificateFetcher) FetchRancherCertificate(certName string) (*c if err != nil { return nil, fmt.Errorf("Coudln't get certificate by name [%s]. Error: %#v", certName, err) } - var cert client.Certificate - var certWithChain string - if len(certs.Data) >= 1 { - cert = certs.Data[0] - certWithChain = fmt.Sprintf("%s\n%s", cert.Cert, cert.CertChain) + if len(certs.Data) != 1 { + return nil, fmt.Errorf("expected one active certificate named %q", certName) + } + cert := certs.Data[0] + if cert.Name != certName || strings.TrimSpace(cert.Cert) == "" || strings.TrimSpace(cert.Key) == "" { + return nil, fmt.Errorf("certificate %q is incomplete", certName) } + certWithChain := fmt.Sprintf("%s\n%s", cert.Cert, cert.CertChain) return &config.Certificate{ Name: cert.Name, Key: cert.Key, @@ -145,6 +164,43 @@ func (fetcher *RCertificateFetcher) FetchRancherCertificate(certName string) (*c }, nil } +// Track only the certificates referenced by this LB, never the environment's +// complete secret inventory. Values stay in memory and are never logged. +func (fetcher *RCertificateFetcher) trackRancherCertificateNames(meta *LBMetadata) { + fetcher.apiCertMu.Lock() + defer fetcher.apiCertMu.Unlock() + next := make(map[string]*config.Certificate) + names := append([]string{meta.DefaultCert}, meta.Certs...) + for _, name := range names { + if name != "" { + next[name] = fetcher.apiCerts[name] + } + } + fetcher.apiCerts = next +} + +// A failed/incomplete read cannot replace a usable certificate or acknowledge a +// change. FetchCertificates refreshes the baseline on the normal apply path. +func (fetcher *RCertificateFetcher) pollRancherCertificates(read func(string) (*config.Certificate, error)) bool { + fetcher.apiCertMu.Lock() + previous := make(map[string]config.Certificate) + for name, cert := range fetcher.apiCerts { + if cert != nil { + previous[name] = *cert + } + } + fetcher.apiCertMu.Unlock() + changed := false + for name, before := range previous { + after, err := read(name) + if err != nil || after == nil || after.Name != name || after.Key == "" || after.Cert == "" { + return false + } + changed = changed || before != *after + } + return changed +} + func (fetcher *RCertificateFetcher) UpdateEndpoints(lbSvc *metadata.Service, eps []client.PublicEndpoint) error { opts := client.NewListOpts() opts.Filters["uuid"] = lbSvc.UUID @@ -206,26 +262,50 @@ func (fetcher *RCertificateFetcher) ReadDefaultCertificate(defaultCertDir string return currentDefCert } -func (fetcher *RCertificateFetcher) LookForCertUpdates(doOnUpdate func(string)) { - if fetcher.CertDir != "" || fetcher.DefaultCertDir != "" { - lastUpdated := time.Now() - for { - log.Debugf("Start --- LookForCertUpdates polling cert dir %v and default cert dir %v", fetcher.CertDir, fetcher.DefaultCertDir) - log.Debugf("lastUpdated %v", lastUpdated) +func (fetcher *RCertificateFetcher) LookForCertUpdates(doOnUpdate func(string), stop <-chan struct{}) { + interval := fetcher.updateCheckInterval + if interval <= 0 { + interval = 30 + } + ticker := time.NewTicker(time.Duration(interval) * time.Second) + defer ticker.Stop() + lastUpdated := time.Now() + for { + select { + case <-stop: + return + default: + } + log.Debugf("Start --- LookForCertUpdates polling cert dir %v and default cert dir %v", fetcher.CertDir, fetcher.DefaultCertDir) + log.Debugf("lastUpdated %v", lastUpdated) - forceUpdate := time.Since(lastUpdated).Seconds() >= fetcher.forceUpdateInterval - if forceUpdate { - log.Infof("LookForCertUpdates: Executing force update as certs in cache have not been updated in: %v seconds", fetcher.forceUpdateInterval) - } + forceUpdate := time.Since(lastUpdated).Seconds() >= fetcher.forceUpdateInterval + if forceUpdate { + log.Infof("LookForCertUpdates: Executing force update as certs in cache have not been updated in: %v seconds", fetcher.forceUpdateInterval) + } - if fetcher.pollCertificateDirectories(forceUpdate) { - //scheduleApplyConfig - doOnUpdate("") - lastUpdated = time.Now() + changed := false + if fetcher.CertDir != "" || fetcher.DefaultCertDir != "" { + changed = fetcher.pollCertificateDirectories(forceUpdate) + } else { + changed = fetcher.pollRancherCertificates(fetcher.fetchRancherCertificate) + } + if changed { + select { + case <-stop: + return + default: } + //scheduleApplyConfig + doOnUpdate("") + lastUpdated = time.Now() + } - log.Debug("Done --- LookForCertUpdates poll") - time.Sleep(time.Duration(fetcher.updateCheckInterval) * time.Second) + log.Debug("Done --- LookForCertUpdates poll") + select { + case <-stop: + return + case <-ticker.C: } } } diff --git a/controller/rancher/certificate_rotation_test.go b/controller/rancher/certificate_rotation_test.go new file mode 100644 index 0000000..22a4433 --- /dev/null +++ b/controller/rancher/certificate_rotation_test.go @@ -0,0 +1,186 @@ +package rancher + +import ( + "errors" + "reflect" + "sync" + "testing" + + "github.com/PastureStack/load-balancer-controller/config" + "github.com/PastureStack/load-balancer-controller/internal/rancherclient/v2" +) + +type rotationCertificates struct { + client.CertificateOperations + list func(*client.ListOpts) (*client.CertificateCollection, error) +} + +func (c rotationCertificates) List(opts *client.ListOpts) (*client.CertificateCollection, error) { + return c.list(opts) +} + +func rotationFetcher(t *testing.T) (*RCertificateFetcher, *client.Certificate, *int) { + t.Helper() + value := &client.Certificate{Name: "used", Key: "key-a", Cert: "cert-a", CertChain: "chain-a"} + calls := new(int) + fetcher := &RCertificateFetcher{Client: &client.RancherClient{}} + fetcher.Client.Certificate = rotationCertificates{list: func(opts *client.ListOpts) (*client.CertificateCollection, error) { + *calls++ + if opts.Filters["name"] != "used" || opts.Filters["removed_null"] != "1" { + t.Fatal("query escaped the referenced active certificate") + } + return &client.CertificateCollection{Data: []client.Certificate{*value}}, nil + }} + if _, err := fetcher.FetchCertificates(&LBMetadata{DefaultCert: "used"}, true); err != nil { + t.Fatal(err) + } + return fetcher, value, calls +} + +func TestAPICertificateRotationWithoutMetadataChange(t *testing.T) { + for _, field := range []string{"certificate", "key", "chain"} { + t.Run(field, func(t *testing.T) { + fetcher, value, _ := rotationFetcher(t) + if fetcher.pollRancherCertificates(fetcher.fetchRancherCertificate) { + t.Fatal("unchanged certificate scheduled an update") + } + switch field { + case "certificate": + value.Cert = "cert-b" + case "key": + value.Key = "key-b" + case "chain": + value.CertChain = "chain-b" + } + for i := 0; i < 2; i++ { + if !fetcher.pollRancherCertificates(fetcher.fetchRancherCertificate) { + t.Fatal("rotation lost before normal configuration fetch") + } + } + if _, err := fetcher.FetchCertificates(&LBMetadata{DefaultCert: "used"}, true); err != nil { + t.Fatal(err) + } + if fetcher.pollRancherCertificates(fetcher.fetchRancherCertificate) { + t.Fatal("applied read kept scheduling identical material") + } + }) + } +} + +func TestAPICertificateReadFailureKeepsBaselineAndRetries(t *testing.T) { + fetcher, value, _ := rotationFetcher(t) + before := *fetcher.apiCerts["used"] + bad := []func(string) (*config.Certificate, error){ + func(string) (*config.Certificate, error) { return nil, errors.New("unavailable") }, + func(string) (*config.Certificate, error) { return nil, nil }, + func(string) (*config.Certificate, error) { return &config.Certificate{Name: "used", Cert: "new"}, nil }, + func(string) (*config.Certificate, error) { + return &config.Certificate{Name: "other", Cert: "new", Key: "key"}, nil + }, + } + for _, read := range bad { + if fetcher.pollRancherCertificates(read) || *fetcher.apiCerts["used"] != before { + t.Fatal("failed read changed usable certificate") + } + } + value.Cert = "recovered" + if !fetcher.pollRancherCertificates(fetcher.fetchRancherCertificate) { + t.Fatal("recovery was not retried") + } +} + +func TestAPICertificateMissingOrAmbiguousMaterialRejected(t *testing.T) { + fetcher, _, _ := rotationFetcher(t) + before := *fetcher.apiCerts["used"] + for _, data := range [][]client.Certificate{nil, {{Name: "used", Key: "key"}}, {{Name: "other", Key: "key", Cert: "cert"}}, {{Name: "used", Key: "key", Cert: "cert"}, {Name: "used", Key: "key", Cert: "cert"}}} { + fetcher.Client.Certificate = rotationCertificates{list: func(*client.ListOpts) (*client.CertificateCollection, error) { + return &client.CertificateCollection{Data: data}, nil + }} + if _, err := fetcher.FetchRancherCertificate("used"); err == nil { + t.Fatal("missing/ambiguous material accepted") + } + if *fetcher.apiCerts["used"] != before { + t.Fatal("bad material replaced the baseline") + } + } +} + +func TestAPICertificateWatchTracksOnlyCurrentReferences(t *testing.T) { + fetcher, _, _ := rotationFetcher(t) + fetcher.trackRancherCertificateNames(&LBMetadata{DefaultCert: "used", Certs: []string{"used", "new"}}) + var queried []string + fetcher.pollRancherCertificates(func(name string) (*config.Certificate, error) { + queried = append(queried, name) + return fetcher.apiCerts[name], nil + }) + if !reflect.DeepEqual(queried, []string{"used"}) { + t.Fatal("unadopted or unreferenced secret was queried") + } + fetcher.trackRancherCertificateNames(&LBMetadata{}) + if fetcher.pollRancherCertificates(func(string) (*config.Certificate, error) { t.Fatal("removed reference queried"); return nil, nil }) { + t.Fatal("removed reference scheduled apply") + } +} + +func TestAPICertificateRotationSchedulesExistingApplyQueue(t *testing.T) { + fetcher, value, calls := rotationFetcher(t) + value.Cert = "rotated" + stop := make(chan struct{}) + scheduled := 0 + fetcher.LookForCertUpdates(func(string) { scheduled++; close(stop) }, stop) + if scheduled != 1 || *calls != 2 { + t.Fatal("rotation did not schedule exactly one normal apply") + } +} + +func TestAPICertificateWatcherStopsWithoutReadingOrScheduling(t *testing.T) { + fetcher, _, calls := rotationFetcher(t) + stop := make(chan struct{}) + close(stop) + fetcher.LookForCertUpdates(func(string) { t.Fatal("stopped watcher scheduled apply") }, stop) + if *calls != 1 { + t.Fatal("stopped watcher queried API") + } +} + +func TestAPICertificatePollConcurrentReferenceRemoval(t *testing.T) { + fetcher, _, _ := rotationFetcher(t) + started, proceed, finished := make(chan struct{}), make(chan struct{}), make(chan struct{}) + go func() { + defer close(finished) + fetcher.pollRancherCertificates(func(string) (*config.Certificate, error) { + close(started) + <-proceed + return &config.Certificate{Name: "used", Key: "new", Cert: "new"}, nil + }) + }() + <-started + fetcher.trackRancherCertificateNames(&LBMetadata{}) + close(proceed) + <-finished + if len(fetcher.apiCerts) != 0 { + t.Fatal("late poll resurrected a removed reference") + } +} + +func TestAPICertificateConcurrentFetchAndPoll(t *testing.T) { + fetcher, _, _ := rotationFetcher(t) + // All API responses are immutable; exercise only the fetcher's shared state. + fetcher.Client.Certificate = rotationCertificates{list: func(*client.ListOpts) (*client.CertificateCollection, error) { + return &client.CertificateCollection{Data: []client.Certificate{{Name: "used", Key: "key-a", Cert: "cert-a", CertChain: "chain-a"}}}, nil + }} + var wg sync.WaitGroup + for i := 0; i < 2; i++ { + wg.Add(1) + go func() { + defer wg.Done() + for j := 0; j < 100; j++ { + if _, err := fetcher.FetchCertificates(&LBMetadata{DefaultCert: "used"}, true); err != nil { + t.Error(err) + } + fetcher.pollRancherCertificates(fetcher.fetchRancherCertificate) + } + }() + } + wg.Wait() +} diff --git a/controller/rancher/rancher.go b/controller/rancher/rancher.go index a9441fa..9ea62b8 100644 --- a/controller/rancher/rancher.go +++ b/controller/rancher/rancher.go @@ -209,7 +209,7 @@ func (lbc *LoadBalancerController) Run(provider provider.LBProvider) { } }() - go lbc.CertFetcher.LookForCertUpdates(lbc.ScheduleApplyConfig) + go lbc.CertFetcher.LookForCertUpdates(lbc.ScheduleApplyConfig, lbc.stopCh) lbc.MetaFetcher.OnChange(5, lbc.ScheduleApplyConfig) <-lbc.stopCh diff --git a/controller/rancher/rancher_regions_test.go b/controller/rancher/rancher_regions_test.go index bf7816b..f2b74f1 100644 --- a/controller/rancher/rancher_regions_test.go +++ b/controller/rancher/rancher_regions_test.go @@ -383,7 +383,7 @@ func (cf sCertFetcher) ReadDefaultCertificate(defaultCertDir string) *config.Cer return nil } -func (cf sCertFetcher) LookForCertUpdates(do func(string)) { +func (cf sCertFetcher) LookForCertUpdates(do func(string), stop <-chan struct{}) { } func (p *sProvider) ApplyConfig(lbConfig *config.LoadBalancerConfig) error { diff --git a/controller/rancher/rancher_test.go b/controller/rancher/rancher_test.go index 7c728a3..9bfe7a1 100644 --- a/controller/rancher/rancher_test.go +++ b/controller/rancher/rancher_test.go @@ -776,7 +776,7 @@ func (cf tCertFetcher) ReadDefaultCertificate(defaultCertDir string) *config.Cer return nil } -func (cf tCertFetcher) LookForCertUpdates(do func(string)) { +func (cf tCertFetcher) LookForCertUpdates(do func(string), stop <-chan struct{}) { } func (p *tProvider) ApplyConfig(lbConfig *config.LoadBalancerConfig) error { diff --git a/scripts/check-certificate-test-coverage.py b/scripts/check-certificate-test-coverage.py new file mode 100644 index 0000000..0e31e1b --- /dev/null +++ b/scripts/check-certificate-test-coverage.py @@ -0,0 +1,30 @@ +"""Require executed API-certificate rotation regressions, not a green empty run.""" +import json +import sys + +PACKAGE = "github.com/PastureStack/load-balancer-controller/controller/rancher" +REQUIRED = { + "TestAPICertificateRotationWithoutMetadataChange", + "TestAPICertificateReadFailureKeepsBaselineAndRetries", + "TestAPICertificateMissingOrAmbiguousMaterialRejected", + "TestAPICertificateWatchTracksOnlyCurrentReferences", + "TestAPICertificateRotationSchedulesExistingApplyQueue", + "TestAPICertificateWatcherStopsWithoutReadingOrScheduling", + "TestAPICertificatePollConcurrentReferenceRemoval", + "TestAPICertificateConcurrentFetchAndPoll", +} + + +def check(lines): + events = [json.loads(line) for line in lines if line.strip()] + passed = {e.get("Test") for e in events if e.get("Package") == PACKAGE and e.get("Action") == "pass"} + assert not any(e.get("Action") in ("fail", "skip") and + (e.get("Action") == "fail" or e.get("Test") in REQUIRED) for e in events), "failed/skipped regression" + assert REQUIRED <= passed, "missing executed certificate regressions: " + str(sorted(REQUIRED - passed)) + assert any(e.get("Package") == PACKAGE and e.get("Action") == "pass" and not e.get("Test") for e in events), "package did not complete" + return len(REQUIRED) + + +if __name__ == "__main__": + with open(sys.argv[1], encoding="utf-8") as stream: + print("Executed certificate rotation regressions:", check(stream)) diff --git a/scripts/test b/scripts/test index 20ad500..734abcd 100755 --- a/scripts/test +++ b/scripts/test @@ -7,7 +7,11 @@ cd "${root_dir}" race_flag=() python3 scripts/test-haproxy-identity.py python3 scripts/test-alpine-package-pins.py +python3 scripts/test-certificate-test-coverage.py if [[ "${ARCH:-amd64}" == "amd64" ]]; then race_flag=(-race) fi -go test -mod=vendor "${race_flag[@]}" -cover -tags=test ./... +report="$(mktemp)" +trap 'rm -f "$report"' EXIT +go test -mod=vendor "${race_flag[@]}" -json -cover -tags=test ./... | tee "$report" +python3 scripts/check-certificate-test-coverage.py "$report" diff --git a/scripts/test-certificate-test-coverage.py b/scripts/test-certificate-test-coverage.py new file mode 100644 index 0000000..d6533b6 --- /dev/null +++ b/scripts/test-certificate-test-coverage.py @@ -0,0 +1,30 @@ +import importlib.util +import json +from pathlib import Path +import unittest + +spec = importlib.util.spec_from_file_location("coverage", Path(__file__).with_name("check-certificate-test-coverage.py")) +coverage = importlib.util.module_from_spec(spec) +spec.loader.exec_module(coverage) + + +class CoverageTest(unittest.TestCase): + def events(self): + return [{"Package": coverage.PACKAGE, "Test": name, "Action": "pass"} for name in coverage.REQUIRED] + [{"Package": coverage.PACKAGE, "Action": "pass"}] + + def run_events(self, events): + return coverage.check(map(json.dumps, events)) + + def test_complete(self): + self.assertEqual(self.run_events(self.events()), 8) + + def test_empty_filtered_or_other_package(self): + for events in ([], self.events()[1:], [dict(e, Package="other") for e in self.events()]): + with self.assertRaises(AssertionError): self.run_events(events) + + def test_failure_skip_or_missing_package_completion(self): + for events in (self.events()[:-1], self.events() + [{"Action": "fail"}], self.events() + [{"Test": next(iter(coverage.REQUIRED)), "Action": "skip"}]): + with self.assertRaises(AssertionError): self.run_events(events) + + +if __name__ == "__main__": unittest.main()