فهرست منبع

Merge commit from fork

security: GHSA-682r-vp23-j9gj (HIGH) bound the in-memory execution log history
James Read 14 ساعت پیش
والد
کامیت
e5cd02d024

+ 1 - 0
docs/modules/ROOT/pages/config.adoc

@@ -122,6 +122,7 @@ All configuration options are covered in the solution sections
 | Option | Description | Default | Live Reloadable | Documentation
 
 | `logLevel` | The log level to use. `INFO`, `DEBUG`, `WARN`, `TRACE` | `INFO` | Requires Restart | xref:advanced_configuration/logs.adoc[Logging]
+| `logHistoryLimit` | The maximum number of execution logs kept in memory. The oldest finished logs are removed first. Minimum `100`. | `2000` | Requires Restart | xref:logs/saving.adoc#log-history-limit[Saving logs]
 | `logDebugOptions` | Enable various debug logs. | `-` | Requires Restart | xref:troubleshooting/advanced.adoc[Advanced Troubleshooting]
 | `Insecure*` | Various options to disable security features. | `false` | Restart recommended | xref:troubleshooting/advanced.adoc[Advanced Troubleshooting]
 |===

+ 15 - 0
docs/modules/ROOT/pages/logs/saving.adoc

@@ -3,6 +3,21 @@
 
 By default, OliveTin only keeps logs in memory, meaning that if you restart OliveTin your logs will be lost. For some use cases this is acceptable, but you can configure OliveTin to save logs for you.
 
+[#log-history-limit]
+== How many logs are kept in memory
+
+OliveTin keeps up to 2000 execution logs in memory, which is what the Logs pages show. When there are more, the oldest finished logs are removed. Logs for executions that are still running or queued are never removed, and neither are logs that still count towards an action's xref:action_customization/ratelimiting.adoc[rate limit].
+
+You can change the limit with `logHistoryLimit` (minimum `100`):
+
+[source,yaml]
+.`config.yaml`
+----
+logHistoryLimit: 5000
+----
+
+Logs saved to disk with `saveLogs` are not removed. When OliveTin starts, it loads the newest saved logs up to the limit.
+
 When `saveLogs` is enabled, OliveTin writes a file for each configured directory when an execution finishes — a results YAML when `resultsDirectory` is set, and an output log when `outputDirectory` is set. If only one directory is configured, only that file type is written. This includes blocked runs (for example when concurrency or rate limits prevent the action from starting).
 
 You can configure the global setting for saving logs, or override it on a per-action basis;

+ 7 - 0
docs/modules/ROOT/pages/upgrade/upgrade_notes.adoc

@@ -40,6 +40,13 @@ Webhook-triggered actions were already required to use `exec:`. This rule now al
 
 If a webhook action in your config triggers an action that uses `shell:` or `shellAfterCompleted`, that action will now fail with "webhooks cannot use Shell execution". Change it to use `exec:` instead. See xref:action_execution/shellvsexec.adoc[Shell vs Exec].
 
+[#log-history-limit]
+=== The number of execution logs kept in memory is now limited
+
+OliveTin now keeps up to 2000 execution logs in memory, and removes the oldest finished logs when there are more. Previously every execution since OliveTin started was kept in memory, so long-running instances showed their full history on the Logs pages.
+
+If you want a longer history in the web interface, raise `logHistoryLimit` in your config. Logs saved to disk with `saveLogs` are not affected. See xref:logs/saving.adoc#log-history-limit[How many logs are kept in memory].
+
 == 2024.08.14
 
 === Navigation change - Subpaths no longer supported

+ 8 - 0
service/internal/config/config.go

@@ -245,6 +245,7 @@ type Config struct {
 	sourceFiles                        []string
 	AuthLocalUsers                     AuthLocalUsersConfig `koanf:"authLocalUsers"`
 	LogHistoryPageSize                 int64                `koanf:"logHistoryPageSize"`
+	LogHistoryLimit                    int                  `koanf:"logHistoryLimit"`
 	LogDebugOptions                    LogDebugOptions      `koanf:"logDebugOptions"`
 	DefaultPermissions                 PermissionsList      `koanf:"defaultPermissions"`
 	DefaultPolicy                      ConfigurationPolicy  `koanf:"defaultPolicy"`
@@ -333,6 +334,12 @@ type DashboardComponent struct {
 	Contents     []*DashboardComponent `koanf:"contents"`
 }
 
+// DefaultLogHistoryLimit is how many execution logs are kept in memory by default.
+const DefaultLogHistoryLimit = 2000
+
+// MinimumLogHistoryLimit stops the in-memory log history being configured too small to be useful.
+const MinimumLogHistoryLimit = 100
+
 func DefaultConfig() *Config {
 	return DefaultConfigWithBasePort(1337)
 }
@@ -350,6 +357,7 @@ func DefaultConfigWithBasePort(basePort int) *Config {
 	config.ExternalRestAddress = "."
 	config.LogLevel = "INFO"
 	config.LogHistoryPageSize = 10
+	config.LogHistoryLimit = DefaultLogHistoryLimit
 	config.CheckForUpdates = false
 	config.DefaultPermissions.Exec = true
 	config.DefaultPermissions.View = true

+ 8 - 0
service/internal/config/sanitize.go

@@ -18,6 +18,7 @@ func (cfg *Config) Sanitize() {
 	cfg.sanitizeLogLevel()
 	cfg.sanitizeAuthRequireGuestsToLogin()
 	cfg.sanitizeLogHistoryPageSize()
+	cfg.sanitizeLogHistoryLimit()
 	cfg.sanitizeLocalUsers()
 	cfg.sanitizeSecurityHeaders()
 	cfg.sanitizeOnClickDefaults()
@@ -358,6 +359,13 @@ func (cfg *Config) sanitizeLogHistoryPageSize() {
 	}
 }
 
+func (cfg *Config) sanitizeLogHistoryLimit() {
+	if cfg.LogHistoryLimit < MinimumLogHistoryLimit {
+		log.Warnf("logHistoryLimit %d is too low, setting it to %d", cfg.LogHistoryLimit, MinimumLogHistoryLimit)
+		cfg.LogHistoryLimit = MinimumLogHistoryLimit
+	}
+}
+
 func (cfg *Config) sanitizeLocalUsers() {
 	for _, user := range cfg.AuthLocalUsers.Users {
 		expandLocalUserEnvTemplates(user)

+ 3 - 1
service/internal/executor/executor.go

@@ -62,6 +62,7 @@ type Executor struct {
 	MapActionBindingsLock sync.RWMutex
 	listenersMu           sync.RWMutex
 	groupQueueMu          sync.Mutex
+	nextLogIndex          int64
 }
 
 // ExecutionRequest is a request to execute an action. It's passed to an
@@ -572,10 +573,11 @@ func (e *Executor) SetLog(trackingID string, entry *InternalLogEntry) string {
 		entry.ExecutionTrackingID = trackingID
 	}
 
-	entry.Index = int64(len(e.logsTrackingIdsByDate))
+	entry.Index = e.takeNextLogIndexLocked()
 
 	e.logs[trackingID] = entry
 	e.logsTrackingIdsByDate = append(e.logsTrackingIdsByDate, trackingID)
+	e.evictOldLogsLocked(time.Now())
 
 	return trackingID
 }

+ 4 - 1
service/internal/executor/loadlogs.go

@@ -5,6 +5,7 @@ import (
 	"path/filepath"
 	"sort"
 	"strings"
+	"time"
 
 	log "github.com/sirupsen/logrus"
 	"gopkg.in/yaml.v3"
@@ -165,7 +166,7 @@ func (e *Executor) restoreLogsToExecutor(loadedLogs []*InternalLogEntry, skipped
 			continue
 		}
 
-		logEntry.Index = int64(len(e.logsTrackingIdsByDate))
+		logEntry.Index = e.takeNextLogIndexLocked()
 		e.logs[logEntry.ExecutionTrackingID] = logEntry
 		e.logsTrackingIdsByDate = append(e.logsTrackingIdsByDate, logEntry.ExecutionTrackingID)
 
@@ -174,6 +175,8 @@ func (e *Executor) restoreLogsToExecutor(loadedLogs []*InternalLogEntry, skipped
 		}
 	}
 
+	e.evictOldLogsLocked(time.Now())
+
 	return skippedCount
 }
 

+ 116 - 0
service/internal/executor/log_retention.go

@@ -0,0 +1,116 @@
+package executor
+
+import (
+	"slices"
+	"time"
+
+	config "github.com/OliveTin/OliveTin/internal/config"
+)
+
+// The in-memory log history is capped so that requests cannot grow it without
+// limit. The oldest finished entries are evicted first. Entries are never
+// evicted while they are still running or queued, or while they still count
+// towards their action's maxRate window, because evicting those would let
+// unrelated requests reset an action's rate limit. Logs saved to disk are not
+// affected.
+
+func (e *Executor) takeNextLogIndexLocked() int64 {
+	index := e.nextLogIndex
+	e.nextLogIndex++
+	return index
+}
+
+func (e *Executor) logHistoryLimit() int {
+	if e.Cfg == nil || e.Cfg.LogHistoryLimit <= 0 {
+		return config.DefaultLogHistoryLimit
+	}
+
+	return e.Cfg.LogHistoryLimit
+}
+
+// evictOldLogsLocked must be called with logmutex held for writing.
+func (e *Executor) evictOldLogsLocked(now time.Time) {
+	excess := len(e.logsTrackingIdsByDate) - e.logHistoryLimit()
+	if excess <= 0 {
+		return
+	}
+
+	kept := make([]string, 0, len(e.logsTrackingIdsByDate)-excess)
+
+	for _, trackingID := range e.logsTrackingIdsByDate {
+		if excess > 0 && canEvictLogEntry(e.logs[trackingID], now) {
+			e.removeLogLocked(trackingID)
+			excess--
+			continue
+		}
+
+		kept = append(kept, trackingID)
+	}
+
+	e.logsTrackingIdsByDate = kept
+}
+
+func canEvictLogEntry(entry *InternalLogEntry, now time.Time) bool {
+	if entry == nil {
+		return true
+	}
+
+	if !entry.ExecutionFinished {
+		return false
+	}
+
+	return !countsTowardsRateLimit(entry, now)
+}
+
+func countsTowardsRateLimit(entry *InternalLogEntry, now time.Time) bool {
+	if entry.Binding == nil || entry.Binding.Action == nil {
+		return false
+	}
+
+	window := longestRateWindow(entry.Binding.Action.MaxRate)
+	if window <= 0 {
+		return false
+	}
+
+	return shouldCountExecution(entry, now.Add(-window))
+}
+
+func longestRateWindow(rates []config.RateSpec) time.Duration {
+	longest := time.Duration(0)
+
+	for _, rate := range rates {
+		longest = max(longest, parseDuration(rate))
+	}
+
+	return longest
+}
+
+func (e *Executor) removeLogLocked(trackingID string) {
+	entry := e.logs[trackingID]
+	delete(e.logs, trackingID)
+
+	if entry == nil || entry.Binding == nil {
+		return
+	}
+
+	e.removeLogFromBindingLocked(entry)
+}
+
+func (e *Executor) removeLogFromBindingLocked(entry *InternalLogEntry) {
+	bindingID := entry.Binding.ID
+	bindingLogs := e.LogsByBindingId[bindingID]
+
+	index := slices.Index(bindingLogs, entry)
+	if index < 0 {
+		return
+	}
+
+	if len(bindingLogs) == 1 {
+		delete(e.LogsByBindingId, bindingID)
+		return
+	}
+
+	// Build a new slice rather than deleting in place, because callers may still
+	// be reading the previous slice after releasing the lock.
+	e.LogsByBindingId[bindingID] = slices.Concat(bindingLogs[:index], bindingLogs[index+1:])
+}

+ 180 - 0
service/internal/executor/log_retention_test.go

@@ -0,0 +1,180 @@
+package executor
+
+import (
+	"testing"
+	"time"
+
+	auth "github.com/OliveTin/OliveTin/internal/auth"
+	config "github.com/OliveTin/OliveTin/internal/config"
+	"github.com/stretchr/testify/assert"
+	"github.com/stretchr/testify/require"
+)
+
+func newRetentionTestExecutor(t *testing.T, action *config.Action) (*Executor, *config.Config, *ActionBinding) {
+	t.Helper()
+
+	cfg := config.DefaultConfig()
+	cfg.LogHistoryLimit = config.MinimumLogHistoryLimit
+	cfg.Actions = append(cfg.Actions, action)
+	cfg.Sanitize()
+
+	e := DefaultExecutor(cfg)
+	e.RebuildActionMap()
+
+	binding := e.FindBindingWithNoEntity(action)
+	require.NotNil(t, binding)
+
+	return e, cfg, binding
+}
+
+func addRetentionTestLog(e *Executor, entry *InternalLogEntry) {
+	e.logmutex.Lock()
+	e.addLogToBindingMap(entry)
+	e.logmutex.Unlock()
+
+	e.SetLog(entry.ExecutionTrackingID, entry)
+}
+
+func assertLogStoresConsistent(t *testing.T, e *Executor, bindingID string) {
+	t.Helper()
+
+	e.logmutex.RLock()
+	defer e.logmutex.RUnlock()
+
+	assert.Len(t, e.logs, len(e.logsTrackingIdsByDate), "map and date index must hold the same entries")
+	for _, entry := range e.LogsByBindingId[bindingID] {
+		_, found := e.logs[entry.ExecutionTrackingID]
+		assert.True(t, found, "per-binding logs must not keep evicted entries")
+	}
+}
+
+func TestLogHistoryEvictsOldestFinishedEntries(t *testing.T) {
+	e, cfg, binding := newRetentionTestExecutor(t, &config.Action{Title: "retention", Shell: "true"})
+
+	entries := make([]*InternalLogEntry, 0, 250)
+	for range 250 {
+		entry := newQueueTestLogEntry(binding, true)
+		entries = append(entries, entry)
+		addRetentionTestLog(e, entry)
+	}
+
+	e.logmutex.RLock()
+	assert.Len(t, e.logsTrackingIdsByDate, cfg.LogHistoryLimit)
+	assert.Equal(t, entries[150].ExecutionTrackingID, e.logsTrackingIdsByDate[0], "oldest entries are evicted first")
+	assert.Len(t, e.LogsByBindingId[binding.ID], cfg.LogHistoryLimit)
+	e.logmutex.RUnlock()
+
+	_, found := e.GetLog(entries[0].ExecutionTrackingID)
+	assert.False(t, found)
+	_, found = e.GetLog(entries[249].ExecutionTrackingID)
+	assert.True(t, found)
+	assert.Equal(t, int64(249), entries[249].Index, "indexes keep increasing after eviction")
+
+	assertLogStoresConsistent(t, e, binding.ID)
+}
+
+func TestLogHistoryKeepsRunningEntries(t *testing.T) {
+	e, cfg, binding := newRetentionTestExecutor(t, &config.Action{Title: "retention", Shell: "true"})
+
+	running := newQueueTestLogEntry(binding, false)
+	addRetentionTestLog(e, running)
+
+	for range 250 {
+		addRetentionTestLog(e, newQueueTestLogEntry(binding, true))
+	}
+
+	_, found := e.GetLog(running.ExecutionTrackingID)
+	assert.True(t, found, "running executions must never be evicted")
+
+	e.logmutex.RLock()
+	assert.Len(t, e.logsTrackingIdsByDate, cfg.LogHistoryLimit)
+	e.logmutex.RUnlock()
+	assertLogStoresConsistent(t, e, binding.ID)
+}
+
+func TestLogHistoryKeepsEntriesCountingTowardsRateLimit(t *testing.T) {
+	limited := &config.Action{
+		Title:   "rate limited",
+		Shell:   "true",
+		MaxRate: []config.RateSpec{{Limit: 3, Duration: "1h"}},
+	}
+	e, _, limitedBinding := newRetentionTestExecutor(t, limited)
+
+	other := &config.Action{Title: "other", Shell: "true"}
+	e.Cfg.Actions = append(e.Cfg.Actions, other)
+	e.RebuildActionMap()
+	otherBinding := e.FindBindingWithNoEntity(other)
+	require.NotNil(t, otherBinding)
+
+	counted := make([]*InternalLogEntry, 0, 3)
+	for range 3 {
+		entry := newQueueTestLogEntry(limitedBinding, true)
+		counted = append(counted, entry)
+		addRetentionTestLog(e, entry)
+	}
+
+	blocked := newQueueTestLogEntry(limitedBinding, true)
+	blocked.Blocked = true
+	addRetentionTestLog(e, blocked)
+
+	for range 250 {
+		addRetentionTestLog(e, newQueueTestLogEntry(otherBinding, true))
+	}
+
+	for _, entry := range counted {
+		_, found := e.GetLog(entry.ExecutionTrackingID)
+		assert.True(t, found, "entries inside the maxRate window must not be evicted")
+	}
+
+	_, found := e.GetLog(blocked.ExecutionTrackingID)
+	assert.False(t, found, "blocked entries do not count towards the rate limit and can be evicted")
+
+	req := &ExecutionRequest{Binding: limitedBinding, executor: e, logEntry: &InternalLogEntry{}}
+	assert.Equal(t, 3, getExecutionsCount(limited.MaxRate[0], req), "flooding other actions must not reset the rate limit")
+	assertLogStoresConsistent(t, e, limitedBinding.ID)
+}
+
+func TestLogHistoryBoundsDeniedRequests(t *testing.T) {
+	action := &config.Action{Title: "admins only", Shell: "true"}
+	e, cfg, binding := newRetentionTestExecutor(t, action)
+	cfg.DefaultPermissions.Exec = false
+	user := auth.UserGuest(cfg)
+
+	for range 250 {
+		wg, _ := e.ExecRequest(&ExecutionRequest{AuthenticatedUser: user, Cfg: cfg, Binding: binding})
+		wg.Wait()
+	}
+
+	e.logmutex.RLock()
+	defer e.logmutex.RUnlock()
+	assert.LessOrEqual(t, len(e.logsTrackingIdsByDate), cfg.LogHistoryLimit, "denied requests must not grow the log store without limit")
+	assert.LessOrEqual(t, len(e.LogsByBindingId[binding.ID]), cfg.LogHistoryLimit)
+}
+
+func TestLogHistoryLimitIsSanitized(t *testing.T) {
+	cfg := config.DefaultConfig()
+	assert.Equal(t, config.DefaultLogHistoryLimit, cfg.LogHistoryLimit)
+
+	cfg.LogHistoryLimit = 5
+	cfg.Sanitize()
+	assert.Equal(t, config.MinimumLogHistoryLimit, cfg.LogHistoryLimit)
+}
+
+func TestLogHistoryLoadedFromDiskIsBounded(t *testing.T) {
+	e, cfg, binding := newRetentionTestExecutor(t, &config.Action{Title: "retention", Shell: "true"})
+
+	loaded := make([]*InternalLogEntry, 0, 250)
+	for i := range 250 {
+		entry := newQueueTestLogEntry(binding, true)
+		entry.DatetimeStarted = time.Now().Add(time.Duration(i-250) * time.Minute)
+		loaded = append(loaded, entry)
+	}
+
+	e.restoreLogsToExecutor(loaded, 0)
+
+	e.logmutex.RLock()
+	assert.Len(t, e.logsTrackingIdsByDate, cfg.LogHistoryLimit)
+	assert.Equal(t, loaded[150].ExecutionTrackingID, e.logsTrackingIdsByDate[0], "the newest loaded logs are kept")
+	e.logmutex.RUnlock()
+	assertLogStoresConsistent(t, e, binding.ID)
+}