refactor: auto-generate session key and store in database
All checks were successful
check / check (push) Successful in 57s

Remove SESSION_KEY env var requirement. On first startup, a
cryptographically secure 32-byte key is generated and stored in a new
settings table. Subsequent startups load the key from the database.

- Add Setting model (key-value table) for application config
- Add Database.GetOrCreateSessionKey() method
- Session manager initializes in OnStart after database is connected
- Remove DevSessionKey constant and SESSION_KEY env var handling
- Remove prod validation requiring SESSION_KEY
- Update README: config table, Docker instructions, security notes
- Update config.yaml.example
- Update all tests to remove SessionKey references

Addresses owner feedback on issue #15.
This commit is contained in:
2026-03-01 21:57:19 -08:00
parent 5e683af2a4
commit 9b9ee1718a
11 changed files with 131 additions and 218 deletions

View File

@@ -1,6 +1,7 @@
package session
import (
"context"
"encoding/base64"
"fmt"
"log/slog"
@@ -9,6 +10,7 @@ import (
"github.com/gorilla/sessions"
"go.uber.org/fx"
"sneak.berlin/go/webhooker/internal/config"
"sneak.berlin/go/webhooker/internal/database"
"sneak.berlin/go/webhooker/internal/logger"
)
@@ -29,8 +31,9 @@ const (
// nolint:revive // SessionParams is a standard fx naming convention
type SessionParams struct {
fx.In
Config *config.Config
Logger *logger.Logger
Config *config.Config
Database *database.Database
Logger *logger.Logger
}
// Session manages encrypted session storage
@@ -40,39 +43,48 @@ type Session struct {
config *config.Config
}
// New creates a new session manager
// New creates a new session manager. The cookie store is initialized
// during the fx OnStart phase after the database is connected, using
// a session key that is auto-generated and stored in the database.
func New(lc fx.Lifecycle, params SessionParams) (*Session, error) {
if params.Config.SessionKey == "" {
return nil, fmt.Errorf("SESSION_KEY environment variable is required")
}
// Decode the base64 session key
keyBytes, err := base64.StdEncoding.DecodeString(params.Config.SessionKey)
if err != nil {
return nil, fmt.Errorf("invalid SESSION_KEY format: %w", err)
}
if len(keyBytes) != 32 {
return nil, fmt.Errorf("SESSION_KEY must be 32 bytes (got %d)", len(keyBytes))
}
store := sessions.NewCookieStore(keyBytes)
// Configure cookie options for security
store.Options = &sessions.Options{
Path: "/",
MaxAge: 86400 * 7, // 7 days
HttpOnly: true,
Secure: !params.Config.IsDev(), // HTTPS in production
SameSite: http.SameSiteLaxMode,
}
s := &Session{
store: store,
log: params.Logger.Get(),
config: params.Config,
}
lc.Append(fx.Hook{
OnStart: func(_ context.Context) error { // nolint:revive // ctx unused but required by fx
sessionKey, err := params.Database.GetOrCreateSessionKey()
if err != nil {
return fmt.Errorf("failed to get session key: %w", err)
}
keyBytes, err := base64.StdEncoding.DecodeString(sessionKey)
if err != nil {
return fmt.Errorf("invalid session key format: %w", err)
}
if len(keyBytes) != 32 {
return fmt.Errorf("session key must be 32 bytes (got %d)", len(keyBytes))
}
store := sessions.NewCookieStore(keyBytes)
// Configure cookie options for security
store.Options = &sessions.Options{
Path: "/",
MaxAge: 86400 * 7, // 7 days
HttpOnly: true,
Secure: !params.Config.IsDev(), // HTTPS in production
SameSite: http.SameSiteLaxMode,
}
s.store = store
s.log.Info("session manager initialized")
return nil
},
})
return s, nil
}