From dd443065fef2590a3484be6348d60e6db5352c0e Mon Sep 17 00:00:00 2001 From: Chris Lu Date: Wed, 25 Nov 2026 13:04:51 -0800 Subject: [PATCH] admin: keep stored plugin job data and config from read-only sessions (#12973) * admin: return compact plugin job detail to read-only sessions Read-only sessions got the stored parameters, labels, description and result output of a job, while job listings already leave them out. Co-Authored-By: Claude Opus 5.5 * admin: require admin access to read plugin job type config The stored config holds literal values such as the admin script, so a read-only session must not read it, the same as it cannot write it. Co-Authored-By: Claude Opus 5.5 * plugin worker: log only the command name in admin script activities The activity timeline is readable by read-only sessions, and command arguments can carry secrets; the full command lines stay in the output. Co-Authored-By: Claude Opus 5.5 * admin: keep only the command name in admin script running activities Activities stored before the worker change, and activities sent by workers that have not been upgraded, still carry full command lines. Reduce them when they are loaded and when they arrive. Co-Authored-By: Claude Opus 5.5 * admin: redact admin script activities whose report omits the job type A progress report for a tracked job can leave the job type out; use the tracked job's type so the command arguments are still dropped. Co-Authored-By: Claude Opus 5.5 * admin: keep a test comment on its test Co-Authored-By: Claude Opus 5.5 * admin: require the job-type-less admin script report to be recorded Co-Authored-By: Claude Opus 5.5 * admin: type untracked admin script progress from the pending execution A progress report that carries neither a job type nor a tracked job id still belongs to the execution the admin sent under its request id; use that job type so its admin script activities lose the command arguments. Co-Authored-By: Claude Opus 5.5 * admin: redact running executor activities whose job type is unknown A report that arrives after its execution timed out or was cancelled can carry only a request id. Its job type cannot be resolved any more, so treat it like an admin script report and keep only the command name. Co-Authored-By: Claude Opus 5.5 * admin: test the plugin config route on a bare handler in its own file Co-Authored-By: Claude Opus 5.5 * admin: match the unredacted admin script message exactly in the test Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- weed/admin/dash/plugin_api.go | 3 + weed/admin/dash/plugin_readonly_test.go | 80 ++++++++++ weed/admin/handlers/admin_handlers.go | 2 +- .../handlers/plugin_config_route_test.go | 35 +++++ weed/admin/plugin/plugin_monitor.go | 44 +++++- weed/admin/plugin/plugin_monitor_test.go | 141 ++++++++++++++++++ weed/plugin/worker/admin_script_handler.go | 2 +- 7 files changed, 301 insertions(+), 6 deletions(-) create mode 100644 weed/admin/dash/plugin_readonly_test.go create mode 100644 weed/admin/handlers/plugin_config_route_test.go diff --git a/weed/admin/dash/plugin_api.go b/weed/admin/dash/plugin_api.go index 790cbcda2b..fdaafe11bc 100644 --- a/weed/admin/dash/plugin_api.go +++ b/weed/admin/dash/plugin_api.go @@ -208,6 +208,9 @@ func (s *AdminServer) GetPluginJobDetailAPI(w http.ResponseWriter, r *http.Reque writeJSONError(w, http.StatusNotFound, "job detail not found") return } + if IsReadOnlyRole(RoleFromContext(r.Context())) { + plugin.StripJobDetailFields(detail) + } writeJSON(w, http.StatusOK, detail) } diff --git a/weed/admin/dash/plugin_readonly_test.go b/weed/admin/dash/plugin_readonly_test.go new file mode 100644 index 0000000000..1737efa47b --- /dev/null +++ b/weed/admin/dash/plugin_readonly_test.go @@ -0,0 +1,80 @@ +package dash + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/gorilla/mux" + "github.com/seaweedfs/seaweedfs/weed/admin/plugin" +) + +func TestGetPluginJobDetailAPIStripsRichFieldsForReadOnly(t *testing.T) { + dataDir := t.TempDir() + store, err := plugin.NewConfigStore(dataDir) + if err != nil { + t.Fatalf("NewConfigStore: %v", err) + } + const marker = "secret-marker" + if err := store.SaveJobDetail(plugin.TrackedJob{ + JobID: "job-1", + JobType: "admin_script", + State: "succeeded", + Summary: "Run admin script", + Detail: "detail " + marker, + Parameters: map[string]interface{}{"script": marker}, + Labels: map[string]string{"script_name": marker}, + ResultOutputValues: map[string]interface{}{"output": marker}, + }); err != nil { + t.Fatalf("SaveJobDetail: %v", err) + } + if err := store.SaveActivities([]plugin.JobActivity{{ + JobID: "job-1", + JobType: "admin_script", + Source: "activity_source_executor", + Stage: "running", + Message: "s3.configure -secret_key " + marker, + }}); err != nil { + t.Fatalf("SaveActivities: %v", err) + } + p, err := plugin.New(plugin.Options{DataDir: dataDir}) + if err != nil { + t.Fatalf("plugin.New: %v", err) + } + t.Cleanup(p.Shutdown) + s := &AdminServer{plugin: p} + + get := func(role string) (int, string) { + req := httptest.NewRequest(http.MethodGet, "/api/plugin/jobs/job-1/detail", nil) + req = mux.SetURLVars(req, map[string]string{"jobId": "job-1"}) + req = req.WithContext(WithAuthContext(req.Context(), "user", role, "")) + w := httptest.NewRecorder() + s.GetPluginJobDetailAPI(w, req) + return w.Code, w.Body.String() + } + + code, body := get("admin") + if code != http.StatusOK || !strings.Contains(body, marker) { + t.Fatalf("admin: code=%d body=%s", code, body) + } + + code, body = get(RoleReadOnly) + if code != http.StatusOK { + t.Fatalf("read-only: code=%d body=%s", code, body) + } + if strings.Contains(body, marker) { + t.Fatalf("read-only detail leaked rich fields: %s", body) + } + var detail plugin.JobDetail + if err := json.Unmarshal([]byte(body), &detail); err != nil { + t.Fatalf("decode: %v", err) + } + if detail.Job == nil || detail.Job.State != "succeeded" || detail.Job.Summary != "Run admin script" { + t.Fatalf("read-only detail lost compact fields: %+v", detail.Job) + } + if len(detail.Activities) != 1 || detail.Activities[0].Message != "s3.configure" { + t.Fatalf("read-only detail activities: %+v", detail.Activities) + } +} diff --git a/weed/admin/handlers/admin_handlers.go b/weed/admin/handlers/admin_handlers.go index 41d4c2bd32..fa146bc83f 100644 --- a/weed/admin/handlers/admin_handlers.go +++ b/weed/admin/handlers/admin_handlers.go @@ -302,7 +302,7 @@ func (h *AdminHandlers) registerAPIRoutes(api *mux.Router, enforceWrite bool) { pluginApi.HandleFunc("/scheduler-status", h.adminServer.GetPluginSchedulerStatusAPI).Methods(http.MethodGet) pluginApi.HandleFunc("/job-types/{jobType}/descriptor", h.adminServer.GetPluginJobTypeDescriptorAPI).Methods(http.MethodGet) pluginApi.HandleFunc("/job-types/{jobType}/schema", h.adminServer.RequestPluginJobTypeSchemaAPI).Methods(http.MethodPost) - pluginApi.HandleFunc("/job-types/{jobType}/config", h.adminServer.GetPluginJobTypeConfigAPI).Methods(http.MethodGet) + pluginApi.Handle("/job-types/{jobType}/config", wrapWrite(h.adminServer.GetPluginJobTypeConfigAPI)).Methods(http.MethodGet) pluginApi.Handle("/job-types/{jobType}/config", wrapWrite(h.adminServer.UpdatePluginJobTypeConfigAPI)).Methods(http.MethodPut) pluginApi.HandleFunc("/job-types/{jobType}/runs", h.adminServer.GetPluginRunHistoryAPI).Methods(http.MethodGet) pluginApi.Handle("/job-types/{jobType}/detect", wrapWrite(h.adminServer.TriggerPluginDetectionAPI)).Methods(http.MethodPost) diff --git a/weed/admin/handlers/plugin_config_route_test.go b/weed/admin/handlers/plugin_config_route_test.go new file mode 100644 index 0000000000..73bc84836b --- /dev/null +++ b/weed/admin/handlers/plugin_config_route_test.go @@ -0,0 +1,35 @@ +package handlers + +import ( + "net/http" + "net/http/httptest" + "testing" + + "github.com/gorilla/mux" + "github.com/seaweedfs/seaweedfs/weed/admin/dash" +) + +func TestPluginJobTypeConfigRequiresAdmin(t *testing.T) { + for _, tc := range []struct { + name, role string + enforce bool + wantDenied bool + }{ + {"read-only user", dash.RoleReadOnly, true, true}, + {"admin", "admin", true, false}, + {"no authentication", "", false, false}, + } { + t.Run(tc.name, func(t *testing.T) { + router := mux.NewRouter() + h := &AdminHandlers{adminServer: &dash.AdminServer{}} + h.registerAPIRoutes(router.PathPrefix("/api").Subrouter(), tc.enforce) + req := httptest.NewRequest(http.MethodGet, "/api/plugin/job-types/admin_script/config", nil) + req = req.WithContext(dash.WithAuthContext(req.Context(), "", tc.role, "")) + w := httptest.NewRecorder() + router.ServeHTTP(w, req) + if denied := w.Code == http.StatusForbidden; denied != tc.wantDenied { + t.Fatalf("code=%d body=%s, want denied=%v", w.Code, w.Body.String(), tc.wantDenied) + } + }) + } +} diff --git a/weed/admin/plugin/plugin_monitor.go b/weed/admin/plugin/plugin_monitor.go index a9ad1d8554..6013acf3d0 100644 --- a/weed/admin/plugin/plugin_monitor.go +++ b/weed/admin/plugin/plugin_monitor.go @@ -106,6 +106,9 @@ func (r *Plugin) loadPersistedMonitorState() error { activities = activities[len(activities)-maxActivityRecords:] } if len(activities) > 0 { + for i := range activities { + redactAdminScriptActivity(&activities[i]) + } r.activitiesMu.Lock() r.activities = append([]JobActivity(nil), activities...) r.activitiesMu.Unlock() @@ -771,6 +774,13 @@ func stripTrackedJobDetailFields(job *TrackedJob) { job.ResultOutputValues = nil } +// StripJobDetailFields reduces a built detail to what job listings return. +func StripJobDetailFields(detail *JobDetail) { + if detail != nil { + stripTrackedJobDetailFields(detail.Job) + } +} + func hasTrackedJobRichDetails(job TrackedJob) bool { return strings.TrimSpace(job.Detail) != "" || len(job.Parameters) > 0 || @@ -837,6 +847,7 @@ func (r *Plugin) handleJobProgressUpdate(workerID string, update *plugin_pb.JobP now := time.Now().UTC() resolvedWorkerID := strings.TrimSpace(workerID) + jobType := update.JobType if strings.TrimSpace(update.JobId) != "" { r.jobsMu.Lock() @@ -859,6 +870,7 @@ func (r *Plugin) handleJobProgressUpdate(workerID string, update *plugin_pb.JobP if update.JobType != "" { job.JobType = update.JobType } + jobType = job.JobType if update.RequestId != "" { job.RequestID = update.RequestId } @@ -882,8 +894,15 @@ func (r *Plugin) handleJobProgressUpdate(workerID string, update *plugin_pb.JobP r.dirtyJobs = true r.jobsMu.Unlock() } + if jobType == "" && update.RequestId != "" { + r.pendingExecutionMu.Lock() + if pending := r.pendingExecution[update.RequestId]; pending != nil { + jobType = pending.jobType + } + r.pendingExecutionMu.Unlock() + } - r.trackWorkerActivities(update.JobType, update.JobId, update.RequestId, resolvedWorkerID, update.Activities) + r.trackWorkerActivities(jobType, update.JobId, update.RequestId, resolvedWorkerID, update.Activities) if update.Message != "" || update.Stage != "" { source := "worker_progress" if strings.TrimSpace(update.JobId) == "" { @@ -891,7 +910,7 @@ func (r *Plugin) handleJobProgressUpdate(workerID string, update *plugin_pb.JobP } r.appendActivity(JobActivity{ JobID: update.JobId, - JobType: update.JobType, + JobType: jobType, RequestID: update.RequestId, WorkerID: resolvedWorkerID, Source: source, @@ -1290,7 +1309,7 @@ func (r *Plugin) trackWorkerActivities(jobType, jobID, requestID, workerID strin if event.CreatedAt != nil { timestamp = event.CreatedAt.AsTime().UTC() } - r.appendActivity(JobActivity{ + activity := JobActivity{ JobID: jobID, JobType: jobType, RequestID: requestID, @@ -1300,7 +1319,24 @@ func (r *Plugin) trackWorkerActivities(jobType, jobID, requestID, workerID strin Stage: event.Stage, Details: configValueMapToPlain(event.Details), OccurredAt: timeToPtr(timestamp), - }) + } + redactAdminScriptActivity(&activity) + r.appendActivity(activity) + } +} + +// Older admin script workers logged each command with its arguments, which +// can carry secrets; keep only the command name. A report whose job type is +// unknown may come from one of them. +func redactAdminScriptActivity(activity *JobActivity) { + jobType := strings.TrimSpace(activity.JobType) + if activity.Stage != "running" || + activity.Source != strings.ToLower(plugin_pb.ActivitySource_ACTIVITY_SOURCE_EXECUTOR.String()) || + (jobType != "" && !strings.EqualFold(jobType, adminScriptJobType)) { + return + } + if fields := strings.Fields(activity.Message); len(fields) > 1 { + activity.Message = fields[0] } } diff --git a/weed/admin/plugin/plugin_monitor_test.go b/weed/admin/plugin/plugin_monitor_test.go index 0311df3b49..fd564edb39 100644 --- a/weed/admin/plugin/plugin_monitor_test.go +++ b/weed/admin/plugin/plugin_monitor_test.go @@ -232,6 +232,147 @@ func TestHandleJobProgressUpdateCarriesWorkerIDInActivities(t *testing.T) { } } +func TestAdminScriptRunningActivityKeepsOnlyCommandName(t *testing.T) { + t.Parallel() + + pluginSvc, err := New(Options{}) + if err != nil { + t.Fatalf("New: %v", err) + } + defer pluginSvc.Shutdown() + + pluginSvc.handleJobProgressUpdate("worker-a", &plugin_pb.JobProgressUpdate{ + JobId: "job-admin-script", + JobType: "admin_script", + State: plugin_pb.JobState_JOB_STATE_RUNNING, + Stage: "running", + Message: "executed 1/1 command(s)", + Activities: []*plugin_pb.ActivityEvent{ + { + Source: plugin_pb.ActivitySource_ACTIVITY_SOURCE_EXECUTOR, + Stage: "running", + Message: "s3.configure -secret_key hidden", + }, + }, + }) + + messages := map[string]string{} + for _, activity := range pluginSvc.ListJobActivities("job-admin-script", 0) { + messages[activity.Source] = activity.Message + } + if got := messages["activity_source_executor"]; got != "s3.configure" { + t.Fatalf("executor activity message = %q, want %q", got, "s3.configure") + } + if got := messages["worker_progress"]; got != "executed 1/1 command(s)" { + t.Fatalf("progress activity message = %q", got) + } + + pluginSvc.handleJobProgressUpdate("worker-a", &plugin_pb.JobProgressUpdate{ + JobId: "job-admin-script", + State: plugin_pb.JobState_JOB_STATE_RUNNING, + Stage: "running", + Activities: []*plugin_pb.ActivityEvent{ + { + Source: plugin_pb.ActivitySource_ACTIVITY_SOURCE_EXECUTOR, + Stage: "running", + Message: "s3.bucket.create -access_key other", + }, + }, + }) + found := false + for _, activity := range pluginSvc.ListJobActivities("job-admin-script", 0) { + if activity.Message == "s3.bucket.create -access_key other" { + t.Fatalf("report without a job type kept the command arguments: %q", activity.Message) + } + found = found || activity.Message == "s3.bucket.create" + } + if !found { + t.Fatalf("report without a job type was not recorded") + } +} + +func TestAdminScriptRunningActivityTypedByPendingExecution(t *testing.T) { + t.Parallel() + + pluginSvc, err := New(Options{}) + if err != nil { + t.Fatalf("New: %v", err) + } + defer pluginSvc.Shutdown() + + pluginSvc.pendingExecutionMu.Lock() + pluginSvc.pendingExecution["req-admin-script"] = &pendingExecutionState{ + completed: make(chan *plugin_pb.JobCompleted, 1), + jobID: "job-untracked", + jobType: "admin_script", + } + pluginSvc.pendingExecutionMu.Unlock() + + pluginSvc.handleJobProgressUpdate("worker-a", &plugin_pb.JobProgressUpdate{ + RequestId: "req-admin-script", + State: plugin_pb.JobState_JOB_STATE_RUNNING, + Stage: "running", + Activities: []*plugin_pb.ActivityEvent{ + { + Source: plugin_pb.ActivitySource_ACTIVITY_SOURCE_EXECUTOR, + Stage: "running", + Message: "s3.configure -secret_key hidden", + }, + }, + }) + + executorActivities := 0 + for _, activity := range pluginSvc.ListActivities("", 0) { + if activity.Source != "activity_source_executor" { + continue + } + executorActivities++ + if activity.JobType != "admin_script" || activity.Message != "s3.configure" { + t.Fatalf("activity = %+v, want an admin_script activity with message %q", activity, "s3.configure") + } + } + if executorActivities != 1 { + t.Fatalf("executor activities = %d, want 1", executorActivities) + } +} + +func TestUntypedRunningActivityAfterCancellationKeepsOnlyCommandName(t *testing.T) { + t.Parallel() + + pluginSvc, err := New(Options{}) + if err != nil { + t.Fatalf("New: %v", err) + } + defer pluginSvc.Shutdown() + + pluginSvc.handleJobProgressUpdate("worker-a", &plugin_pb.JobProgressUpdate{ + RequestId: "req-cancelled", + State: plugin_pb.JobState_JOB_STATE_RUNNING, + Stage: "running", + Activities: []*plugin_pb.ActivityEvent{ + { + Source: plugin_pb.ActivitySource_ACTIVITY_SOURCE_EXECUTOR, + Stage: "running", + Message: "s3.configure -secret_key hidden", + }, + }, + }) + + executorActivities := 0 + for _, activity := range pluginSvc.ListActivities("", 0) { + if activity.Source != "activity_source_executor" { + continue + } + executorActivities++ + if activity.Message != "s3.configure" { + t.Fatalf("activity message = %q, want %q", activity.Message, "s3.configure") + } + } + if executorActivities != 1 { + t.Fatalf("executor activities = %d, want 1", executorActivities) + } +} + // A worker that leaves the state out of its progress (as seaweed-worker did) // must still have its completion applied. func TestProgressWithoutStateKeepsJobRunningUntilCompleted(t *testing.T) { diff --git a/weed/plugin/worker/admin_script_handler.go b/weed/plugin/worker/admin_script_handler.go index 5df6fbe3f6..256c46b4b1 100644 --- a/weed/plugin/worker/admin_script_handler.go +++ b/weed/plugin/worker/admin_script_handler.go @@ -320,7 +320,7 @@ func (h *AdminScriptHandler) Execute(ctx context.Context, request *plugin_pb.Exe Stage: "running", Message: fmt.Sprintf("executed %d/%d command(s)", executed, len(execCommands)), Activities: []*plugin_pb.ActivityEvent{ - BuildExecutorActivity("running", commandLine), + BuildExecutorActivity("running", cmd.Name), }, }); sendErr != nil { break