fix: code quality, memory safety, and install improvements

Critical fixes:
- Fix Dockerfile: reorder stages so frontend assets embed into Go binary
- Fix Go version 1.25 (nonexistent) to 1.24 across Dockerfile, go.mod, CI
- Add graceful game server shutdown on SIGTERM/SIGINT
- Order startup tasks: updates complete before auto-start
- Fix TOCTOU race in UpdateSettings with atomic Update() method

Security:
- Add optional AUTH_TOKEN bearer auth middleware on API/WS routes
- Fix path traversal in DeleteMod using filepath.Rel instead of HasPrefix
- Add input validation for IPPort, ServerParameters, ScheduledUpdate

Memory safety:
- Cap RPT buffer allocation to 64KB to prevent OOM on large logs
- Cap GetLog file read to 10MB
- Fix context cancel leak in SteamCmdManager.run()
- Remove data-raced cancel field in steamcmd.go
- Atomic file writes (write-temp-then-rename) across all managers

Reliability:
- Log save errors in ProcessManager.Stop()
- Atomic file writes prevent corruption on crash

Tests:
- Add mod_manager_test.go (12 tests: ListWorkshopMods, ListLocalMods,
  BuildUsageMap, RemoveMod, dirSize)
- Add scheduler_test.go (6 tests: Start/Stop, Refresh with empty,
  invalid, valid, and replaced cron expressions)
- Add TestRestart to server_process_test.go

CI/Docs:
- Add -race flag to go test in CI and Makefile
- Add npm lint step to CI
- Add Go/npm module caching to CI
- Update README: prerequisites, AUTH_TOKEN/GIN_MODE/SERVERS_DIR docs,
  fix manual quickstart to use make build
This commit is contained in:
MrFastwind
2026-07-25 02:47:04 +02:00
parent 8bf163a931
commit 4d6f162b8f
18 changed files with 638 additions and 88 deletions
+17 -1
View File
@@ -195,7 +195,13 @@ func (h *Handler) StreamRPTLogs(c *gin.Context) {
if _, err := f.Seek(currentOffset, io.SeekStart); err != nil {
return nil
}
buf := make([]byte, fi.Size()-currentOffset)
remaining := fi.Size() - currentOffset
const maxBuf = 64 * 1024
bufSize := remaining
if bufSize > maxBuf {
bufSize = maxBuf
}
buf := make([]byte, bufSize)
n, _ := io.ReadFull(f, buf)
currentOffset += int64(n)
@@ -260,6 +266,16 @@ func (h *Handler) GetLog(c *gin.Context) {
}
}
fi, err := os.Stat(path)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
const maxLogSize = 10 * 1024 * 1024
if fi.Size() > maxLogSize {
c.JSON(http.StatusRequestEntityTooLarge, gin.H{"error": "log file too large, use live streaming"})
return
}
data, err := os.ReadFile(path)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
+9 -1
View File
@@ -49,6 +49,14 @@ func (h *Handler) ListMods(c *gin.Context) {
c.JSON(http.StatusOK, all)
}
func isUnderDir(path, dir string) bool {
rel, err := filepath.Rel(dir, path)
if err != nil {
return false
}
return rel != ".." && !strings.HasPrefix(rel, ".."+string(filepath.Separator))
}
func (h *Handler) DeleteMod(c *gin.Context) {
var input deleteModInput
if err := c.ShouldBindJSON(&input); err != nil {
@@ -62,7 +70,7 @@ func (h *Handler) DeleteMod(c *gin.Context) {
return
}
if !strings.HasPrefix(absPath, h.serverfileDir) && !strings.HasPrefix(absPath, h.modsDir) {
if !isUnderDir(absPath, h.serverfileDir) && !isUnderDir(absPath, h.modsDir) {
c.JSON(http.StatusForbidden, gin.H{"error": "path outside allowed directories"})
return
}
+43 -4
View File
@@ -1,6 +1,10 @@
package api
import (
"net/http"
"os"
"strings"
"arma3-web-server/internal/services"
"github.com/gin-gonic/gin"
@@ -20,6 +24,7 @@ type Handler struct {
cfgDir string
profilesDir string
frontendServed bool
authToken string
}
func New(
@@ -47,11 +52,44 @@ func New(
cfgDir: cfgDir,
profilesDir: profilesDir,
frontendServed: frontendServed,
authToken: os.Getenv("AUTH_TOKEN"),
}
}
func (h *Handler) authMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
if h.authToken == "" {
c.Next()
return
}
auth := c.GetHeader("Authorization")
if !strings.HasPrefix(auth, "Bearer ") {
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "missing or invalid authorization header"})
return
}
token := strings.TrimPrefix(auth, "Bearer ")
if !secureCompare(token, h.authToken) {
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "invalid token"})
return
}
c.Next()
}
}
func secureCompare(a, b string) bool {
if len(a) != len(b) {
return false
}
for i := 0; i < len(a); i++ {
if a[i] != b[i] {
return false
}
}
return true
}
func (h *Handler) SetupRoutes(r *gin.Engine) {
api := r.Group("/api")
api := r.Group("/api", h.authMiddleware())
{
api.GET("/server/settings", h.GetSettings)
api.PUT("/server/settings", h.UpdateSettings)
@@ -93,7 +131,8 @@ func (h *Handler) SetupRoutes(r *gin.Engine) {
api.POST("/mods/cleanup", h.CleanupMods)
}
r.GET("/ws/server/logs", h.StreamLogs)
r.GET("/ws/steamcmd/logs", h.StreamSteamCMDLogs)
r.GET("/ws/server/rpt", h.StreamRPTLogs)
ws := r.Group("/ws", h.authMiddleware())
ws.GET("/server/logs", h.StreamLogs)
ws.GET("/steamcmd/logs", h.StreamSteamCMDLogs)
ws.GET("/server/rpt", h.StreamRPTLogs)
}
+76 -49
View File
@@ -1,9 +1,15 @@
package api
import (
"fmt"
"net"
"net/http"
"strings"
"arma3-web-server/internal/models"
"github.com/gin-gonic/gin"
"github.com/robfig/cron/v3"
)
type updateSettingsInput struct {
@@ -39,65 +45,86 @@ func (h *Handler) UpdateSettings(c *gin.Context) {
return
}
s, err := h.settings.Load()
if input.IPPort != nil && *input.IPPort != "" {
if _, _, err := net.SplitHostPort(*input.IPPort); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("invalid ip_port: must be host:port format: %v", err)})
return
}
}
if input.ServerParameters != nil && len(*input.ServerParameters) > 8192 {
c.JSON(http.StatusBadRequest, gin.H{"error": "server_parameters too long (max 8192)"})
return
}
if input.ScheduledUpdate != nil && *input.ScheduledUpdate != "" {
parser := cron.NewParser(cron.Minute | cron.Hour | cron.Dom | cron.Month | cron.Dow)
if _, err := parser.Parse(*input.ScheduledUpdate); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("invalid cron expression: %v", err)})
return
}
}
if input.ServerParameters != nil {
for _, forbidden := range []string{"--dry-run", "--rm", "--privileged"} {
if strings.Contains(*input.ServerParameters, forbidden) {
c.JSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("server_parameters contains forbidden flag: %s", forbidden)})
return
}
}
}
s, err := h.settings.Update(func(s *models.ServerSettings) {
if input.IPPort != nil {
s.IPPort = *input.IPPort
}
if input.ServerParameters != nil {
s.ServerParameters = *input.ServerParameters
}
if input.SteamBranch != nil {
s.SteamBranch = *input.SteamBranch
}
if input.SteamUser != nil {
s.SteamUser = *input.SteamUser
}
if input.Platform != nil {
s.Platform = *input.Platform
}
if input.CBASettings != nil {
s.CBASettings = *input.CBASettings
}
if input.AILevelPresets != nil {
s.AILevelPresets = *input.AILevelPresets
}
if input.DifficultyPresets != nil {
s.DifficultyPresets = *input.DifficultyPresets
}
if input.ActiveConfig != nil {
s.ActiveConfig = *input.ActiveConfig
}
if input.ActiveModlist != nil {
s.ActiveModlist = *input.ActiveModlist
}
if input.AutoUpdateOnStartup != nil {
s.AutoUpdateOnStartup = *input.AutoUpdateOnStartup
}
if input.AutoStartOnStartup != nil {
s.AutoStartOnStartup = *input.AutoStartOnStartup
}
if input.AutoUpdateModsOnStartup != nil {
s.AutoUpdateModsOnStartup = *input.AutoUpdateModsOnStartup
}
if input.ScheduledUpdate != nil {
s.ScheduledUpdate = *input.ScheduledUpdate
}
})
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
if input.IPPort != nil {
s.IPPort = *input.IPPort
}
if input.ServerParameters != nil {
s.ServerParameters = *input.ServerParameters
}
if input.SteamBranch != nil {
s.SteamBranch = *input.SteamBranch
}
if input.SteamUser != nil {
s.SteamUser = *input.SteamUser
}
if input.Platform != nil {
s.Platform = *input.Platform
}
if input.CBASettings != nil {
s.CBASettings = *input.CBASettings
}
if input.AILevelPresets != nil {
s.AILevelPresets = *input.AILevelPresets
}
if input.DifficultyPresets != nil {
s.DifficultyPresets = *input.DifficultyPresets
}
if input.ActiveConfig != nil {
s.ActiveConfig = *input.ActiveConfig
}
if input.ActiveModlist != nil {
s.ActiveModlist = *input.ActiveModlist
}
if input.AutoUpdateOnStartup != nil {
s.AutoUpdateOnStartup = *input.AutoUpdateOnStartup
}
if input.AutoStartOnStartup != nil {
s.AutoStartOnStartup = *input.AutoStartOnStartup
}
if input.AutoUpdateModsOnStartup != nil {
s.AutoUpdateModsOnStartup = *input.AutoUpdateModsOnStartup
}
if input.ScheduledUpdate != nil {
s.ScheduledUpdate = *input.ScheduledUpdate
}
if err := h.process.WriteUserconfigFiles(s); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "write userconfig: " + err.Error()})
return
}
if err := h.settings.Save(s); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
if h.scheduler != nil {
h.scheduler.Refresh()
}