diff --git a/test/tls_rotation/tls_rotation_integration_test.go b/test/tls_rotation/tls_rotation_integration_test.go index e57a69a3a6..1001a3832e 100644 --- a/test/tls_rotation/tls_rotation_integration_test.go +++ b/test/tls_rotation/tls_rotation_integration_test.go @@ -145,6 +145,104 @@ func TestMasterHTTPSCertRotation(t *testing.T) { waitForCert(t, addr, caPool, leafSerial2, 15*time.Second, "rotated cert") } +// TestMasterHTTPSCertRotationOnSIGHUP is the same rotation flow as +// TestMasterHTTPSCertRotation, but with a one-hour refresh window and a +// SIGHUP instead of waiting for the periodic tick. It verifies the +// grace.OnReload hook forces certreload providers to re-read cert/key +// immediately. +func TestMasterHTTPSCertRotationOnSIGHUP(t *testing.T) { + if testing.Short() { + t.Skip("skipping HTTPS rotation integration test in -short mode") + } + + weedBin := findWeedBinary(t) + + dir := t.TempDir() + tlsDir := filepath.Join(dir, "tls") + if err := os.MkdirAll(tlsDir, 0o755); err != nil { + t.Fatalf("mkdir tls: %v", err) + } + certPath := filepath.Join(tlsDir, "server.crt") + keyPath := filepath.Join(tlsDir, "server.key") + + ca, caKey := generateCA(t) + leafSerial1 := big.NewInt(20001) + leafSerial2 := big.NewInt(20002) + + writeLeaf(t, certPath, keyPath, ca, caKey, leafSerial1) + + masterDir := filepath.Join(dir, "master") + if err := os.MkdirAll(masterDir, 0o755); err != nil { + t.Fatalf("mkdir master: %v", err) + } + if err := os.WriteFile(filepath.Join(masterDir, "security.toml"), []byte("# test\n"), 0o644); err != nil { + t.Fatalf("write security.toml: %v", err) + } + + port, grpcPort := getFreeTCPPort(t), getFreeTCPPort(t) + ctx, cancel := context.WithTimeout(context.Background(), 90*time.Second) + defer cancel() + + cmd := exec.CommandContext(ctx, weedBin, "master", + "-ip", "127.0.0.1", + "-port", strconv.Itoa(port), + "-port.grpc", strconv.Itoa(grpcPort), + "-mdir", masterDir, + ) + cmd.Dir = masterDir + cmd.Env = append(os.Environ(), + "HOME="+dir, + "WEED_HTTPS_MASTER_CERT="+certPath, + "WEED_HTTPS_MASTER_KEY="+keyPath, + // Keep the periodic refresh out of the way: the new cert must + // appear because of SIGHUP, not because of a tick. + "WEED_TLS_CERT_REFRESH_INTERVAL=1h", + ) + logPath := filepath.Join(masterDir, "master.log") + logOut, err := os.Create(logPath) + if err != nil { + t.Fatalf("create master log: %v", err) + } + cmd.Stdout = logOut + cmd.Stderr = logOut + + if err := cmd.Start(); err != nil { + t.Fatalf("start master: %v", err) + } + t.Cleanup(func() { + if cmd.Process != nil { + _ = cmd.Process.Signal(syscall.SIGTERM) + done := make(chan struct{}) + go func() { _ = cmd.Wait(); close(done) }() + select { + case <-done: + case <-time.After(10 * time.Second): + _ = cmd.Process.Kill() + <-done + } + } + _ = logOut.Close() + if t.Failed() { + if b, readErr := os.ReadFile(logPath); readErr == nil { + t.Logf("master.log:\n%s", string(b)) + } + } + }) + + caPool := x509.NewCertPool() + caPool.AddCert(ca) + addr := fmt.Sprintf("127.0.0.1:%d", port) + + waitForCert(t, addr, caPool, leafSerial1, 30*time.Second, "initial cert") + + writeLeaf(t, certPath, keyPath, ca, caKey, leafSerial2) + if err := cmd.Process.Signal(syscall.SIGHUP); err != nil { + t.Fatalf("send SIGHUP: %v", err) + } + + waitForCert(t, addr, caPool, leafSerial2, 10*time.Second, "rotated cert after SIGHUP") +} + // waitForCert polls until a TLS handshake against addr yields a peer // cert with the expected serial, or fails the test at the deadline. // The last handshake error is surfaced in the fatal message so that a diff --git a/weed/security/certreload/certreload.go b/weed/security/certreload/certreload.go index c0288198e2..704a2b1cac 100644 --- a/weed/security/certreload/certreload.go +++ b/weed/security/certreload/certreload.go @@ -1,6 +1,8 @@ -// Package certreload wraps grpc's pemfile.Provider so both TLS servers -// (weed/security) and TLS clients (weed/util/http/client) can share one -// reloading cert implementation without an import cycle between them. +// Package certreload provides a reloadable PEM certificate provider for +// both TLS servers (weed/security) and TLS clients +// (weed/util/http/client). It re-reads cert/key/CA files on a timer and +// can be forced to reload immediately (e.g. on SIGHUP) without restarting +// the process. // // Lives in its own subpackage because weed/security already imports // weed/util/http/client (for LoadHTTPClientFromFile). @@ -14,7 +16,6 @@ import ( "time" "google.golang.org/grpc/credentials/tls/certprovider" - "google.golang.org/grpc/credentials/tls/certprovider/pemfile" ) // RefreshIntervalEnv names an environment variable that overrides the @@ -24,10 +25,9 @@ import ( // with short-lived certs (e.g. Vault-issued). const RefreshIntervalEnv = "WEED_TLS_CERT_REFRESH_INTERVAL" -// DefaultRefreshInterval is the cadence at which the pemfile provider -// stats cert/key files on disk. It re-parses only when mtime/contents -// change, so the hot path (KeyMaterial() on each TLS handshake) stays -// cheap. +// DefaultRefreshInterval is the cadence at which the provider re-reads +// cert/key files from disk. The hot path (KeyMaterial() on each TLS +// handshake) returns the cached material, so it stays cheap. // // 5 hours matches the prior constant used for gRPC mTLS. Resolved once // at process start from RefreshIntervalEnv if set. @@ -44,9 +44,9 @@ func resolveRefreshInterval(fallback time.Duration) time.Duration { // NewServerGetCertificate returns a callback suitable for // tls.Config.GetCertificate. It reloads certFile and keyFile from disk -// on each refresh tick so rotated certs (e.g. from k8s cert-manager) -// are picked up without a restart. Caller should Close() the returned -// provider at shutdown. +// on each refresh tick, and immediately on SIGHUP, so rotated certs +// (e.g. from k8s cert-manager) are picked up without a restart. Caller +// should Close() the returned provider at shutdown. func NewServerGetCertificate(certFile, keyFile string) (func(*tls.ClientHelloInfo) (*tls.Certificate, error), certprovider.Provider, error) { return newServerGetCertificate(certFile, keyFile, DefaultRefreshInterval) } @@ -57,9 +57,8 @@ func newServerGetCertificate(certFile, keyFile string, refresh time.Duration) (f return nil, nil, err } get := func(hello *tls.ClientHelloInfo) (*tls.Certificate, error) { - // KeyMaterial blocks until the pemfile provider has read the files - // for the first time. Use the handshake context so a stuck read - // bounds the handshake instead of hanging it forever. + // KeyMaterial reads the files on first use; later calls return the + // cached material until the next refresh. ctx := context.Background() if hello != nil { ctx = hello.Context() @@ -72,7 +71,8 @@ func newServerGetCertificate(certFile, keyFile string, refresh time.Duration) (f // NewClientGetCertificate returns a callback suitable for // tls.Config.GetClientCertificate. Fires per TLS handshake, so long-lived // HTTPS clients (FUSE mount, backup, filer→volume, etc.) pick up rotated -// client mTLS certs as pooled connections recycle. +// client mTLS certs as pooled connections recycle, and immediately after +// a SIGHUP. func NewClientGetCertificate(certFile, keyFile string) (func(*tls.CertificateRequestInfo) (*tls.Certificate, error), certprovider.Provider, error) { return newClientGetCertificate(certFile, keyFile, DefaultRefreshInterval) } @@ -96,13 +96,13 @@ func newProvider(certFile, keyFile string, refresh time.Duration) (certprovider. if certFile == "" || keyFile == "" { return nil, fmt.Errorf("both certFile and keyFile are required") } - provider, err := pemfile.NewProvider(pemfile.Options{ + provider, err := NewProvider(Options{ CertFile: certFile, KeyFile: keyFile, RefreshDuration: refresh, }) if err != nil { - return nil, fmt.Errorf("pemfile.NewProvider: %w", err) + return nil, fmt.Errorf("certreload.NewProvider: %w", err) } return provider, nil } diff --git a/weed/security/certreload/certreload_test.go b/weed/security/certreload/certreload_test.go index 12399d5b00..04ef282fe3 100644 --- a/weed/security/certreload/certreload_test.go +++ b/weed/security/certreload/certreload_test.go @@ -1,6 +1,7 @@ package certreload import ( + "context" "crypto/ecdsa" "crypto/elliptic" "crypto/rand" @@ -12,6 +13,8 @@ import ( "path/filepath" "testing" "time" + + "google.golang.org/grpc/credentials/tls/certprovider" ) // TestServerGetCertificatePicksUpNewFile writes an initial cert/key @@ -45,16 +48,14 @@ func TestServerGetCertificatePicksUpNewFile(t *testing.T) { t.Fatalf("want CN=first, got %q", first.Subject.CommonName) } - // Rotate the files. pemfile watches mtime; sleep so the new files have - // a later mtime even on filesystems with 1s granularity. - time.Sleep(1100 * time.Millisecond) + // Rotate the files; the periodic refresh should pick up the new pair. if err := writeSelfSigned(certPath, keyPath, "second"); err != nil { t.Fatalf("write second cert: %v", err) } - // The pemfile poller can briefly observe a mismatched cert/key pair - // during rotation (cert written before key). Tolerate transient errors - // and only fail at the deadline; keep the last error for diagnostics. + // The refresh can briefly observe a mismatched cert/key pair during + // rotation (cert written before key). Tolerate transient errors and + // only fail at the deadline; keep the last error for diagnostics. var lastErr error deadline := time.Now().Add(5 * time.Second) for time.Now().Before(deadline) { @@ -78,6 +79,118 @@ func TestServerGetCertificatePicksUpNewFile(t *testing.T) { t.Fatalf("reloader did not pick up rotated cert within timeout; last error: %v", lastErr) } +// TestReloadAllPicksUpNewFileImmediately rotates the files and forces a +// reload, asserting that the new material is served right away instead of +// waiting for the periodic tick. +func TestReloadAllPicksUpNewFileImmediately(t *testing.T) { + dir := t.TempDir() + certPath := filepath.Join(dir, "tls.crt") + keyPath := filepath.Join(dir, "tls.key") + + if err := writeSelfSigned(certPath, keyPath, "first"); err != nil { + t.Fatalf("write first cert: %v", err) + } + + provider, err := NewProvider(Options{ + CertFile: certPath, + KeyFile: keyPath, + RefreshDuration: time.Hour, + }) + if err != nil { + t.Fatalf("NewProvider: %v", err) + } + defer provider.Close() + + km, err := provider.KeyMaterial(context.Background()) + if err != nil { + t.Fatalf("initial KeyMaterial: %v", err) + } + if got := leafCommonName(t, km); got != "first" { + t.Fatalf("want CN=first, got %q", got) + } + + if err := writeSelfSigned(certPath, keyPath, "second"); err != nil { + t.Fatalf("write second cert: %v", err) + } + ReloadAll() + + km, err = provider.KeyMaterial(context.Background()) + if err != nil { + t.Fatalf("KeyMaterial after reload: %v", err) + } + if got := leafCommonName(t, km); got != "second" { + t.Fatalf("want CN=second after reload, got %q", got) + } +} + +// TestReloadKeepsOldMaterialOnInvalidFile verifies that a broken rotation +// does not take the listener down: Reload reports the error and the last +// good material is still served. +func TestReloadKeepsOldMaterialOnInvalidFile(t *testing.T) { + dir := t.TempDir() + certPath := filepath.Join(dir, "tls.crt") + keyPath := filepath.Join(dir, "tls.key") + + if err := writeSelfSigned(certPath, keyPath, "first"); err != nil { + t.Fatalf("write first cert: %v", err) + } + + provider, err := NewProvider(Options{ + CertFile: certPath, + KeyFile: keyPath, + RefreshDuration: time.Hour, + }) + if err != nil { + t.Fatalf("NewProvider: %v", err) + } + defer provider.Close() + + good, err := provider.KeyMaterial(context.Background()) + if err != nil { + t.Fatalf("initial KeyMaterial: %v", err) + } + + if err := os.WriteFile(certPath, []byte("not a certificate"), 0o600); err != nil { + t.Fatalf("corrupt cert: %v", err) + } + if err := provider.Reload(); err == nil { + t.Fatal("Reload: expected an error for a corrupt certificate") + } + ReloadAll() + + km, err := provider.KeyMaterial(context.Background()) + if err != nil { + t.Fatalf("KeyMaterial after failed reload: %v", err) + } + if got := leafCommonName(t, km); got != "first" { + t.Fatalf("want old CN=first after failed reload, got %q", got) + } + if leafCommonName(t, good) != "first" { + t.Fatal("previous material was mutated by a failed reload") + } +} + +func TestNewProviderValidatesOptions(t *testing.T) { + if _, err := NewProvider(Options{CertFile: "cert.pem"}); err == nil { + t.Fatal("expected an error for a cert without a key") + } + if _, err := NewProvider(Options{}); err == nil { + t.Fatal("expected an error for an empty options set") + } +} + +func leafCommonName(t *testing.T, km *certprovider.KeyMaterial) string { + t.Helper() + if len(km.Certs) == 0 { + t.Fatal("key material has no certificates") + } + leaf, err := x509.ParseCertificate(km.Certs[0].Certificate[0]) + if err != nil { + t.Fatalf("parse leaf: %v", err) + } + return leaf.Subject.CommonName +} + func writeSelfSigned(certPath, keyPath, commonName string) error { key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) if err != nil { diff --git a/weed/security/certreload/provider.go b/weed/security/certreload/provider.go new file mode 100644 index 0000000000..12351b2138 --- /dev/null +++ b/weed/security/certreload/provider.go @@ -0,0 +1,189 @@ +package certreload + +import ( + "context" + "crypto/tls" + "crypto/x509" + "fmt" + "os" + "sync" + "time" + + "github.com/seaweedfs/seaweedfs/weed/glog" + "google.golang.org/grpc/credentials/tls/certprovider" +) + +// Options configures a reloadable PEM certificate provider. +type Options struct { + // CertFile and KeyFile hold the identity certificate and its private + // key. Both must be set, or neither. + CertFile string + KeyFile string + // RootFile holds the trusted CA certificates. + RootFile string + // RefreshDuration is how often the provider re-reads the files on its + // own. A zero value falls back to DefaultRefreshInterval. + RefreshDuration time.Duration +} + +func (o Options) validate() error { + if (o.CertFile == "") != (o.KeyFile == "") { + return fmt.Errorf("certFile and keyFile must both be set") + } + if o.CertFile == "" && o.RootFile == "" { + return fmt.Errorf("at least one of cert/key or rootFile must be set") + } + return nil +} + +func (o Options) describe() string { + if o.CertFile != "" { + return o.CertFile + " / " + o.KeyFile + } + return o.RootFile +} + +// Provider is a certprovider.Provider backed by PEM files on disk. It keeps +// the current key material in memory, refreshes it on a timer, and can be +// forced to re-read the files with Reload. Providers register themselves so +// ReloadAll can refresh every TLS listener and client in the process on +// SIGHUP. +type Provider struct { + opts Options + + mu sync.RWMutex + km *certprovider.KeyMaterial + + stop chan struct{} + closeOnce sync.Once +} + +var ( + registryMu sync.Mutex + registry = make(map[*Provider]struct{}) +) + +// NewProvider returns a provider that reads the configured files lazily on +// the first KeyMaterial call, matching the behavior of gRPC's pemfile +// provider. The provider must be closed to stop its refresh goroutine. +func NewProvider(opts Options) (*Provider, error) { + if err := opts.validate(); err != nil { + return nil, err + } + if opts.RefreshDuration <= 0 { + opts.RefreshDuration = DefaultRefreshInterval + } + p := &Provider{ + opts: opts, + stop: make(chan struct{}), + } + registryMu.Lock() + registry[p] = struct{}{} + registryMu.Unlock() + go p.run() + return p, nil +} + +// KeyMaterial returns the latest key material. The first call reads the +// files; later calls return the cached value until Reload or the refresh +// timer replaces it. +func (p *Provider) KeyMaterial(ctx context.Context) (*certprovider.KeyMaterial, error) { + p.mu.RLock() + km := p.km + p.mu.RUnlock() + if km != nil { + return km, nil + } + + p.mu.Lock() + defer p.mu.Unlock() + if p.km == nil { + km, err := p.load() + if err != nil { + return nil, err + } + p.km = km + } + return p.km, nil +} + +// Reload re-reads the configured files and atomically replaces the key +// material. On error the previous material is kept, so a broken rotation +// does not take the listener down. +func (p *Provider) Reload() error { + km, err := p.load() + if err != nil { + return err + } + p.mu.Lock() + p.km = km + p.mu.Unlock() + return nil +} + +// Close stops the refresh goroutine and removes the provider from the +// SIGHUP reload registry. +func (p *Provider) Close() { + p.closeOnce.Do(func() { + close(p.stop) + registryMu.Lock() + delete(registry, p) + registryMu.Unlock() + }) +} + +func (p *Provider) run() { + ticker := time.NewTicker(p.opts.RefreshDuration) + defer ticker.Stop() + for { + select { + case <-ticker.C: + if err := p.Reload(); err != nil { + glog.Warningf("certreload: periodic refresh %s: %v", p.opts.describe(), err) + } + case <-p.stop: + return + } + } +} + +func (p *Provider) load() (*certprovider.KeyMaterial, error) { + km := &certprovider.KeyMaterial{} + if p.opts.CertFile != "" { + cert, err := tls.LoadX509KeyPair(p.opts.CertFile, p.opts.KeyFile) + if err != nil { + return nil, err + } + km.Certs = []tls.Certificate{cert} + } + if p.opts.RootFile != "" { + rootPEM, err := os.ReadFile(p.opts.RootFile) + if err != nil { + return nil, err + } + roots := x509.NewCertPool() + if !roots.AppendCertsFromPEM(rootPEM) { + return nil, fmt.Errorf("no CA certificates found in %s", p.opts.RootFile) + } + km.Roots = roots + } + return km, nil +} + +// ReloadAll forces every live provider to re-read its files. It is meant to +// be called from a SIGHUP handler so rotated certificates take effect +// immediately instead of at the next refresh tick. +func ReloadAll() { + registryMu.Lock() + providers := make([]*Provider, 0, len(registry)) + for p := range registry { + providers = append(providers, p) + } + registryMu.Unlock() + + for _, p := range providers { + if err := p.Reload(); err != nil { + glog.Warningf("certreload: SIGHUP refresh %s: %v", p.opts.describe(), err) + } + } +} diff --git a/weed/security/tls.go b/weed/security/tls.go index 26feb29533..e4d90cd9fd 100644 --- a/weed/security/tls.go +++ b/weed/security/tls.go @@ -20,7 +20,6 @@ import ( "google.golang.org/grpc" "google.golang.org/grpc/credentials" "google.golang.org/grpc/credentials/insecure" - "google.golang.org/grpc/credentials/tls/certprovider/pemfile" "google.golang.org/grpc/security/advancedtls" ) @@ -79,7 +78,7 @@ func loadServerTLS(config *util.ViperProxy, component string) (grpc.ServerOption return nil, nil, nil } - serverOptions := pemfile.Options{ + serverOptions := certreload.Options{ CertFile: config.GetString(component + ".cert"), KeyFile: config.GetString(component + ".key"), RefreshDuration: CredRefreshingInterval, @@ -94,18 +93,18 @@ func loadServerTLS(config *util.ViperProxy, component string) (grpc.ServerOption return nil, nil, err } - serverIdentityProvider, err := pemfile.NewProvider(serverOptions) + serverIdentityProvider, err := certreload.NewProvider(serverOptions) if err != nil { - return nil, nil, fmt.Errorf("pemfile.NewProvider(%v) failed: %w", serverOptions, err) + return nil, nil, fmt.Errorf("certreload.NewProvider(%v) failed: %w", serverOptions, err) } - serverRootOptions := pemfile.Options{ + serverRootOptions := certreload.Options{ RootFile: config.GetString("grpc.ca"), RefreshDuration: CredRefreshingInterval, } - serverRootProvider, err := pemfile.NewProvider(serverRootOptions) + serverRootProvider, err := certreload.NewProvider(serverRootOptions) if err != nil { - return nil, nil, fmt.Errorf("pemfile.NewProvider(%v) failed: %w", serverRootOptions, err) + return nil, nil, fmt.Errorf("certreload.NewProvider(%v) failed: %w", serverRootOptions, err) } // Start a server and create a client using advancedtls API with Provider. @@ -219,22 +218,22 @@ func loadClientTLS(config *util.ViperProxy, component, targetComponent string) ( return nil, err } - clientOptions := pemfile.Options{ + clientOptions := certreload.Options{ CertFile: certFileName, KeyFile: keyFileName, RefreshDuration: CredRefreshingInterval, } - clientProvider, err := pemfile.NewProvider(clientOptions) + clientProvider, err := certreload.NewProvider(clientOptions) if err != nil { - return nil, fmt.Errorf("pemfile.NewProvider(%v) failed: %w", clientOptions, err) + return nil, fmt.Errorf("certreload.NewProvider(%v) failed: %w", clientOptions, err) } - clientRootOptions := pemfile.Options{ + clientRootOptions := certreload.Options{ RootFile: caFileName, RefreshDuration: CredRefreshingInterval, } - clientRootProvider, err := pemfile.NewProvider(clientRootOptions) + clientRootProvider, err := certreload.NewProvider(clientRootOptions) if err != nil { - return nil, fmt.Errorf("pemfile.NewProvider(%v) failed: %w", clientRootOptions, err) + return nil, fmt.Errorf("certreload.NewProvider(%v) failed: %w", clientRootOptions, err) } options := &advancedtls.Options{ IdentityOptions: advancedtls.IdentityCertificateOptions{ @@ -331,8 +330,8 @@ func LoadClientTLSHTTP(clientCertFile string) *tls.Config { } } -// checkTLSFiles validates configured TLS material up front: the pemfile -// providers read lazily, so without this a typo'd or unparseable file would +// checkTLSFiles validates configured TLS material up front: the providers +// read lazily, so without this a typo'd or unparseable file would // only surface at handshake time instead of at startup. func checkTLSFiles(certFile, keyFile, caFile string) error { if _, err := tls.LoadX509KeyPair(certFile, keyFile); err != nil { diff --git a/weed/security/tls_hup.go b/weed/security/tls_hup.go new file mode 100644 index 0000000000..ffc324b93d --- /dev/null +++ b/weed/security/tls_hup.go @@ -0,0 +1,12 @@ +//go:build !plan9 + +package security + +import ( + "github.com/seaweedfs/seaweedfs/weed/security/certreload" + "github.com/seaweedfs/seaweedfs/weed/util/grace" +) + +func init() { + grace.OnReload(certreload.ReloadAll) +}