Преглед изворни кода

security: GHSA-v863-wq24-xg2x (MED) reload the local JWT public key when the file changes

The local public key was cached by path, so a key replaced at the same
path was never loaded, and a deleted or unreadable key file left the old
key trusted. The key file is now read on every request and parsed again
whenever its contents change. A key file that cannot be read or parsed
rejects every token, and the parsed key is returned under the lock
instead of being read from a global after it is released.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
jamesread пре 1 дан
родитељ
комит
fe8b0533bc

+ 51 - 54
service/internal/auth/otjwt/jwt.go

@@ -1,6 +1,7 @@
 package otjwt
 
 import (
+	"bytes"
 	"context"
 	"crypto/rsa"
 	"errors"
@@ -67,18 +68,56 @@ func parseJwtTokenWithRemoteKey(cfg *config.Config, jwtToken string) (*jwt.Token
 }
 
 var (
-	pubKeyBytes   []byte = nil
-	pubKey        *rsa.PublicKey
-	loadedKeyPath string
-
 	jwksVerifier keyfunc.Keyfunc
 	jwksOnce     sync.Once
 	jwksInitErr  error
 
-	localKeyMutex   sync.RWMutex
-	localKeyInitErr error
+	localKey localKeyCache
 )
 
+// Operators rotate the local public key by replacing the file at the same
+// path, for example when a Kubernetes or Docker secret is updated, so the file
+// is read on every request and parsed again whenever its contents change. A
+// key file that cannot be read or parsed rejects every token, rather than
+// leaving the previous key trusted.
+type localKeyCache struct {
+	key      *rsa.PublicKey
+	keyBytes []byte
+	mu       sync.Mutex
+}
+
+func (c *localKeyCache) get(keyPath string) (*rsa.PublicKey, error) {
+	keyBytes, err := os.ReadFile(keyPath)
+
+	c.mu.Lock()
+	defer c.mu.Unlock()
+
+	if err != nil {
+		c.clearLocked()
+		return nil, fmt.Errorf("couldn't read public key from file %s", keyPath)
+	}
+
+	if c.key != nil && bytes.Equal(c.keyBytes, keyBytes) {
+		return c.key, nil
+	}
+
+	parsedKey, err := jwt.ParseRSAPublicKeyFromPEM(keyBytes)
+	if err != nil {
+		c.clearLocked()
+		return nil, fmt.Errorf("error parsing public key object (from %s)", keyPath)
+	}
+
+	c.keyBytes = keyBytes
+	c.key = parsedKey
+
+	return parsedKey, nil
+}
+
+func (c *localKeyCache) clearLocked() {
+	c.keyBytes = nil
+	c.key = nil
+}
+
 func initJwks(cfg *config.Config) error {
 	jwksOnce.Do(func() {
 		if cfg.AuthJwtCertsURL != "" {
@@ -102,58 +141,16 @@ func initRemoteJwks(certsURL string) (keyfunc.Keyfunc, error) {
 	return keyfunc.NewDefaultCtx(context.Background(), []string{certsURL})
 }
 
-func loadPublicKeyFromFile(keyPath string) error {
-	keyBytes, err := os.ReadFile(keyPath)
-	if err != nil {
-		return fmt.Errorf("couldn't read public key from file %s", keyPath)
-	}
-
-	parsedKey, err := jwt.ParseRSAPublicKeyFromPEM(keyBytes)
-	if err != nil {
-		return fmt.Errorf("error parsing public key object (from %s)", keyPath)
-	}
-
-	pubKeyBytes = keyBytes
-	pubKey = parsedKey
-	loadedKeyPath = keyPath
-	localKeyInitErr = nil
-	return nil
-}
-
-func isKeyLoadedForPath(keyPath string) bool {
-	return pubKeyBytes != nil && loadedKeyPath == keyPath
-}
-
-func readLocalPublicKeyWithLock(keyPath string) error {
-	localKeyMutex.RLock()
-	alreadyLoaded := isKeyLoadedForPath(keyPath)
-	localKeyMutex.RUnlock()
-
-	if alreadyLoaded {
-		return nil
-	}
-
-	localKeyMutex.Lock()
-	defer localKeyMutex.Unlock()
-
-	if isKeyLoadedForPath(keyPath) {
-		return nil
-	}
-
-	localKeyInitErr = loadPublicKeyFromFile(keyPath)
-	return localKeyInitErr
-}
-
-func readLocalPublicKey(cfg *config.Config) error {
+func readLocalPublicKey(cfg *config.Config) (*rsa.PublicKey, error) {
 	if cfg.AuthJwtPubKeyPath == "" {
-		return errors.New("no JWT public key path configured")
+		return nil, errors.New("no JWT public key path configured")
 	}
-	return readLocalPublicKeyWithLock(cfg.AuthJwtPubKeyPath)
+
+	return localKey.get(cfg.AuthJwtPubKeyPath)
 }
 
 func parseJwtTokenWithLocalKey(cfg *config.Config, jwtString string) (*jwt.Token, error) {
-	err := readLocalPublicKey(cfg)
-
+	publicKey, err := readLocalPublicKey(cfg)
 	if err != nil {
 		return nil, err
 	}
@@ -163,7 +160,7 @@ func parseJwtTokenWithLocalKey(cfg *config.Config, jwtString string) (*jwt.Token
 			return nil, fmt.Errorf("parseJwt expected token algorithm RSA but got: %v", token.Header["alg"])
 		}
 
-		return pubKey, nil
+		return publicKey, nil
 	}
 
 	opts := parserOptionsWithAudience(cfg)

+ 172 - 0
service/internal/auth/otjwt/jwt_local_key_rotation_test.go

@@ -0,0 +1,172 @@
+package otjwt
+
+import (
+	"crypto/rsa"
+	"os"
+	"path/filepath"
+	"sync"
+	"testing"
+
+	config "github.com/OliveTin/OliveTin/internal/config"
+	"github.com/stretchr/testify/assert"
+	"github.com/stretchr/testify/require"
+)
+
+type rotationKey struct {
+	private *rsa.PrivateKey
+	pubPem  []byte
+	token   string
+}
+
+func newRotationKey(t *testing.T) rotationKey {
+	t.Helper()
+
+	privateKey, pubPem := generateRSAKeyPair(t)
+
+	return rotationKey{
+		private: privateKey,
+		pubPem:  pubPem,
+		token:   createJWTTokenWithExpirationAndAudience(t, privateKey, 1000, ""),
+	}
+}
+
+func localKeyConfig(keyPath string) *config.Config {
+	cfg := config.DefaultConfig()
+	cfg.AuthJwtPubKeyPath = keyPath
+
+	return cfg
+}
+
+func tokenAccepted(cfg *config.Config, token string) bool {
+	parsed, err := parseJwtTokenWithLocalKey(cfg, token)
+
+	return err == nil && parsed != nil && parsed.Valid
+}
+
+func writeKeyFile(t *testing.T, path string, content []byte) {
+	t.Helper()
+
+	require.NoError(t, os.WriteFile(path, content, 0o600))
+}
+
+func requireOnlyAccepted(t *testing.T, cfg *config.Config, accepted rotationKey, rejected rotationKey) {
+	t.Helper()
+
+	assert.True(t, tokenAccepted(cfg, accepted.token), "token signed by the current key must be accepted")
+	assert.False(t, tokenAccepted(cfg, rejected.token), "token signed by the old key must be rejected")
+}
+
+func TestLocalKeyReplacedInPlaceIsUsedWithoutRestart(t *testing.T) {
+	keyA, keyB := newRotationKey(t), newRotationKey(t)
+	keyPath := filepath.Join(t.TempDir(), "jwt.pub")
+	writeKeyFile(t, keyPath, keyA.pubPem)
+	cfg := localKeyConfig(keyPath)
+
+	requireOnlyAccepted(t, cfg, keyA, keyB)
+
+	writeKeyFile(t, keyPath, keyB.pubPem)
+
+	requireOnlyAccepted(t, cfg, keyB, keyA)
+}
+
+func TestLocalKeyReplacedByRenameIsUsedWithoutRestart(t *testing.T) {
+	keyA, keyB := newRotationKey(t), newRotationKey(t)
+	dir := t.TempDir()
+	keyPath := filepath.Join(dir, "jwt.pub")
+	writeKeyFile(t, keyPath, keyA.pubPem)
+	cfg := localKeyConfig(keyPath)
+
+	requireOnlyAccepted(t, cfg, keyA, keyB)
+
+	staged := filepath.Join(dir, "jwt.pub.new")
+	writeKeyFile(t, staged, keyB.pubPem)
+	require.NoError(t, os.Rename(staged, keyPath))
+
+	requireOnlyAccepted(t, cfg, keyB, keyA)
+}
+
+// Kubernetes updates a mounted secret by pointing a symlink at a new directory.
+func TestLocalKeyReplacedBySymlinkSwapIsUsedWithoutRestart(t *testing.T) {
+	keyA, keyB := newRotationKey(t), newRotationKey(t)
+	dir := t.TempDir()
+
+	for name, key := range map[string]rotationKey{"..2026_a": keyA, "..2026_b": keyB} {
+		require.NoError(t, os.Mkdir(filepath.Join(dir, name), 0o750))
+		writeKeyFile(t, filepath.Join(dir, name, "jwt.pub"), key.pubPem)
+	}
+
+	require.NoError(t, os.Symlink("..2026_a", filepath.Join(dir, "..data")))
+	require.NoError(t, os.Symlink(filepath.Join("..data", "jwt.pub"), filepath.Join(dir, "jwt.pub")))
+	cfg := localKeyConfig(filepath.Join(dir, "jwt.pub"))
+
+	requireOnlyAccepted(t, cfg, keyA, keyB)
+
+	require.NoError(t, os.Symlink("..2026_b", filepath.Join(dir, "..data_tmp")))
+	require.NoError(t, os.Rename(filepath.Join(dir, "..data_tmp"), filepath.Join(dir, "..data")))
+
+	requireOnlyAccepted(t, cfg, keyB, keyA)
+}
+
+func TestLocalKeyDeletedRejectsEveryToken(t *testing.T) {
+	keyA := newRotationKey(t)
+	keyPath := filepath.Join(t.TempDir(), "jwt.pub")
+	writeKeyFile(t, keyPath, keyA.pubPem)
+	cfg := localKeyConfig(keyPath)
+
+	require.True(t, tokenAccepted(cfg, keyA.token))
+
+	require.NoError(t, os.Remove(keyPath))
+	assert.False(t, tokenAccepted(cfg, keyA.token), "a deleted key file must not leave the old key trusted")
+
+	writeKeyFile(t, keyPath, keyA.pubPem)
+	assert.True(t, tokenAccepted(cfg, keyA.token), "restoring the key file must work without a restart")
+}
+
+func TestLocalKeyCorruptedRejectsEveryToken(t *testing.T) {
+	keyA := newRotationKey(t)
+	keyPath := filepath.Join(t.TempDir(), "jwt.pub")
+	writeKeyFile(t, keyPath, keyA.pubPem)
+	cfg := localKeyConfig(keyPath)
+
+	require.True(t, tokenAccepted(cfg, keyA.token))
+
+	writeKeyFile(t, keyPath, []byte("not a public key"))
+
+	assert.False(t, tokenAccepted(cfg, keyA.token), "a corrupted key file must not leave the old key trusted")
+}
+
+func TestLocalKeyUnchangedFileReusesParsedKey(t *testing.T) {
+	keyA := newRotationKey(t)
+	keyPath := filepath.Join(t.TempDir(), "jwt.pub")
+	writeKeyFile(t, keyPath, keyA.pubPem)
+
+	first, err := localKey.get(keyPath)
+	require.NoError(t, err)
+
+	second, err := localKey.get(keyPath)
+	require.NoError(t, err)
+
+	assert.Same(t, first, second, "an unchanged key file must not be parsed again")
+}
+
+func TestLocalKeyRotationDuringConcurrentRequests(t *testing.T) {
+	keyA, keyB := newRotationKey(t), newRotationKey(t)
+	keyPath := filepath.Join(t.TempDir(), "jwt.pub")
+	writeKeyFile(t, keyPath, keyA.pubPem)
+	cfg := localKeyConfig(keyPath)
+
+	var wg sync.WaitGroup
+	for range 8 {
+		wg.Go(func() {
+			for range 50 {
+				tokenAccepted(cfg, keyA.token)
+				tokenAccepted(cfg, keyB.token)
+			}
+		})
+	}
+
+	writeKeyFile(t, keyPath, keyB.pubPem)
+	wg.Wait()
+
+	requireOnlyAccepted(t, cfg, keyB, keyA)
+}