Просмотр исходного кода

Merge commit from fork

security: GHSA-v863-wq24-xg2x (MED) reload the local JWT public key when the file changes
James Read 13 часов назад
Родитель
Сommit
bf6645eda4

+ 1 - 1
docs/modules/ROOT/pages/config.adoc

@@ -89,7 +89,7 @@ All configuration options are covered in the solution sections
 | `authJwtClaimUsername` | The claim to use for the username. | `sub` | Requires restart | xref:security/jwt_hmac.adoc[JWT with HMAC], xref:security/jwt_keys.adoc[JWT with Keys]
 | `authJwtClaimUserGroup` | The claim to use for the usergroup. | `sub` | Requires restart | xref:security/jwt_hmac.adoc[JWT with HMAC], xref:security/jwt_keys.adoc[JWT with Keys]
 | `authJwtHeader` | The HTTP header to use for JWT authentication. | `` | Requires restart | xref:security/jwt_keys.adoc[JWT with Keys]
-| `authJwtPubKeyPath` | The path to the public key to use for JWT authentication. | `` | Requires restart | xref:security/jwt_keys.adoc[JWT with Keys]
+| `authJwtPubKeyPath` | The path to the public key to use for JWT authentication. | `` | Live reloadable. The key file is read on every request, so replacing it takes effect without a restart. | xref:security/jwt_keys.adoc#rotating-public-keys-on-disk[JWT with Keys]
 | `authHttpHeaderUsername` | The HTTP header to use for the username. | `` | Requires restart | xref:security/trusted_header.adoc[Trusted Headers]
 | `authHttpHeaderUserGroup` | The HTTP header to use for the usergroup. | `` | Requires restart | xref:security/trusted_header.adoc[Trusted Headers]
 | `authLocalUsers` | The list of local users. | `[]` | Requires restart | xref:security/local.adoc[Local Users]

+ 7 - 0
docs/modules/ROOT/pages/security/jwt_keys.adoc

@@ -46,6 +46,13 @@ authJwtClaimUsername: email
 authJwtCookieName: "CF_Authorization"
 ----
 
+[#rotating-public-keys-on-disk]
+=== Rotating public keys on disk
+
+OliveTin reads the key file on every request, so you can rotate the key by replacing the file at the same path, for example by updating a Kubernetes or Docker secret, without restarting OliveTin. As soon as the file changes, tokens signed by the old key are rejected and tokens signed by the new key are accepted.
+
+If the key file is missing or cannot be parsed, OliveTin rejects every JWT until the file is fixed. When you replace the file, write the new key to a temporary file and rename it over the old one, so that OliveTin never reads a half-written key.
+
 == See Also
 
 * xref:solutions/cloudflare_access_tunnel/index.adoc[Cloudflare Access & Tunnels Solution]

+ 7 - 0
docs/modules/ROOT/pages/upgrade/upgrade_notes.adoc

@@ -19,6 +19,13 @@ A webhook in `execOnWebhook` without an `authType` used to accept every request
 
 If you have webhooks without an `authType`, add one. Use `authType: bearer`, `hmac-sha256`, `hmac-sha1` or `basic` with a `secret`, or set `authType: none` if the webhook should accept requests from anyone who can reach `/webhooks`. See xref:action_execution/onwebhook.adoc#every-webhook-needs-an-authtype[Webhook Authentication].
 
+[#jwt-local-key-reloaded]
+=== JWT public keys on disk are read on every request
+
+When `authJwtPubKeyPath` is set, OliveTin used to load the key file once and keep using that key until it restarted, even if the file was replaced, deleted or broken. It now reads the file on every request. Replacing the file takes effect straight away, so tokens signed by the old key stop working without a restart.
+
+If the key file is missing or cannot be parsed, every JWT is now rejected, instead of the previously loaded key staying in use. If you remove or move the key file while OliveTin is running, make sure the file at `authJwtPubKeyPath` is always present and valid. See xref:security/jwt_keys.adoc#rotating-public-keys-on-disk[Rotating public keys on disk].
+
 [#whoami-session-fingerprint]
 === `WhoAmI` no longer returns the session ID
 

+ 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)
+}