diff options
| author | haturatu <taro@eyes4you.org> | 2025-10-13 00:08:25 +0900 |
|---|---|---|
| committer | haturatu <taro@eyes4you.org> | 2025-10-13 00:08:25 +0900 |
| commit | 15830af5b190cfb6f28e0bdf0f4bf110256ed9ef (patch) | |
| tree | efd3c4bdd00f8bea6df8ba2155015d18db5cfba2 /cmd | |
| parent | 6515a6fd2b2d29a8f363c906148f3abf7cf982e9 (diff) | |
fix(csrf): js csrf support
Diffstat (limited to 'cmd')
| -rw-r--r-- | cmd/server/main.go | 43 |
1 files changed, 31 insertions, 12 deletions
diff --git a/cmd/server/main.go b/cmd/server/main.go index 196164e..b60c1e0 100644 --- a/cmd/server/main.go +++ b/cmd/server/main.go @@ -15,6 +15,7 @@ import ( "time" "github.com/joho/godotenv" + "github.com/gorilla/csrf" ) func main() { @@ -113,6 +114,7 @@ func main() { // --- Protected API Endpoints (for Admin UI, protected by SessionAuth) --- adminCreateUserAPI := http.HandlerFunc(handlers.CreateUserHandler) + getUsersHandler := http.HandlerFunc(handlers.GetUsersHandler) adminUsersAPI := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.Method == http.MethodPost { adminCreateUserAPI.ServeHTTP(w, r) @@ -175,24 +177,41 @@ func main() { } listenAddr := ":" + port - // --- Start Server --- - logging.AppLog.Info("Server starting on " + listenAddr) - - // Start periodic background tasks - - go startBackgroundTasks(pool, rateLimiter) - - + // --- CSRF Protection --- + csrfSecret := os.Getenv("CSRF_SECRET_KEY") + if csrfSecret == "" { + logging.AppLog.Error("CSRF_SECRET_KEY environment variable not set") + os.Exit(1) + } + // In production, you should set csrf.Secure(true). + // You can use an environment variable to control this setting. + csrfOptions := []csrf.Option{ + csrf.Secure(true), // Set to true in production + csrf.Path("/"), + } - if err := http.ListenAndServe(listenAddr, finalHandler); err != nil { + trustedOrigins := os.Getenv("CSRF_TRUSTED_ORIGINS") + if trustedOrigins != "" { + origins := strings.Split(trustedOrigins, ",") + csrfOptions = append(csrfOptions, csrf.TrustedOrigins(origins)) + } - logging.AppLog.Error("Server failed to start", "error", err) + csrfMiddleware := csrf.Protect( + []byte(csrfSecret), + csrfOptions..., + ) - os.Exit(1) + // --- Start Server --- + logging.AppLog.Info("Server starting on " + listenAddr) - } + // Start periodic background tasks + go startBackgroundTasks(pool, rateLimiter) + if err := http.ListenAndServe(listenAddr, csrfMiddleware(finalHandler)); err != nil { + logging.AppLog.Error("Server failed to start", "error", err) + os.Exit(1) } +} |
