Rework security module, replace JWT library, invalidate JWT tokens signed for Chrly v4, generate RSA key in runtime when not provided via configuration

This commit is contained in:
ErickSkrauch
2024-02-01 12:11:39 +01:00
parent 11340289ad
commit 10c11bc060
15 changed files with 246 additions and 321 deletions

View File

@@ -3,7 +3,7 @@ package di
import "github.com/defval/di"
func New() (*di.Container, error) {
container, err := di.New(
return di.New(
config,
dispatcher,
logger,
@@ -12,11 +12,6 @@ func New() (*di.Container, error) {
handlers,
profilesDi,
server,
signer,
securityDiOptions,
)
if err != nil {
return nil, err
}
return container, nil
}

View File

@@ -1,29 +1,36 @@
package di
import (
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/base64"
"encoding/pem"
"errors"
"strings"
"ely.by/chrly/internal/http"
. "ely.by/chrly/internal/signer"
"ely.by/chrly/internal/security"
"github.com/defval/di"
"github.com/spf13/viper"
)
var signer = di.Options(
var securityDiOptions = di.Options(
di.Provide(newTexturesSigner,
di.As(new(http.TexturesSigner)),
),
)
func newTexturesSigner(config *viper.Viper) (*Signer, error) {
func newTexturesSigner(config *viper.Viper) (*security.Signer, error) {
keyStr := config.GetString("chrly.signing.key")
if keyStr == "" {
return nil, errors.New("chrly.signing.key must be set in order to sign textures")
// TODO: log a message about the generated signing key and the way to specify it permanently
privateKey, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
return nil, err
}
return security.NewSigner(privateKey), nil
}
var keyBytes []byte
@@ -40,10 +47,10 @@ func newTexturesSigner(config *viper.Viper) (*Signer, error) {
}
rawPem, _ := pem.Decode(keyBytes)
key, err := x509.ParsePKCS1PrivateKey(rawPem.Bytes)
privateKey, err := x509.ParsePKCS1PrivateKey(rawPem.Bytes)
if err != nil {
return nil, err
}
return &Signer{Key: key}, nil
return security.NewSigner(privateKey), nil
}

View File

@@ -12,6 +12,7 @@ import (
"github.com/spf13/viper"
. "ely.by/chrly/internal/http"
"ely.by/chrly/internal/security"
)
var server = di.Options(
@@ -19,16 +20,13 @@ var server = di.Options(
di.Provide(newServer),
)
func newAuthenticator(config *viper.Viper, emitter Emitter) (*JwtAuth, error) {
func newAuthenticator(config *viper.Viper) (*security.Jwt, error) {
key := config.GetString("chrly.secret")
if key == "" {
return nil, errors.New("chrly.secret must be set in order to use authenticator")
}
return &JwtAuth{
Key: []byte(key),
Emitter: emitter,
}, nil
return security.NewJwt([]byte(key)), nil
}
type serverParams struct {