Compare commits

..

No commits in common. "c3162756ad9b0cea1253bd1864d84d2163abae7e" and "9057adebdd4bd2b4449604a7f64301465b243595" have entirely different histories.

6 changed files with 82 additions and 238 deletions

View File

@ -7,8 +7,6 @@ DB_SSLMODE=disable
API_KEY= API_KEY=
# JWT Configuration # JWT Configuration
#JWT_SECRET=test JWT_SECRET=test
#JWT_KEY_DIR=keys JWT_KEY_DIR=keys
#JWT_KEY_GENERATE=true JWT_KEY_GENERATE=true
JWT_TOKEN_DURATION=24h
ENVIRONMENT=production

1
backend/.gitignore vendored
View File

@ -1 +0,0 @@
keys

View File

@ -13,8 +13,7 @@ import (
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
swaggerFiles "github.com/swaggo/files" swaggerFiles "github.com/swaggo/files"
ginSwagger "github.com/swaggo/gin-swagger" ginSwagger "github.com/swaggo/gin-swagger"
_ "github.com/timetracker/backend/docs" _ "github.com/timetracker/backend/docs" // This line is important for swag to work
"github.com/timetracker/backend/internal/api/middleware"
"github.com/timetracker/backend/internal/api/routes" "github.com/timetracker/backend/internal/api/routes"
"github.com/timetracker/backend/internal/config" "github.com/timetracker/backend/internal/config"
"github.com/timetracker/backend/internal/models" "github.com/timetracker/backend/internal/models"
@ -61,11 +60,6 @@ func main() {
log.Fatalf("Error migrating database: %v", err) log.Fatalf("Error migrating database: %v", err)
} }
// Initialize JWT keys
if err := middleware.InitJWTKeys(); err != nil {
log.Fatalf("Error initializing JWT keys: %v", err)
}
// Create Gin router // Create Gin router
r := gin.Default() r := gin.Default()

View File

@ -8,157 +8,88 @@ import (
"errors" "errors"
"fmt" "fmt"
"os" "os"
"path/filepath"
"time" "time"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"github.com/golang-jwt/jwt/v5" "github.com/golang-jwt/jwt/v5"
"github.com/joho/godotenv"
"github.com/oklog/ulid/v2" "github.com/oklog/ulid/v2"
"github.com/timetracker/backend/internal/api/utils" "github.com/timetracker/backend/internal/api/utils"
"github.com/timetracker/backend/internal/config"
"github.com/timetracker/backend/internal/models" "github.com/timetracker/backend/internal/models"
) )
var ( var (
signKey *rsa.PrivateKey jwtSecret string
verifyKey *rsa.PublicKey tokenDuration = 24 * time.Hour
) )
// InitJWTKeys initializes the JWT keys func init() {
func InitJWTKeys() error { // Load .env file
cfg := config.MustLoadConfig() _ = godotenv.Load()
// If a secret is provided, we'll use HMAC-SHA256, so no need for certificates // Get JWT secret from environment
if cfg.JWTConfig.Secret != "" { jwtSecret = os.Getenv("JWT_SECRET")
println("Using HMAC-SHA256 for JWT")
return nil
}
// Check if keys exist // Generate a random secret if none is provided
privKeyPath := filepath.Join(cfg.JWTConfig.KeyDir, cfg.JWTConfig.PrivKeyFile) if jwtSecret == "" {
pubKeyPath := filepath.Join(cfg.JWTConfig.KeyDir, cfg.JWTConfig.PubKeyFile) randomBytes := make([]byte, 32)
_, err := rand.Read(randomBytes)
keysExist := fileExists(privKeyPath) && fileExists(pubKeyPath)
// Generate keys if they don't exist and KeyGenerate is true
if !keysExist && cfg.JWTConfig.KeyGenerate {
println("Generating RSA keys")
if err := generateRSAKeys(cfg.JWTConfig); err != nil {
return fmt.Errorf("failed to generate RSA keys: %w", err)
}
} else if !keysExist {
return errors.New("JWT keys not found and key generation is disabled")
}
// Load keys
var err error
signKey, err = loadPrivateKey(privKeyPath)
if err != nil { if err != nil {
return fmt.Errorf("failed to load private key: %w", err) panic("failed to generate JWT secret: " + err.Error())
}
jwtSecret = string(randomBytes)
} }
verifyKey, err = loadPublicKey(pubKeyPath) // Generate and store RSA keys if configured
if os.Getenv("JWT_KEY_GENERATE") == "true" {
keyDir := os.Getenv("JWT_KEY_DIR")
if keyDir == "" {
keyDir = "./keys"
}
// Create directory if it doesn't exist
if err := os.MkdirAll(keyDir, 0755); err != nil {
panic("failed to create key directory: " + err.Error())
}
// Generate RSA key pair
privateKey, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil { if err != nil {
return fmt.Errorf("failed to load public key: %w", err) panic("failed to generate RSA key pair: " + err.Error())
}
return nil
}
// fileExists checks if a file exists
func fileExists(path string) bool {
_, err := os.Stat(path)
return !os.IsNotExist(err)
}
// generateRSAKeys generates RSA keys and saves them to disk
func generateRSAKeys(cfg models.JWTConfig) error {
// Create key directory if it doesn't exist
if err := os.MkdirAll(cfg.KeyDir, 0700); err != nil {
return fmt.Errorf("failed to create key directory: %w", err)
}
// Generate private key
privateKey, err := rsa.GenerateKey(rand.Reader, cfg.KeyBits)
if err != nil {
return fmt.Errorf("failed to generate private key: %w", err)
} }
// Save private key // Save private key
privKeyPath := filepath.Join(cfg.KeyDir, cfg.PrivKeyFile) privateKeyFile, err := os.Create(fmt.Sprintf("%s/private.pem", keyDir))
privKeyFile, err := os.OpenFile(privKeyPath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
if err != nil { if err != nil {
return fmt.Errorf("failed to create private key file: %w", err) panic("failed to create private key file: " + err.Error())
} }
defer privKeyFile.Close() defer privateKeyFile.Close()
privKeyPEM := &pem.Block{ privateKeyPEM := &pem.Block{
Type: "RSA PRIVATE KEY", Type: "RSA PRIVATE KEY",
Bytes: x509.MarshalPKCS1PrivateKey(privateKey), Bytes: x509.MarshalPKCS1PrivateKey(privateKey),
} }
if err := pem.Encode(privKeyFile, privKeyPEM); err != nil { if err := pem.Encode(privateKeyFile, privateKeyPEM); err != nil {
return fmt.Errorf("failed to encode private key: %w", err) panic("failed to encode private key: " + err.Error())
} }
// Save public key // Save public key
pubKeyPath := filepath.Join(cfg.KeyDir, cfg.PubKeyFile) publicKeyFile, err := os.Create(fmt.Sprintf("%s/public.pem", keyDir))
pubKeyFile, err := os.OpenFile(pubKeyPath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)
if err != nil { if err != nil {
return fmt.Errorf("failed to create public key file: %w", err) panic("failed to create public key file: " + err.Error())
} }
defer pubKeyFile.Close() defer publicKeyFile.Close()
pubKeyPEM := &pem.Block{ publicKeyPEM := &pem.Block{
Type: "RSA PUBLIC KEY", Type: "RSA PUBLIC KEY",
Bytes: x509.MarshalPKCS1PublicKey(&privateKey.PublicKey), Bytes: x509.MarshalPKCS1PublicKey(&privateKey.PublicKey),
} }
if err := pem.Encode(pubKeyFile, pubKeyPEM); err != nil { if err := pem.Encode(publicKeyFile, publicKeyPEM); err != nil {
return fmt.Errorf("failed to encode public key: %w", err) panic("failed to encode public key: " + err.Error())
} }
return nil
} }
// loadPrivateKey loads a private key from a file
func loadPrivateKey(path string) (*rsa.PrivateKey, error) {
keyData, err := os.ReadFile(path)
if err != nil {
return nil, fmt.Errorf("failed to read private key file: %w", err)
}
block, _ := pem.Decode(keyData)
if block == nil {
return nil, errors.New("failed to parse PEM block containing the private key")
}
privateKey, err := x509.ParsePKCS1PrivateKey(block.Bytes)
if err != nil {
return nil, fmt.Errorf("failed to parse private key: %w", err)
}
return privateKey, nil
}
// loadPublicKey loads a public key from a file
func loadPublicKey(path string) (*rsa.PublicKey, error) {
keyData, err := os.ReadFile(path)
if err != nil {
return nil, fmt.Errorf("failed to read public key file: %w", err)
}
block, _ := pem.Decode(keyData)
if block == nil {
return nil, errors.New("failed to parse PEM block containing the public key")
}
publicKey, err := x509.ParsePKCS1PublicKey(block.Bytes)
if err != nil {
return nil, fmt.Errorf("failed to parse public key: %w", err)
}
return publicKey, nil
} }
// Claims represents the JWT claims // Claims represents the JWT claims
@ -243,60 +174,36 @@ func GenerateToken(user *models.User, c *gin.Context) (string, error) {
Role: user.Role, Role: user.Role,
CompanyID: user.CompanyID.String(), CompanyID: user.CompanyID.String(),
RegisteredClaims: jwt.RegisteredClaims{ RegisteredClaims: jwt.RegisteredClaims{
ExpiresAt: jwt.NewNumericDate(time.Now().Add(config.MustLoadConfig().JWTConfig.TokenDuration)), ExpiresAt: jwt.NewNumericDate(time.Now().Add(tokenDuration)),
IssuedAt: jwt.NewNumericDate(time.Now()), IssuedAt: jwt.NewNumericDate(time.Now()),
NotBefore: jwt.NewNumericDate(time.Now()), NotBefore: jwt.NewNumericDate(time.Now()),
}, },
} }
cfg := config.MustLoadConfig() // Create the token
var token *jwt.Token token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
var tokenString string
var err error
// Choose signing method based on configuration
if cfg.JWTConfig.Secret != "" {
// Use HMAC-SHA256 if a secret is provided
token = jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
tokenString, err = token.SignedString([]byte(cfg.JWTConfig.Secret))
} else {
// Use RSA if no secret is provided
token = jwt.NewWithClaims(jwt.SigningMethodRS256, claims)
tokenString, err = token.SignedString(signKey)
}
// Sign the token
tokenString, err := token.SignedString([]byte(jwtSecret))
if err != nil { if err != nil {
return "", err return "", err
} }
// Set the cookie // Set the cookie
c.SetCookie("jwt", tokenString, int(cfg.JWTConfig.TokenDuration.Seconds()), "/", "", true, true) c.SetCookie("jwt", tokenString, int(tokenDuration.Seconds()), "/", "", true, true)
return tokenString, nil return tokenString, nil
} }
// validateToken validates a JWT token and returns the claims // validateToken validates a JWT token and returns the claims
func validateToken(tokenString string) (*Claims, error) { func validateToken(tokenString string) (*Claims, error) {
cfg := config.MustLoadConfig()
// Parse the token // Parse the token
token, err := jwt.ParseWithClaims(tokenString, &Claims{}, func(token *jwt.Token) (any, error) { token, err := jwt.ParseWithClaims(tokenString, &Claims{}, func(token *jwt.Token) (interface{}, error) {
// Check which signing method was used // Validate the signing method
if _, ok := token.Method.(*jwt.SigningMethodHMAC); ok { if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
// HMAC method was used, validate with secret
if cfg.JWTConfig.Secret == "" {
return nil, errors.New("HMAC signing method used but no secret configured")
}
return []byte(cfg.JWTConfig.Secret), nil
} else if _, ok := token.Method.(*jwt.SigningMethodRSA); ok {
// RSA method was used, validate with public key
if verifyKey == nil {
return nil, errors.New("RSA signing method used but no public key loaded")
}
return verifyKey, nil
}
return nil, errors.New("unexpected signing method") return nil, errors.New("unexpected signing method")
}
return []byte(jwtSecret), nil
}) })
if err != nil { if err != nil {

View File

@ -6,7 +6,6 @@ import (
"log" "log"
"os" "os"
"strconv" "strconv"
"time"
"github.com/joho/godotenv" "github.com/joho/godotenv"
"github.com/timetracker/backend/internal/models" "github.com/timetracker/backend/internal/models"
@ -16,7 +15,6 @@ import (
// Config represents the application configuration // Config represents the application configuration
type Config struct { type Config struct {
Database models.DatabaseConfig Database models.DatabaseConfig
JWTConfig models.JWTConfig
APIKey string APIKey string
} }
@ -27,7 +25,6 @@ func LoadConfig() (*Config, error) {
cfg := &Config{ cfg := &Config{
Database: models.DefaultDatabaseConfig(), Database: models.DefaultDatabaseConfig(),
JWTConfig: models.JWTConfig{},
} }
// Load database configuration // Load database configuration
@ -35,50 +32,12 @@ func LoadConfig() (*Config, error) {
return nil, fmt.Errorf("failed to load database config: %w", err) return nil, fmt.Errorf("failed to load database config: %w", err)
} }
// Load JWT configuration
if err := loadJWTConfig(cfg); err != nil {
return nil, fmt.Errorf("failed to load JWT config: %w", err)
}
// Load API key // Load API key
cfg.APIKey = getEnv("API_KEY", "") cfg.APIKey = getEnv("API_KEY", "")
return cfg, nil return cfg, nil
} }
// loadJWTConfig loads JWT configuration from environment
func loadJWTConfig(cfg *Config) error {
cfg.JWTConfig.Secret = getEnv("JWT_SECRET", "")
defaultDuration := 24 * time.Hour
durationStr := getEnv("JWT_TOKEN_DURATION", defaultDuration.String())
duration, err := time.ParseDuration(durationStr)
if err != nil {
return fmt.Errorf("invalid JWT_TOKEN_DURATION: %w", err)
}
cfg.JWTConfig.TokenDuration = duration
keyGenerateStr := getEnv("JWT_KEY_GENERATE", "true")
keyGenerate, err := strconv.ParseBool(keyGenerateStr)
if err != nil {
return fmt.Errorf("invalid JWT_KEY_GENERATE: %w", err)
}
cfg.JWTConfig.KeyGenerate = keyGenerate
cfg.JWTConfig.KeyDir = getEnv("JWT_KEY_DIR", "./keys")
cfg.JWTConfig.PrivKeyFile = getEnv("JWT_PRIV_KEY_FILE", "jwt.key")
cfg.JWTConfig.PubKeyFile = getEnv("JWT_PUB_KEY_FILE", "jwt.key.pub")
keyBitsStr := getEnv("JWT_KEY_BITS", "2048")
keyBits, err := strconv.Atoi(keyBitsStr)
if err != nil {
return fmt.Errorf("invalid JWT_KEY_BITS: %w", err)
}
cfg.JWTConfig.KeyBits = keyBits
return nil
}
// loadDatabaseConfig loads database configuration from environment // loadDatabaseConfig loads database configuration from environment
func loadDatabaseConfig(cfg *Config) error { func loadDatabaseConfig(cfg *Config) error {
// Required fields // Required fields

View File

@ -1,13 +0,0 @@
package models
import "time"
type JWTConfig struct {
Secret string `env:"JWT_SECRET" default:""`
TokenDuration time.Duration `env:"JWT_TOKEN_DURATION" default:"24h"`
KeyGenerate bool `env:"JWT_KEY_GENERATE" default:"true"`
KeyDir string `env:"JWT_KEY_DIR" default:"./keys"`
PrivKeyFile string `env:"JWT_PRIV_KEY_FILE" default:"jwt.key"`
PubKeyFile string `env:"JWT_PUB_KEY_FILE" default:"jwt.key.pub"`
KeyBits int `env:"JWT_KEY_BITS" default:"2048"`
}