Refactor JWT secret generating & decoding code (#29172)

Old code is not consistent for generating & decoding the JWT secrets.

Now, the callers only need to use 2 consistent functions:
NewJwtSecretWithBase64 and DecodeJwtSecretBase64

And remove a non-common function Base64FixedDecode from util.go
This commit is contained in:
wxiaoguang 2024-02-16 23:18:30 +08:00 committed by GitHub
parent 7132a0ba75
commit 45c15387b2
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
9 changed files with 57 additions and 46 deletions

View File

@ -70,7 +70,7 @@ func runGenerateInternalToken(c *cli.Context) error {
} }
func runGenerateLfsJwtSecret(c *cli.Context) error { func runGenerateLfsJwtSecret(c *cli.Context) error {
_, jwtSecretBase64, err := generate.NewJwtSecretBase64() _, jwtSecretBase64, err := generate.NewJwtSecretWithBase64()
if err != nil { if err != nil {
return err return err
} }

View File

@ -7,6 +7,7 @@ package generate
import ( import (
"crypto/rand" "crypto/rand"
"encoding/base64" "encoding/base64"
"fmt"
"io" "io"
"time" "time"
@ -38,19 +39,24 @@ func NewInternalToken() (string, error) {
return internalToken, nil return internalToken, nil
} }
// NewJwtSecret generates a new value intended to be used for JWT secrets. const defaultJwtSecretLen = 32
func NewJwtSecret() ([]byte, error) {
bytes := make([]byte, 32) // DecodeJwtSecretBase64 decodes a base64 encoded jwt secret into bytes, and check its length
_, err := io.ReadFull(rand.Reader, bytes) func DecodeJwtSecretBase64(src string) ([]byte, error) {
if err != nil { encoding := base64.RawURLEncoding
decoded := make([]byte, encoding.DecodedLen(len(src))+3)
if n, err := encoding.Decode(decoded, []byte(src)); err != nil {
return nil, err return nil, err
} else if n != defaultJwtSecretLen {
return nil, fmt.Errorf("invalid base64 decoded length: %d, expects: %d", n, defaultJwtSecretLen)
} }
return bytes, nil return decoded[:defaultJwtSecretLen], nil
} }
// NewJwtSecretBase64 generates a new base64 encoded value intended to be used for JWT secrets. // NewJwtSecretWithBase64 generates a jwt secret with its base64 encoded value intended to be used for saving into config file
func NewJwtSecretBase64() ([]byte, string, error) { func NewJwtSecretWithBase64() ([]byte, string, error) {
bytes, err := NewJwtSecret() bytes := make([]byte, defaultJwtSecretLen)
_, err := io.ReadFull(rand.Reader, bytes)
if err != nil { if err != nil {
return nil, "", err return nil, "", err
} }

View File

@ -0,0 +1,34 @@
// Copyright 2024 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
package generate
import (
"encoding/base64"
"strings"
"testing"
"github.com/stretchr/testify/assert"
)
func TestDecodeJwtSecretBase64(t *testing.T) {
_, err := DecodeJwtSecretBase64("abcd")
assert.ErrorContains(t, err, "invalid base64 decoded length")
_, err = DecodeJwtSecretBase64(strings.Repeat("a", 64))
assert.ErrorContains(t, err, "invalid base64 decoded length")
str32 := strings.Repeat("x", 32)
encoded32 := base64.RawURLEncoding.EncodeToString([]byte(str32))
decoded32, err := DecodeJwtSecretBase64(encoded32)
assert.NoError(t, err)
assert.Equal(t, str32, string(decoded32))
}
func TestNewJwtSecretWithBase64(t *testing.T) {
secret, encoded, err := NewJwtSecretWithBase64()
assert.NoError(t, err)
assert.Len(t, secret, 32)
decoded, err := DecodeJwtSecretBase64(encoded)
assert.NoError(t, err)
assert.Equal(t, secret, decoded)
}

View File

@ -4,12 +4,10 @@
package setting package setting
import ( import (
"encoding/base64"
"fmt" "fmt"
"time" "time"
"code.gitea.io/gitea/modules/generate" "code.gitea.io/gitea/modules/generate"
"code.gitea.io/gitea/modules/util"
) )
// LFS represents the configuration for Git LFS // LFS represents the configuration for Git LFS
@ -62,9 +60,9 @@ func loadLFSFrom(rootCfg ConfigProvider) error {
} }
LFS.JWTSecretBase64 = loadSecret(rootCfg.Section("server"), "LFS_JWT_SECRET_URI", "LFS_JWT_SECRET") LFS.JWTSecretBase64 = loadSecret(rootCfg.Section("server"), "LFS_JWT_SECRET_URI", "LFS_JWT_SECRET")
LFS.JWTSecretBytes, err = util.Base64FixedDecode(base64.RawURLEncoding, []byte(LFS.JWTSecretBase64), 32) LFS.JWTSecretBytes, err = generate.DecodeJwtSecretBase64(LFS.JWTSecretBase64)
if err != nil { if err != nil {
LFS.JWTSecretBytes, LFS.JWTSecretBase64, err = generate.NewJwtSecretBase64() LFS.JWTSecretBytes, LFS.JWTSecretBase64, err = generate.NewJwtSecretWithBase64()
if err != nil { if err != nil {
return fmt.Errorf("error generating JWT Secret for custom config: %v", err) return fmt.Errorf("error generating JWT Secret for custom config: %v", err)
} }

View File

@ -4,13 +4,11 @@
package setting package setting
import ( import (
"encoding/base64"
"math" "math"
"path/filepath" "path/filepath"
"code.gitea.io/gitea/modules/generate" "code.gitea.io/gitea/modules/generate"
"code.gitea.io/gitea/modules/log" "code.gitea.io/gitea/modules/log"
"code.gitea.io/gitea/modules/util"
) )
// OAuth2UsernameType is enum describing the way gitea 'name' should be generated from oauth2 data // OAuth2UsernameType is enum describing the way gitea 'name' should be generated from oauth2 data
@ -137,13 +135,12 @@ func loadOAuth2From(rootCfg ConfigProvider) {
} }
if InstallLock { if InstallLock {
if _, err := util.Base64FixedDecode(base64.RawURLEncoding, []byte(OAuth2.JWTSecretBase64), 32); err != nil { if _, err := generate.DecodeJwtSecretBase64(OAuth2.JWTSecretBase64); err != nil {
key, err := generate.NewJwtSecret() _, OAuth2.JWTSecretBase64, err = generate.NewJwtSecretWithBase64()
if err != nil { if err != nil {
log.Fatal("error generating JWT secret: %v", err) log.Fatal("error generating JWT secret: %v", err)
} }
OAuth2.JWTSecretBase64 = base64.RawURLEncoding.EncodeToString(key)
saveCfg, err := rootCfg.PrepareSaving() saveCfg, err := rootCfg.PrepareSaving()
if err != nil { if err != nil {
log.Fatal("save oauth2.JWT_SECRET failed: %v", err) log.Fatal("save oauth2.JWT_SECRET failed: %v", err)

View File

@ -6,7 +6,6 @@ package util
import ( import (
"bytes" "bytes"
"crypto/rand" "crypto/rand"
"encoding/base64"
"fmt" "fmt"
"math/big" "math/big"
"strconv" "strconv"
@ -246,13 +245,3 @@ func ToFloat64(number any) (float64, error) {
func ToPointer[T any](val T) *T { func ToPointer[T any](val T) *T {
return &val return &val
} }
func Base64FixedDecode(encoding *base64.Encoding, src []byte, length int) ([]byte, error) {
decoded := make([]byte, encoding.DecodedLen(len(src))+3)
if n, err := encoding.Decode(decoded, src); err != nil {
return nil, err
} else if n != length {
return nil, fmt.Errorf("invalid base64 decoded length: %d, expects: %d", n, length)
}
return decoded[:length], nil
}

View File

@ -4,7 +4,6 @@
package util package util
import ( import (
"encoding/base64"
"regexp" "regexp"
"strings" "strings"
"testing" "testing"
@ -234,16 +233,3 @@ func TestToPointer(t *testing.T) {
val123 := 123 val123 := 123
assert.False(t, &val123 == ToPointer(val123)) assert.False(t, &val123 == ToPointer(val123))
} }
func TestBase64FixedDecode(t *testing.T) {
_, err := Base64FixedDecode(base64.RawURLEncoding, []byte("abcd"), 32)
assert.ErrorContains(t, err, "invalid base64 decoded length")
_, err = Base64FixedDecode(base64.RawURLEncoding, []byte(strings.Repeat("a", 64)), 32)
assert.ErrorContains(t, err, "invalid base64 decoded length")
str32 := strings.Repeat("x", 32)
encoded32 := base64.RawURLEncoding.EncodeToString([]byte(str32))
decoded32, err := Base64FixedDecode(base64.RawURLEncoding, []byte(encoded32), 32)
assert.NoError(t, err)
assert.Equal(t, str32, string(decoded32))
}

View File

@ -409,7 +409,7 @@ func SubmitInstall(ctx *context.Context) {
cfg.Section("server").Key("LFS_START_SERVER").SetValue("true") cfg.Section("server").Key("LFS_START_SERVER").SetValue("true")
cfg.Section("lfs").Key("PATH").SetValue(form.LFSRootPath) cfg.Section("lfs").Key("PATH").SetValue(form.LFSRootPath)
var lfsJwtSecret string var lfsJwtSecret string
if _, lfsJwtSecret, err = generate.NewJwtSecretBase64(); err != nil { if _, lfsJwtSecret, err = generate.NewJwtSecretWithBase64(); err != nil {
ctx.RenderWithErr(ctx.Tr("install.lfs_jwt_secret_failed", err), tplInstall, &form) ctx.RenderWithErr(ctx.Tr("install.lfs_jwt_secret_failed", err), tplInstall, &form)
return return
} }

View File

@ -18,6 +18,7 @@ import (
"path/filepath" "path/filepath"
"strings" "strings"
"code.gitea.io/gitea/modules/generate"
"code.gitea.io/gitea/modules/log" "code.gitea.io/gitea/modules/log"
"code.gitea.io/gitea/modules/setting" "code.gitea.io/gitea/modules/setting"
"code.gitea.io/gitea/modules/util" "code.gitea.io/gitea/modules/util"
@ -336,7 +337,7 @@ func InitSigningKey() error {
// loadSymmetricKey checks if the configured secret is valid. // loadSymmetricKey checks if the configured secret is valid.
// If it is not valid, it will return an error. // If it is not valid, it will return an error.
func loadSymmetricKey() (any, error) { func loadSymmetricKey() (any, error) {
return util.Base64FixedDecode(base64.RawURLEncoding, []byte(setting.OAuth2.JWTSecretBase64), 32) return generate.DecodeJwtSecretBase64(setting.OAuth2.JWTSecretBase64)
} }
// loadOrCreateAsymmetricKey checks if the configured private key exists. // loadOrCreateAsymmetricKey checks if the configured private key exists.