Просмотр исходного кода

security: GHSA-mgr4-8mh8-frw7 (MED) restart actions using the current config binding

RestartAction reused the binding stored in the old log entry, which can
point at an action that a config reload has since removed or changed.
It now looks the binding ID up in the current action map, returns
NotFound if the action or entity is gone, and runs the current binding,
so ACLs, the command, arguments and justification come from the
current config.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
jamesread 1 день назад
Родитель
Сommit
ffee44dacd

+ 21 - 3
service/internal/api/api.go

@@ -1903,18 +1903,23 @@ func (api *oliveTinAPI) RestartAction(ctx ctx.Context, req *connect.Request[apiv
 		return nil, err
 	}
 
-	if err := validateRestartLogEntry(execReqLogEntry); err != nil {
+	binding, err := api.currentBindingForRestart(execReqLogEntry, req.Msg.ExecutionTrackingId)
+	if err != nil {
+		return nil, err
+	}
+
+	if err := validateRestartLogEntry(binding, execReqLogEntry); err != nil {
 		return nil, err
 	}
 
 	authenticatedUser := auth.UserFromApiCall(ctx, req, api.cfg)
 	restartArgs := copyStringMap(execReqLogEntry.Arguments)
-	if err := api.errUnlessStartEntityAccessAllowed(authenticatedUser, execReqLogEntry.Binding, restartArgs); err != nil {
+	if err := api.errUnlessStartEntityAccessAllowed(authenticatedUser, binding, restartArgs); err != nil {
 		return nil, err
 	}
 
 	execReq := executor.ExecutionRequest{
-		Binding:           execReqLogEntry.Binding,
+		Binding:           binding,
 		Arguments:         restartArgs,
 		Justification:     execReqLogEntry.Justification,
 		AuthenticatedUser: authenticatedUser,
@@ -1945,6 +1950,19 @@ func (api *oliveTinAPI) restartActionLogEntry(executionTrackingId string) (*exec
 	return execReqLogEntry, nil
 }
 
+// A log entry keeps the binding it ran with, which can be out of date after the
+// config is reloaded. Restarts look the binding up again so that they run the
+// action as it is configured now, with its current ACLs, and so that actions
+// removed from the config cannot be restarted.
+func (api *oliveTinAPI) currentBindingForRestart(entry *executor.InternalLogEntry, executionTrackingId string) (*executor.ActionBinding, error) {
+	binding := api.executor.FindBindingByID(entry.Binding.ID)
+	if binding == nil || binding.Action == nil {
+		return nil, connect.NewError(connect.CodeNotFound, fmt.Errorf("action for tracking ID %s is no longer in the configuration", executionTrackingId))
+	}
+
+	return binding, nil
+}
+
 var (
 	executorListenersMu sync.Mutex
 	executorListeners   = map[*executor.Executor]*oliveTinAPI{}

+ 3 - 3
service/internal/api/api_log_arguments.go

@@ -46,12 +46,12 @@ func restartArgumentsIncompleteError() error {
 	return connect.NewError(connect.CodeInvalidArgument, fmt.Errorf("stored arguments are incomplete for restart; use StartAction with the required arguments instead"))
 }
 
-func validateRestartLogEntry(entry *executor.InternalLogEntry) error {
-	if entry.Binding.Action.RequiresJustification() && strings.TrimSpace(entry.Justification) == "" {
+func validateRestartLogEntry(binding *executor.ActionBinding, entry *executor.InternalLogEntry) error {
+	if binding.Action.RequiresJustification() && strings.TrimSpace(entry.Justification) == "" {
 		return restartRequiresJustificationError()
 	}
 
-	if executor.RestartArgumentsIncomplete(entry.Binding.Action, entry.Binding.Entity, entry.Arguments) {
+	if executor.RestartArgumentsIncomplete(binding.Action, binding.Entity, entry.Arguments) {
 		return restartArgumentsIncompleteError()
 	}
 

+ 218 - 0
service/internal/api/restart_action_current_binding_test.go

@@ -0,0 +1,218 @@
+package api
+
+import (
+	"context"
+	"testing"
+
+	"connectrpc.com/connect"
+	"github.com/stretchr/testify/assert"
+	"github.com/stretchr/testify/require"
+
+	apiv1 "github.com/OliveTin/OliveTin/gen/olivetin/api/v1"
+	apiv1connect "github.com/OliveTin/OliveTin/gen/olivetin/api/v1/apiv1connect"
+	config "github.com/OliveTin/OliveTin/internal/config"
+	"github.com/OliveTin/OliveTin/internal/entities"
+	"github.com/OliveTin/OliveTin/internal/executor"
+)
+
+const restartTestActionID = "restart-test-action"
+
+func restartTestAction(command string, acls ...string) *config.Action {
+	return &config.Action{
+		ID:            restartTestActionID,
+		Title:         "Restart test action",
+		Exec:          []string{"echo", command},
+		Acls:          acls,
+		MaxConcurrent: 1,
+		Timeout:       5,
+	}
+}
+
+func startAndWaitForBinding(t *testing.T, client apiv1connect.OliveTinApiServiceClient, ex *executor.Executor, bindingID string) string {
+	t.Helper()
+
+	resp, err := client.StartAction(context.Background(), connect.NewRequest(&apiv1.StartActionRequest{BindingId: bindingID}))
+	require.NoError(t, err)
+	waitForLogFinished(t, ex, resp.Msg.ExecutionTrackingId)
+
+	return resp.Msg.ExecutionTrackingId
+}
+
+func restartAndWait(t *testing.T, client apiv1connect.OliveTinApiServiceClient, ex *executor.Executor, trackingID string) *executor.InternalLogEntry {
+	t.Helper()
+
+	resp, err := client.RestartAction(context.Background(), connect.NewRequest(&apiv1.RestartActionRequest{ExecutionTrackingId: trackingID}))
+	require.NoError(t, err)
+	waitForLogFinished(t, ex, resp.Msg.ExecutionTrackingId)
+
+	entry, ok := ex.GetLog(resp.Msg.ExecutionTrackingId)
+	require.True(t, ok)
+
+	return entry
+}
+
+func requireRestartNotFound(t *testing.T, client apiv1connect.OliveTinApiServiceClient, trackingID string) {
+	t.Helper()
+
+	_, err := client.RestartAction(context.Background(), connect.NewRequest(&apiv1.RestartActionRequest{ExecutionTrackingId: trackingID}))
+	require.Error(t, err)
+	assert.Equal(t, connect.CodeNotFound, connect.CodeOf(err))
+}
+
+func logCount(ex *executor.Executor) int {
+	logs, _ := ex.GetLogTrackingIds(0, 1000)
+
+	return len(logs)
+}
+
+func entityBindingID(ex *executor.Executor) string {
+	ex.MapActionBindingsLock.RLock()
+	defer ex.MapActionBindingsLock.RUnlock()
+
+	for id, binding := range ex.MapActionBindings {
+		if binding.Entity != nil {
+			return id
+		}
+	}
+
+	return ""
+}
+
+func newRestartTestServer(t *testing.T, cfg *config.Config) (*executor.Executor, apiv1connect.OliveTinApiServiceClient) {
+	t.Helper()
+
+	ex := executor.DefaultExecutor(cfg)
+	ex.RebuildActionMap()
+
+	ts, client := getNewTestServerAndClientWithExecutor(cfg, ex)
+	t.Cleanup(ts.Close)
+
+	return ex, client
+}
+
+func TestRestartActionRunsUnchangedActionAgain(t *testing.T) {
+	cfg := config.DefaultConfig()
+	cfg.Actions = []*config.Action{restartTestAction("first-run")}
+	ex, client := newRestartTestServer(t, cfg)
+
+	trackingID := startAndWaitForBinding(t, client, ex, restartTestActionID)
+	ex.RebuildActionMap()
+
+	entry := restartAndWait(t, client, ex, trackingID)
+	assert.False(t, entry.Blocked)
+	assert.Contains(t, entry.Output, "first-run")
+}
+
+func TestRestartActionRejectsActionRemovedFromConfig(t *testing.T) {
+	cfg := config.DefaultConfig()
+	cfg.Actions = []*config.Action{restartTestAction("removed-command")}
+	ex, client := newRestartTestServer(t, cfg)
+
+	trackingID := startAndWaitForBinding(t, client, ex, restartTestActionID)
+	logsBefore := logCount(ex)
+
+	cfg.Actions = nil
+	ex.RebuildActionMap()
+
+	requireRestartNotFound(t, client, trackingID)
+	assert.Equal(t, logsBefore, logCount(ex), "a rejected restart must not start an execution")
+}
+
+func TestRestartActionUsesCurrentAclsAfterReload(t *testing.T) {
+	cfg := config.DefaultConfig()
+	cfg.DefaultPermissions.Exec = false
+	cfg.AccessControlLists = []*config.AccessControlList{
+		{Name: "guest-exec", MatchUsernames: []string{"guest"}, Permissions: config.PermissionsList{Exec: true}},
+		{Name: "admin-exec", MatchUsernames: []string{"admin"}, Permissions: config.PermissionsList{Exec: true}},
+	}
+	cfg.Actions = []*config.Action{restartTestAction("old-guest-command", "guest-exec")}
+	ex, client := newRestartTestServer(t, cfg)
+
+	trackingID := startAndWaitForBinding(t, client, ex, restartTestActionID)
+
+	cfg.Actions = []*config.Action{restartTestAction("new-admin-command", "admin-exec")}
+	ex.RebuildActionMap()
+
+	entry := restartAndWait(t, client, ex, trackingID)
+	assert.True(t, entry.Blocked, "the guest must be blocked by the action's current ACLs")
+	assert.NotContains(t, entry.Output, "old-guest-command")
+	assert.NotContains(t, entry.Output, "new-admin-command")
+}
+
+func TestRestartActionRunsCurrentCommandAfterReload(t *testing.T) {
+	cfg := config.DefaultConfig()
+	cfg.Actions = []*config.Action{restartTestAction("old-command")}
+	ex, client := newRestartTestServer(t, cfg)
+
+	trackingID := startAndWaitForBinding(t, client, ex, restartTestActionID)
+
+	cfg.Actions = []*config.Action{restartTestAction("new-command")}
+	ex.RebuildActionMap()
+
+	entry := restartAndWait(t, client, ex, trackingID)
+	assert.False(t, entry.Blocked)
+	assert.Contains(t, entry.Output, "new-command")
+	assert.NotContains(t, entry.Output, "old-command")
+}
+
+func TestRestartActionRequiresJustificationAddedAfterReload(t *testing.T) {
+	cfg := config.DefaultConfig()
+	cfg.Actions = []*config.Action{restartTestAction("no-justification")}
+	ex, client := newRestartTestServer(t, cfg)
+
+	trackingID := startAndWaitForBinding(t, client, ex, restartTestActionID)
+
+	action := restartTestAction("no-justification")
+	action.Justification = config.JustificationRequiredNoTemplate
+	cfg.Actions = []*config.Action{action}
+	ex.RebuildActionMap()
+
+	_, err := client.RestartAction(context.Background(), connect.NewRequest(&apiv1.RestartActionRequest{ExecutionTrackingId: trackingID}))
+	require.Error(t, err)
+	assert.Contains(t, err.Error(), "justification")
+}
+
+func TestRestartActionRequiresArgumentAddedAfterReload(t *testing.T) {
+	cfg := config.DefaultConfig()
+	cfg.Actions = []*config.Action{restartTestAction("no-arguments")}
+	ex, client := newRestartTestServer(t, cfg)
+
+	trackingID := startAndWaitForBinding(t, client, ex, restartTestActionID)
+
+	action := restartTestAction("{{ host }}")
+	action.Arguments = []config.ActionArgument{{Name: "host", Type: "ascii_identifier"}}
+	cfg.Actions = []*config.Action{action}
+	ex.RebuildActionMap()
+
+	_, err := client.RestartAction(context.Background(), connect.NewRequest(&apiv1.RestartActionRequest{ExecutionTrackingId: trackingID}))
+	require.Error(t, err)
+	assert.Equal(t, connect.CodeInvalidArgument, connect.CodeOf(err))
+}
+
+func TestRestartActionRejectsEntityRemovedAfterReload(t *testing.T) {
+	const entityType = "restarttestservers"
+
+	entities.ClearEntitiesOfType(entityType)
+	t.Cleanup(func() { entities.ClearEntitiesOfType(entityType) })
+	entities.AddEntity(entityType, "web01", map[string]any{"name": "web01"})
+
+	cfg := config.DefaultConfig()
+	cfg.Actions = []*config.Action{{
+		Title:         "Restart entity test",
+		Exec:          []string{"echo", "entity-command"},
+		Entity:        entityType,
+		MaxConcurrent: 1,
+		Timeout:       5,
+	}}
+	ex, client := newRestartTestServer(t, cfg)
+
+	bindingID := entityBindingID(ex)
+	require.NotEmpty(t, bindingID)
+
+	trackingID := startAndWaitForBinding(t, client, ex, bindingID)
+
+	entities.ClearEntitiesOfType(entityType)
+	ex.RebuildActionMap()
+
+	requireRestartNotFound(t, client, trackingID)
+}