Use lowercase for log messages

This commit is contained in:
2024-12-15 17:13:40 +01:00
parent a32e0957ed
commit 8dd57bdf0b
4 changed files with 51 additions and 48 deletions

View File

@@ -58,46 +58,46 @@ func (c *Config) validate() error {
// LoadConfig creates a new Config instance with values from environment variables // LoadConfig creates a new Config instance with values from environment variables
func LoadConfig() (*Config, error) { func LoadConfig() (*Config, error) {
logging.Info("Loading configuration from environment variables") logging.Info("loading configuration from environment variables")
config := DefaultConfig() config := DefaultConfig()
if env := os.Getenv("NOVAMD_ENV"); env != "" { if env := os.Getenv("NOVAMD_ENV"); env != "" {
logging.Debug("Loading config for environment", "env", env) logging.Debug("loading config for environment", "env", env)
config.IsDevelopment = env == "development" config.IsDevelopment = env == "development"
} }
if dbPath := os.Getenv("NOVAMD_DB_PATH"); dbPath != "" { if dbPath := os.Getenv("NOVAMD_DB_PATH"); dbPath != "" {
logging.Debug("Loading config for database path", "path", dbPath) logging.Debug("loading config for database path", "path", dbPath)
config.DBPath = dbPath config.DBPath = dbPath
} }
if workDir := os.Getenv("NOVAMD_WORKDIR"); workDir != "" { if workDir := os.Getenv("NOVAMD_WORKDIR"); workDir != "" {
logging.Debug("Loading config for work directory", "dir", workDir) logging.Debug("loading config for work directory", "dir", workDir)
config.WorkDir = workDir config.WorkDir = workDir
} }
if staticPath := os.Getenv("NOVAMD_STATIC_PATH"); staticPath != "" { if staticPath := os.Getenv("NOVAMD_STATIC_PATH"); staticPath != "" {
logging.Debug("Loading config for static path", "path", staticPath) logging.Debug("loading config for static path", "path", staticPath)
config.StaticPath = staticPath config.StaticPath = staticPath
} }
if port := os.Getenv("NOVAMD_PORT"); port != "" { if port := os.Getenv("NOVAMD_PORT"); port != "" {
logging.Debug("Loading config for port", "port", port) logging.Debug("loading config for port", "port", port)
config.Port = port config.Port = port
} }
if rootURL := os.Getenv("NOVAMD_ROOT_URL"); rootURL != "" { if rootURL := os.Getenv("NOVAMD_ROOT_URL"); rootURL != "" {
logging.Debug("Loading config for root URL", "url", rootURL) logging.Debug("loading config for root URL", "url", rootURL)
config.RootURL = rootURL config.RootURL = rootURL
} }
if domain := os.Getenv("NOVAMD_DOMAIN"); domain != "" { if domain := os.Getenv("NOVAMD_DOMAIN"); domain != "" {
logging.Debug("Loading config for domain", "domain", domain) logging.Debug("loading config for domain", "domain", domain)
config.Domain = domain config.Domain = domain
} }
if corsOrigins := os.Getenv("NOVAMD_CORS_ORIGINS"); corsOrigins != "" { if corsOrigins := os.Getenv("NOVAMD_CORS_ORIGINS"); corsOrigins != "" {
logging.Debug("Loading config for CORS origins", "origins", corsOrigins) logging.Debug("loading config for CORS origins", "origins", corsOrigins)
config.CORSOrigins = strings.Split(corsOrigins, ",") config.CORSOrigins = strings.Split(corsOrigins, ",")
} }
@@ -106,7 +106,7 @@ func LoadConfig() (*Config, error) {
config.EncryptionKey = os.Getenv("NOVAMD_ENCRYPTION_KEY") config.EncryptionKey = os.Getenv("NOVAMD_ENCRYPTION_KEY")
config.JWTSigningKey = os.Getenv("NOVAMD_JWT_SIGNING_KEY") config.JWTSigningKey = os.Getenv("NOVAMD_JWT_SIGNING_KEY")
logging.Debug("Sensitive configuration loaded", logging.Debug("sensitive configuration loaded",
"adminEmailSet", config.AdminEmail != "", "adminEmailSet", config.AdminEmail != "",
"adminPasswordSet", config.AdminPassword != "", "adminPasswordSet", config.AdminPassword != "",
"encryptionKeySet", config.EncryptionKey != "", "encryptionKeySet", config.EncryptionKey != "",
@@ -116,12 +116,12 @@ func LoadConfig() (*Config, error) {
if reqStr := os.Getenv("NOVAMD_RATE_LIMIT_REQUESTS"); reqStr != "" { if reqStr := os.Getenv("NOVAMD_RATE_LIMIT_REQUESTS"); reqStr != "" {
parsed, err := strconv.Atoi(reqStr) parsed, err := strconv.Atoi(reqStr)
if err != nil { if err != nil {
logging.Warn("Invalid rate limit requests value, using default", logging.Warn("invalid rate limit requests value, using default",
"value", reqStr, "value", reqStr,
"default", config.RateLimitRequests, "default", config.RateLimitRequests,
"error", err) "error", err)
} else { } else {
logging.Debug("Loading config for rate limit requests", "requests", parsed) logging.Debug("loading config for rate limit requests", "requests", parsed)
config.RateLimitRequests = parsed config.RateLimitRequests = parsed
} }
} }
@@ -129,12 +129,12 @@ func LoadConfig() (*Config, error) {
if windowStr := os.Getenv("NOVAMD_RATE_LIMIT_WINDOW"); windowStr != "" { if windowStr := os.Getenv("NOVAMD_RATE_LIMIT_WINDOW"); windowStr != "" {
parsed, err := time.ParseDuration(windowStr) parsed, err := time.ParseDuration(windowStr)
if err != nil { if err != nil {
logging.Warn("Invalid rate limit window value, using default", logging.Warn("invalid rate limit window value, using default",
"value", windowStr, "value", windowStr,
"default", config.RateLimitWindow, "default", config.RateLimitWindow,
"error", err) "error", err)
} else { } else {
logging.Debug("Loading config for rate limit window", "window", parsed) logging.Debug("loading config for rate limit window", "window", parsed)
config.RateLimitWindow = parsed config.RateLimitWindow = parsed
} }
} }
@@ -142,13 +142,13 @@ func LoadConfig() (*Config, error) {
// Configure log level, if isDevelopment is set, default to debug // Configure log level, if isDevelopment is set, default to debug
if logLevel := os.Getenv("NOVAMD_LOG_LEVEL"); logLevel != "" { if logLevel := os.Getenv("NOVAMD_LOG_LEVEL"); logLevel != "" {
parsed := logging.ParseLogLevel(logLevel) parsed := logging.ParseLogLevel(logLevel)
logging.Debug("Loading config for log level", "level", parsed) logging.Debug("loading config for log level", "level", parsed)
config.LogLevel = parsed config.LogLevel = parsed
} else if config.IsDevelopment { } else if config.IsDevelopment {
logging.Debug("Setting log level to debug for development") logging.Debug("setting log level to debug for development")
config.LogLevel = logging.DEBUG config.LogLevel = logging.DEBUG
} else { } else {
logging.Debug("Setting log level to info for production") logging.Debug("setting log level to info for production")
config.LogLevel = logging.INFO config.LogLevel = logging.INFO
} }
@@ -157,6 +157,6 @@ func LoadConfig() (*Config, error) {
return nil, err return nil, err
} }
logging.Info("Configuration loaded successfully") logging.Info("configuration loaded successfully")
return config, nil return config, nil
} }

View File

@@ -18,41 +18,44 @@ import (
// initSecretsService initializes the secrets service // initSecretsService initializes the secrets service
func initSecretsService(cfg *Config) (secrets.Service, error) { func initSecretsService(cfg *Config) (secrets.Service, error) {
logging.Debug("Initializing secrets service") logging.Debug("initializing secrets service")
secretsService, err := secrets.NewService(cfg.EncryptionKey) secretsService, err := secrets.NewService(cfg.EncryptionKey)
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to initialize secrets service: %w", err) return nil, fmt.Errorf("failed to initialize secrets service: %w", err)
} }
logging.Debug("Secrets service initialized") logging.Debug("secrets service initialized")
return secretsService, nil return secretsService, nil
} }
// initDatabase initializes and migrates the database // initDatabase initializes and migrates the database
func initDatabase(cfg *Config, secretsService secrets.Service) (db.Database, error) { func initDatabase(cfg *Config, secretsService secrets.Service) (db.Database, error) {
logging.Debug("Initializing database", "path", cfg.DBPath) logging.Debug("initializing database", "path", cfg.DBPath)
database, err := db.Init(cfg.DBPath, secretsService) database, err := db.Init(cfg.DBPath, secretsService)
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to initialize database: %w", err) return nil, fmt.Errorf("failed to initialize database: %w", err)
} }
logging.Debug("Running database migrations") logging.Debug("running database migrations")
if err := database.Migrate(); err != nil { if err := database.Migrate(); err != nil {
return nil, fmt.Errorf("failed to apply database migrations: %w", err) return nil, fmt.Errorf("failed to apply database migrations: %w", err)
} }
logging.Debug("Database initialization complete") logging.Debug("database initialization complete")
return database, nil return database, nil
} }
// initAuth initializes JWT and session services // initAuth initializes JWT and session services
func initAuth(cfg *Config, database db.Database) (auth.JWTManager, auth.SessionManager, auth.CookieManager, error) { func initAuth(cfg *Config, database db.Database) (auth.JWTManager, auth.SessionManager, auth.CookieManager, error) {
logging.Debug("Initializing authentication services") logging.Debug("initializing authentication services")
accessTokeExpiry := 15 * time.Minute
refreshTokenExpiry := 7 * 24 * time.Hour
// Get or generate JWT signing key // Get or generate JWT signing key
signingKey := cfg.JWTSigningKey signingKey := cfg.JWTSigningKey
if signingKey == "" { if signingKey == "" {
logging.Debug("No JWT signing key provided, generating new key") logging.Debug("no JWT signing key provided, generating new key")
var err error var err error
signingKey, err = database.EnsureJWTSecret() signingKey, err = database.EnsureJWTSecret()
if err != nil { if err != nil {
@@ -61,37 +64,37 @@ func initAuth(cfg *Config, database db.Database) (auth.JWTManager, auth.SessionM
logging.Debug("JWT signing key generated") logging.Debug("JWT signing key generated")
} }
logging.Debug("Initializing JWT service", logging.Debug("initializing JWT service",
"accessTokenExpiry", "15m", "accessTokenExpiry", accessTokeExpiry.String(),
"refreshTokenExpiry", "168h") "refreshTokenExpiry", refreshTokenExpiry.String())
// Initialize JWT service // Initialize JWT service
jwtManager, err := auth.NewJWTService(auth.JWTConfig{ jwtManager, err := auth.NewJWTService(auth.JWTConfig{
SigningKey: signingKey, SigningKey: signingKey,
AccessTokenExpiry: 15 * time.Minute, AccessTokenExpiry: accessTokeExpiry,
RefreshTokenExpiry: 7 * 24 * time.Hour, RefreshTokenExpiry: refreshTokenExpiry,
}) })
if err != nil { if err != nil {
return nil, nil, nil, fmt.Errorf("failed to initialize JWT service: %w", err) return nil, nil, nil, fmt.Errorf("failed to initialize JWT service: %w", err)
} }
// Initialize session service // Initialize session service
logging.Debug("Initializing session service") logging.Debug("initializing session service")
sessionManager := auth.NewSessionService(database, jwtManager) sessionManager := auth.NewSessionService(database, jwtManager)
// Initialize cookie service // Initialize cookie service
logging.Debug("Initializing cookie service", logging.Debug("initializing cookie service",
"isDevelopment", cfg.IsDevelopment, "isDevelopment", cfg.IsDevelopment,
"domain", cfg.Domain) "domain", cfg.Domain)
cookieService := auth.NewCookieService(cfg.IsDevelopment, cfg.Domain) cookieService := auth.NewCookieService(cfg.IsDevelopment, cfg.Domain)
logging.Debug("Authentication services initialized") logging.Debug("authentication services initialized")
return jwtManager, sessionManager, cookieService, nil return jwtManager, sessionManager, cookieService, nil
} }
// setupAdminUser creates the admin user if it doesn't exist // setupAdminUser creates the admin user if it doesn't exist
func setupAdminUser(database db.Database, storageManager storage.Manager, cfg *Config) error { func setupAdminUser(database db.Database, storageManager storage.Manager, cfg *Config) error {
logging.Debug("Checking for existing admin user", "email", cfg.AdminEmail) logging.Debug("checking for existing admin user", "email", cfg.AdminEmail)
// Check if admin user exists // Check if admin user exists
adminUser, err := database.GetUserByEmail(cfg.AdminEmail) adminUser, err := database.GetUserByEmail(cfg.AdminEmail)
@@ -100,11 +103,11 @@ func setupAdminUser(database db.Database, storageManager storage.Manager, cfg *C
} }
if adminUser != nil { if adminUser != nil {
logging.Debug("Admin user already exists", "userId", adminUser.ID) logging.Debug("admin user already exists", "userId", adminUser.ID)
return nil return nil
} }
logging.Debug("Creating new admin user") logging.Debug("creating new admin user")
// Hash the password // Hash the password
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(cfg.AdminPassword), bcrypt.DefaultCost) hashedPassword, err := bcrypt.GenerateFromPassword([]byte(cfg.AdminPassword), bcrypt.DefaultCost)
@@ -125,12 +128,12 @@ func setupAdminUser(database db.Database, storageManager storage.Manager, cfg *C
return fmt.Errorf("failed to create admin user: %w", err) return fmt.Errorf("failed to create admin user: %w", err)
} }
logging.Debug("Admin user created", logging.Debug("admin user created",
"userId", createdUser.ID, "userId", createdUser.ID,
"workspaceId", createdUser.LastWorkspaceID) "workspaceId", createdUser.LastWorkspaceID)
// Initialize workspace directory // Initialize workspace directory
logging.Debug("Initializing admin workspace directory", logging.Debug("initializing admin workspace directory",
"userId", createdUser.ID, "userId", createdUser.ID,
"workspaceId", createdUser.LastWorkspaceID) "workspaceId", createdUser.LastWorkspaceID)
@@ -139,7 +142,7 @@ func setupAdminUser(database db.Database, storageManager storage.Manager, cfg *C
return fmt.Errorf("failed to initialize admin workspace: %w", err) return fmt.Errorf("failed to initialize admin workspace: %w", err)
} }
logging.Info("Admin user setup completed", logging.Info("admin user setup completed",
"userId", createdUser.ID, "userId", createdUser.ID,
"workspaceId", createdUser.LastWorkspaceID) "workspaceId", createdUser.LastWorkspaceID)

View File

@@ -20,7 +20,7 @@ import (
// setupRouter creates and configures the chi router with middleware and routes // setupRouter creates and configures the chi router with middleware and routes
func setupRouter(o Options) *chi.Mux { func setupRouter(o Options) *chi.Mux {
logging.Debug("Setting up router") logging.Debug("setting up router")
r := chi.NewRouter() r := chi.NewRouter()
// Basic middleware // Basic middleware
@@ -31,7 +31,7 @@ func setupRouter(o Options) *chi.Mux {
r.Use(middleware.Timeout(30 * time.Second)) r.Use(middleware.Timeout(30 * time.Second))
// Security headers // Security headers
logging.Debug("Setting up security headers") logging.Debug("setting up security headers")
r.Use(secure.New(secure.Options{ r.Use(secure.New(secure.Options{
SSLRedirect: false, SSLRedirect: false,
SSLProxyHeaders: map[string]string{"X-Forwarded-Proto": "https"}, SSLProxyHeaders: map[string]string{"X-Forwarded-Proto": "https"},
@@ -39,7 +39,7 @@ func setupRouter(o Options) *chi.Mux {
}).Handler) }).Handler)
// CORS if origins are configured // CORS if origins are configured
logging.Debug("Setting up CORS") logging.Debug("setting up CORS")
if len(o.Config.CORSOrigins) > 0 { if len(o.Config.CORSOrigins) > 0 {
r.Use(cors.Handler(cors.Options{ r.Use(cors.Handler(cors.Options{
AllowedOrigins: o.Config.CORSOrigins, AllowedOrigins: o.Config.CORSOrigins,
@@ -52,7 +52,7 @@ func setupRouter(o Options) *chi.Mux {
} }
// Initialize auth middleware and handler // Initialize auth middleware and handler
logging.Debug("Setting up authentication middleware") logging.Debug("setting up authentication middleware")
authMiddleware := auth.NewMiddleware(o.JWTManager, o.SessionManager, o.CookieService) authMiddleware := auth.NewMiddleware(o.JWTManager, o.SessionManager, o.CookieService)
handler := &handlers.Handler{ handler := &handlers.Handler{
DB: o.Database, DB: o.Database,
@@ -60,14 +60,14 @@ func setupRouter(o Options) *chi.Mux {
} }
if o.Config.IsDevelopment { if o.Config.IsDevelopment {
logging.Debug("Setting up Swagger docs") logging.Debug("setting up Swagger docs")
r.Get("/swagger/*", httpSwagger.Handler( r.Get("/swagger/*", httpSwagger.Handler(
httpSwagger.URL("/swagger/doc.json"), // The URL pointing to API definition httpSwagger.URL("/swagger/doc.json"), // The URL pointing to API definition
)) ))
} }
// API routes // API routes
logging.Debug("Setting up API routes") logging.Debug("setting up API routes")
r.Route("/api/v1", func(r chi.Router) { r.Route("/api/v1", func(r chi.Router) {
// Rate limiting for API routes // Rate limiting for API routes
if o.Config.RateLimitRequests > 0 { if o.Config.RateLimitRequests > 0 {
@@ -154,7 +154,7 @@ func setupRouter(o Options) *chi.Mux {
}) })
// Handle all other routes with static file server // Handle all other routes with static file server
logging.Debug("Setting up static file server") logging.Debug("setting up static file server")
r.Get("/*", handlers.NewStaticHandler(o.Config.StaticPath).ServeHTTP) r.Get("/*", handlers.NewStaticHandler(o.Config.StaticPath).ServeHTTP)
return r return r

View File

@@ -25,13 +25,13 @@ func NewServer(options *Options) *Server {
func (s *Server) Start() error { func (s *Server) Start() error {
// Start server // Start server
addr := ":" + s.options.Config.Port addr := ":" + s.options.Config.Port
logging.Info("Starting server", "address", addr) logging.Info("starting server", "address", addr)
return http.ListenAndServe(addr, s.router) return http.ListenAndServe(addr, s.router)
} }
// Close handles graceful shutdown of server dependencies // Close handles graceful shutdown of server dependencies
func (s *Server) Close() error { func (s *Server) Close() error {
logging.Info("Shutting down server") logging.Info("shutting down server")
return s.options.Database.Close() return s.options.Database.Close()
} }