diff --git a/api/openapi-v2.json b/api/openapi-v2.json index 0a505beb4..dd98963ea 100644 --- a/api/openapi-v2.json +++ b/api/openapi-v2.json @@ -29253,6 +29253,10 @@ "description": "The requests per minute value.", "type": "integer" }, + "script_memory_mb": { + "description": "The script memory mb value.", + "type": "integer" + }, "script_timeout_ms": { "description": "The script timeout ms value.", "type": "integer" diff --git a/internal/operatorcontrols/README.md b/internal/operatorcontrols/README.md index 04c22a202..59cab8056 100644 --- a/internal/operatorcontrols/README.md +++ b/internal/operatorcontrols/README.md @@ -146,5 +146,19 @@ Per-run broker quotas and conversation admission remain separate controls. Enabled condition and action scripts share the instance-wide `concurrent_scripts` admission pool. `script_timeout_ms` caps both runtimes and action-script REST deadlines; node settings can only narrow the ceiling. Permits are released on -success, error and cancellation. These ceilings are not heap/process isolation. -Keep untrusted scripts disabled until a separately bounded worker design is available. +success, error and cancellation. When `concurrent_scripts` is unset, action +workers fall back to a finite default of 4: each execution is a process, so an +unset limit must not mean unbounded spawning. + +`execute_script` action nodes run in a separate worker process per execution +(selected by `WINDSHIFT_SCRIPT_WORKER=1` on the server binary). The worker gets +`script_memory_mb` (default 128) as a hard per-script heap budget: the worker +sets its own Go memory limit, an in-worker monitor interrupts a runaway +allocation, and on Linux the parent additionally kills the worker when its +resident set passes its baseline plus the budget and a small runtime allowance. +A killed or over-budget worker fails the node with a bounded error, and the API +process is unaffected. The timeout is one absolute instant shared by the parent +and the worker, so startup time counts against the budget, and the parent +refuses a worker frame larger than 1 MiB before decoding it. +Condition scripts still evaluate in-process; they are admin-gated and capped by +`script_timeout_ms` and the 10 KiB source limit. diff --git a/internal/operatorcontrols/policy.go b/internal/operatorcontrols/policy.go index 2a783de5b..7931ecad4 100644 --- a/internal/operatorcontrols/policy.go +++ b/internal/operatorcontrols/policy.go @@ -80,6 +80,7 @@ type Limits struct { RequestsPerMinute int64 `json:"requests_per_minute,omitempty"` ScriptTimeoutMS int `json:"script_timeout_ms,omitempty"` ConcurrentScripts int `json:"concurrent_scripts,omitempty"` + ScriptMemoryMB int `json:"script_memory_mb,omitempty"` AutomationStepsPerDay int64 `json:"automation_steps_per_day,omitempty"` MailRecipientsPerDay int64 `json:"mail_recipients_per_day,omitempty"` AITokensPerDay int64 `json:"ai_tokens_per_day,omitempty"` @@ -133,6 +134,7 @@ func (p Policy) Validate() error { "concurrent_requests": int64(limits.ConcurrentRequests), "concurrent_streams": int64(limits.ConcurrentStreams), "requests_per_minute": limits.RequestsPerMinute, "script_timeout_ms": int64(limits.ScriptTimeoutMS), "concurrent_scripts": int64(limits.ConcurrentScripts), "automation_steps_per_day": limits.AutomationStepsPerDay, + "script_memory_mb": int64(limits.ScriptMemoryMB), "mail_recipients_per_day": limits.MailRecipientsPerDay, "ai_tokens_per_day": limits.AITokensPerDay, "concurrent_ai": int64(limits.ConcurrentAI), } { diff --git a/internal/services/action_script_executor.go b/internal/services/action_script_executor.go index ebb948cd9..a6e529270 100644 --- a/internal/services/action_script_executor.go +++ b/internal/services/action_script_executor.go @@ -1,6 +1,7 @@ package services import ( + "bufio" "context" "encoding/json" "errors" @@ -9,6 +10,7 @@ import ( "net/http" "strings" "sync" + "sync/atomic" "time" "github.com/grafana/sobek" @@ -45,15 +47,15 @@ type ActionScriptWriteMarker interface { } // ExecuteScriptExecutor implements the execute_script node type. Each run gets -// a fresh Sobek runtime bound to the effective action executor; REST calls go -// through a short-lived bearer token minted for that executor and revoked in -// cleanup. +// a fresh Sobek runtime in a dedicated worker process, so a hostile allocation +// is bounded by the worker's heap budget instead of the API server's. REST calls +// go through a short-lived bearer token minted for the effective executor in the +// parent and revoked in cleanup; the worker never sees the token or the +// database. // -// Trusted authors only: Sobek runs in-process and has no hard per-script heap -// limit, so time and output budgets do not make a hostile allocation safe. -// Restricting authorship to action managers and requiring action.set_actor for -// executable edits of privileged actions is the current mitigation; process -// isolation would be a prerequisite before accepting untrusted authors. +// The worker enforces a wall-clock limit and a heap budget, and on Linux the +// parent kills it if its resident set passes the budget. A script that exceeds +// either budget fails the node with a bounded error. // // Side effects are not transactional. A script that mutates state and then // fails has already committed those writes, matching every other action node. @@ -67,6 +69,7 @@ type ExecuteScriptExecutor struct { dispatcher ScriptAPIDispatcher marker ActionScriptWriteMarker logger *slog.Logger + launcher ScriptWorkerLauncher } // NewExecuteScriptExecutor wires the executor with the shared token manager @@ -77,6 +80,7 @@ func NewExecuteScriptExecutor(tokens ActionScriptTokenManager, dispatcher Script tokens: tokens, dispatcher: dispatcher, logger: slog.Default(), + launcher: defaultScriptWorkerLauncher, } } @@ -88,16 +92,23 @@ func (e *ExecuteScriptExecutor) WithWriteMarker(marker ActionScriptWriteMarker) return e } +// WithLauncher overrides the isolated worker launcher. Tests use it to run the +// worker in-process; production uses the subprocess launcher. +func (e *ExecuteScriptExecutor) WithLauncher(launcher ScriptWorkerLauncher) *ExecuteScriptExecutor { + e.launcher = launcher + return e +} + // NodeType pins the dispatch key. func (e *ExecuteScriptExecutor) NodeType() models.ActionNodeType { return models.ActionNodeExecuteScript } -// scriptRun holds the mutable state of one node execution. It is created per -// Execute call and never shared across executions, so scripts cannot observe -// each other's state. -type scriptRun struct { - vm *sobek.Runtime +// scriptHost holds the parent-side mutable state of one node execution. It is +// created per Execute call and never shared across executions. The Sobek realm +// lives in the isolated worker; this struct owns the credentials, budgets, +// console buffer, and reconciliation flags the worker reports against. +type scriptHost struct { runCtx context.Context tokens ActionScriptTokenManager dispatcher ScriptAPIDispatcher @@ -135,7 +146,7 @@ func (e *ExecuteScriptExecutor) Execute(node *models.ActionNode, ctx *models.Exe if ctx == nil { return errors.New("execute_script: execution context is required") } - release, err := e.controls.Acquire(actionRequestContext(ctx), "scripts", e.controls.Limits().ConcurrentScripts) + release, err := e.controls.Acquire(actionRequestContext(ctx), "scripts", e.scriptConcurrencyLimit()) if err != nil { return err } @@ -179,41 +190,42 @@ func (e *ExecuteScriptExecutor) Execute(node *models.ActionNode, ctx *models.Exe maxCalls = maxScriptAPICalls } + // Compile in the parent so a syntax error fails fast without spawning a + // worker. The worker compiles the same wrapper again before running it. wrapped := "(function() {\n" + source + "\n})()" - program, err := sobek.Compile("action_script", wrapped, false) - if err != nil { + if _, err := sobek.Compile("action_script", wrapped, false); err != nil { return fmt.Errorf("execute_script: syntax error: %w", err) } - timeoutCtx, cancel := context.WithTimeout(actionRequestContext(ctx), time.Duration(timeoutMs)*time.Millisecond) - defer cancel() + // One absolute deadline covers worker startup, JS, and REST calls. The same + // instant reaches the worker, so a slow start cannot hand a script a second + // full timeout, and the worker is force-killed a short grace later so it can + // still report its own failure. + deadline := time.Now().Add(time.Duration(timeoutMs) * time.Millisecond) + runCtx, cancelRun := context.WithDeadline(actionRequestContext(ctx), deadline) + defer cancelRun() + killCtx, cancelKill := context.WithDeadline(actionRequestContext(ctx), deadline.Add(scriptWorkerKillGrace)) + defer cancelKill() - run := &scriptRun{ + host := &scriptHost{ tokens: e.tokens, dispatcher: e.dispatcher, marker: e.marker, executionLogID: ctx.ExecutionLogID, actorUserID: ctx.EffectiveActorID, maxAPICalls: maxCalls, - runCtx: WithActionScriptProvenance(timeoutCtx, provenanceFromExecution(ctx, node.ID)), + runCtx: WithActionScriptProvenance(runCtx, provenanceFromExecution(ctx, node.ID)), reconciliation: &ctx.ReconciliationRequired, writeMarked: &ctx.ScriptWriteMarked, } - vm := sobek.New() - run.vm = vm - if err := bindScriptGlobals(vm, run, ctx); err != nil { - return fmt.Errorf("execute_script: bind runtime: %w", err) - } - - // Revocation is deferred so it runs even if result conversion panics. A - // getter evaluated while converting the return value is still script code - // and must not outlive the credential. + // Revocation is deferred so it runs even if the worker fails. The credential + // is minted lazily on the first bridge call and must not outlive the node. defer func() { - if run.cred == nil { + if host.cred == nil { return } - if revokeErr := RevokeActionScriptCredential(e.tokens, run.cred, ctx.EffectiveActorID); revokeErr != nil { + if revokeErr := RevokeActionScriptCredential(e.tokens, host.cred, ctx.EffectiveActorID); revokeErr != nil { actionID := 0 if ctx.Action != nil { actionID = ctx.Action.ID @@ -226,25 +238,27 @@ func (e *ExecuteScriptExecutor) Execute(node *models.ActionNode, ctx *models.Exe } }() - output, runErr := runScriptProgram(vm, program, timeoutCtx) + request := scriptWorkerMessage{ + Type: scriptMessageRun, + Source: source, + TimeoutMS: timeoutMs, + DeadlineUnixNano: deadline.UnixNano(), + MemoryBytes: e.scriptMemoryBytes(), + Globals: scriptGlobals(ctx), + } + output, runErr := e.runWorker(killCtx, request, host) + if stepResult.Output == nil { stepResult.Output = make(map[string]any) } - stepResult.Output["api_calls"] = run.apiCalls - stepResult.Output["console"] = run.console - if run.consoleCut { + stepResult.Output["api_calls"] = host.apiCalls + stepResult.Output["console"] = host.console + if host.consoleCut { stepResult.Output["console_truncated"] = true } - if run.fatal != nil { - return run.fatal - } if runErr != nil { - var interrupted *sobek.InterruptedError - if errors.As(runErr, &interrupted) && interrupted.Value() == errScriptTimeout { - return fmt.Errorf("execute_script: timed out after %dms", timeoutMs) - } - return fmt.Errorf("execute_script: %w", runErr) + return runErr } ctx.Variables[outputVar] = output @@ -253,41 +267,146 @@ func (e *ExecuteScriptExecutor) Execute(node *models.ActionNode, ctx *models.Exe return nil } -// bindScriptGlobals installs the explicit, closed set of bindings a script can -// reach. No Go service, pointer, or shared execution map is exposed. -func bindScriptGlobals(vm *sobek.Runtime, run *scriptRun, ctx *models.ExecutionContext) error { - bindings := map[string]any{ - "windshift": map[string]any{ - "api": map[string]any{ - "request": run.apiRequest, - }, - }, - "console": map[string]any{ - "log": run.consoleFn("log"), - "info": run.consoleFn("info"), - "warn": run.consoleFn("warn"), - "error": run.consoleFn("error"), - "debug": run.consoleFn("debug"), - }, - "context": scriptContextView(ctx), - } - for name, value := range bindings { - if err := vm.Set(name, value); err != nil { - return fmt.Errorf("set %s: %w", name, err) - } +// runWorker starts one isolated worker, sends the run request, and serves the +// bridge until the worker reports a result or failure. The worker owns the +// Sobek realm; this function owns credentials, budgets, and policy. +func (e *ExecuteScriptExecutor) runWorker(ctx context.Context, request scriptWorkerMessage, host *scriptHost) (any, error) { + launcher := e.launcher + if launcher == nil { + launcher = defaultScriptWorkerLauncher } - if ctx.Event != nil { - if err := vm.Set("item_id", ctx.Event.ItemID); err != nil { - return err + proc, err := launcher.Launch(ctx) + if err != nil { + return nil, fmt.Errorf("execute_script: %w", err) + } + defer func() { + _ = proc.Kill() + _ = proc.Wait() + }() + + encoder := json.NewEncoder(proc.Stdin()) + reader := bufio.NewReader(proc.Stdout()) + if err := encoder.Encode(request); err != nil { + return nil, fmt.Errorf("execute_script: send script to worker: %w", err) + } + + var memoryExceeded atomic.Bool + watchdogStop := make(chan struct{}) + defer close(watchdogStop) + var watchdogOnce sync.Once + + for { + frame, err := readScriptWorkerFrame(reader, scriptWorkerMaxFrameBytes) + if err != nil { + if errors.Is(err, errScriptWorkerFrameTooLarge) { + return nil, errors.New("execute_script: script worker frame exceeds wire budget") + } + if memoryExceeded.Load() { + return nil, memoryLimitError(request.MemoryBytes) + } + if host.fatal != nil { + return nil, host.fatal + } + if ctx.Err() != nil { + if errors.Is(ctx.Err(), context.DeadlineExceeded) { + return nil, fmt.Errorf("execute_script: timed out after %dms", request.TimeoutMS) + } + return nil, ctx.Err() + } + return nil, errors.New("execute_script: script worker exited without a result") } - if err := vm.Set("workspace_id", ctx.Event.WorkspaceID); err != nil { - return err + var msg scriptWorkerMessage + if err := json.Unmarshal(frame, &msg); err != nil { + return nil, errors.New("execute_script: script worker sent an invalid frame") } - if err := vm.Set("trigger_user_id", ctx.Event.ActorUserID); err != nil { - return err + switch msg.Type { + case scriptMessageReady: + if request.MemoryBytes > 0 { + if rss, rssErr := proc.RSSBytes(); rssErr == nil && rss > 0 { + watchdogOnce.Do(func() { + go watchWorkerMemory(proc, rss+request.MemoryBytes+scriptWorkerRSSOverhead, watchdogStop, &memoryExceeded) + }) + } + } + case scriptMessageConsole: + host.appendConsole(msg.Level + ": " + msg.Message) + case scriptMessageAPIRequest: + if err := encoder.Encode(host.handleAPIRequest(msg)); err != nil { + return nil, fmt.Errorf("execute_script: reply to worker: %w", err) + } + case scriptMessageResult: + var output any + if len(msg.Output) > 0 { + if err := json.Unmarshal(msg.Output, &output); err != nil { + return nil, fmt.Errorf("execute_script: decode worker result: %w", err) + } + } + return output, nil + case scriptMessageError: + return nil, host.workerError(msg, request.TimeoutMS, request.MemoryBytes) + } + } +} + +// workerError maps a worker-reported failure to the node's terminal error. A +// policy failure returns the parent's stored fatal error so callers still see +// the concrete *ErrScriptAPIPolicy; anything else is bounded worker text. +func (h *scriptHost) workerError(msg scriptWorkerMessage, timeoutMS int, memoryBytes int64) error { + switch msg.ErrorKind { + case scriptErrorTimeout: + return fmt.Errorf("execute_script: timed out after %dms", timeoutMS) + case scriptErrorMemory: + return memoryLimitError(memoryBytes) + case scriptErrorPolicy: + if h.fatal != nil { + return h.fatal } + return scriptAPIPolicyErrorf("%s", msg.Message) + default: + return fmt.Errorf("execute_script: %s", msg.Message) + } +} + +// scriptConcurrencyLimit resolves the instance's script admission ceiling. An +// unset operator limit falls back to a finite default: the per-worker heap +// budget does not bound aggregate CPU or memory, so an unset limit must not +// mean unbounded process spawning. +func (e *ExecuteScriptExecutor) scriptConcurrencyLimit() int { + if limit := e.controls.Limits().ConcurrentScripts; limit > 0 { + return limit + } + return defaultScriptConcurrency +} + +// scriptMemoryBytes resolves the per-script heap budget. Zero means the +// operator left the limit unset, so the default applies. +func (e *ExecuteScriptExecutor) scriptMemoryBytes() int64 { + memoryMB := defaultScriptMemoryMB + if limit := e.controls.Limits().ScriptMemoryMB; limit > 0 { + memoryMB = limit + } + return int64(memoryMB) * 1024 * 1024 +} + +// memoryLimitError is the bounded, explainable failure recorded when a script +// exceeds its heap budget. +func memoryLimitError(memoryBytes int64) error { + return fmt.Errorf("execute_script: script worker memory limit of %d MiB exceeded", memoryBytes/(1024*1024)) +} + +// scriptGlobals is the explicit, closed set of values the worker exposes to +// the script. No Go service, pointer, or shared execution map is serialized. +func scriptGlobals(ctx *models.ExecutionContext) map[string]any { + globals := map[string]any{ + "context": scriptContextView(ctx), + "actor_user_id": ctx.EffectiveActorID, } - return vm.Set("actor_user_id", ctx.EffectiveActorID) + if ctx.Event != nil { + globals["item_id"] = ctx.Event.ItemID + globals["workspace_id"] = ctx.Event.WorkspaceID + globals["trigger_user_id"] = ctx.Event.ActorUserID + } + return globals } // scriptContextView is the read-only, detached JSON view of the execution. It @@ -316,60 +435,42 @@ func scriptContextView(ctx *models.ExecutionContext) map[string]any { return view } -// apiRequest is the single host call exposed to scripts. It validates the -// method and path, enforces the call budget, lazily mints the executor -// credential, and dispatches through the canonical v2 handler. Policy -// violations are fatal: they interrupt the VM so a try/catch cannot swallow -// them. -func (r *scriptRun) apiRequest(call sobek.FunctionCall) sobek.Value { - if r.fatal != nil { - return sobek.Undefined() - } - if err := r.runCtx.Err(); err != nil { - r.fail(err) - return sobek.Undefined() +// handleAPIRequest is the parent half of the bridge. It validates the method +// and path, enforces the call budget, lazily mints the executor credential, and +// dispatches through the canonical v2 handler. Policy violations are returned +// as fatal responses, so the worker interrupts the VM and a try/catch cannot +// swallow them. +func (h *scriptHost) handleAPIRequest(req scriptWorkerMessage) scriptWorkerMessage { + fatal := func(err error) scriptWorkerMessage { + if h.fatal == nil { + h.fatal = err + } + return scriptWorkerMessage{Type: scriptMessageAPIFatal, ID: req.ID, Message: err.Error()} } - options := call.Argument(0) - if scriptValueMissing(options) { - panic(r.vm.NewTypeError("windshift.api.request(options) requires an options object")) + if h.fatal != nil { + return scriptWorkerMessage{Type: scriptMessageAPIFatal, ID: req.ID, Message: h.fatal.Error()} } - obj := options.ToObject(r.vm) - methodVal := scriptObjectGet(obj, "method") - pathVal := scriptObjectGet(obj, "path") - if scriptValueMissing(methodVal) || scriptValueMissing(pathVal) { - panic(r.vm.NewTypeError("windshift.api.request requires method and path")) + if err := h.runCtx.Err(); err != nil { + return fatal(err) } - method := strings.TrimSpace(methodVal.String()) - path := pathVal.String() - - var body []byte - if bodyVal := scriptObjectGet(obj, "body"); !scriptValueMissing(bodyVal) { - encoded, err := json.Marshal(bodyVal.Export()) - if err != nil { - panic(r.vm.NewTypeError("body must be JSON-serializable: " + err.Error())) - } - if len(encoded) > maxScriptRequestBodyBytes { - r.fail(scriptAPIPolicyErrorf("request body exceeds %d bytes", maxScriptRequestBodyBytes)) - return sobek.Undefined() - } - body = encoded + method := strings.TrimSpace(req.Method) + path := req.Path + if len(req.Body) > maxScriptRequestBodyBytes { + return fatal(scriptAPIPolicyErrorf("request body exceeds %d bytes", maxScriptRequestBodyBytes)) } - r.apiCalls++ - if r.apiCalls > r.maxAPICalls { - r.fail(scriptAPIPolicyErrorf("api call budget of %d exceeded", r.maxAPICalls)) - return sobek.Undefined() + h.apiCalls++ + if h.apiCalls > h.maxAPICalls { + return fatal(scriptAPIPolicyErrorf("api call budget of %d exceeded", h.maxAPICalls)) } // Validate before minting or dispatching so a disallowed route fails closed // without spending a credential or a network round trip. if _, err := ValidateScriptAPIRequest(method, path); err != nil { - r.fail(err) - return sobek.Undefined() + return fatal(err) } - if err := r.runCtx.Err(); err != nil { - r.fail(err) - return sobek.Undefined() + if err := h.runCtx.Err(); err != nil { + return fatal(err) } // Persist the write-ahead marker and mark the execution non-replayable @@ -377,35 +478,51 @@ func (r *scriptRun) apiRequest(call sobek.FunctionCall) sobek.Value { // when it returns an error or the worker dies mid-call, so replay must be // blocked from this point unless the flow later completes successfully. if isMutatingScriptMethod(method) { - if err := r.markWritePending(); err != nil { - r.fail(fmt.Errorf("execute_script: persist write marker: %w", err)) - return sobek.Undefined() + if err := h.markWritePending(); err != nil { + return fatal(fmt.Errorf("execute_script: persist write marker: %w", err)) } - if r.reconciliation != nil { - *r.reconciliation = true + if h.reconciliation != nil { + *h.reconciliation = true } } - cred, err := r.ensureCredential() + cred, err := h.ensureCredential() if err != nil { - r.fail(err) - return sobek.Undefined() + return fatal(err) } - if err := r.runCtx.Err(); err != nil { - r.fail(err) - return sobek.Undefined() + if err := h.runCtx.Err(); err != nil { + return fatal(err) } - response, err := r.dispatcher.Dispatch(r.runCtx, cred.Token, ScriptAPIRequest{Method: method, Path: path, Body: body}) + response, err := h.dispatcher.Dispatch(h.runCtx, cred.Token, ScriptAPIRequest{Method: method, Path: path, Body: req.Body}) if err != nil { var policy *ErrScriptAPIPolicy if errors.As(err, &policy) { - r.fail(err) - return sobek.Undefined() + return fatal(err) } - panic(r.vm.NewGoError(fmt.Errorf("windshift.api.request failed: %w", err))) + return scriptWorkerMessage{Type: scriptMessageAPIRecover, ID: req.ID, Message: err.Error()} + } + return scriptWorkerMessage{ + Type: scriptMessageAPIResponse, + ID: req.ID, + Status: response.Status, + Truncated: response.Truncated, + Response: scriptResponseBody(response.Body), + } +} + +// scriptResponseBody keeps a valid JSON body verbatim and otherwise encodes it +// as a JSON string, so the worker can rebuild the same JS shape the in-process +// bridge produced. +func scriptResponseBody(body []byte) json.RawMessage { + if len(body) > 0 && json.Valid(body) { + return json.RawMessage(body) } - return r.responseValue(response) + encoded, err := json.Marshal(string(body)) + if err != nil { + return nil + } + return encoded } // isMutatingScriptMethod reports whether a permitted bridge method changes @@ -421,11 +538,11 @@ func isMutatingScriptMethod(method string) bool { // ensureCredential mints at most one credential per node execution, lazily so a // script that makes no API calls pays no token cost. -func (r *scriptRun) ensureCredential() (*ActionScriptCredential, error) { - r.credOnce.Do(func() { - r.cred, r.credErr = MintActionScriptCredential(r.runCtx, r.tokens, r.actorUserID) +func (h *scriptHost) ensureCredential() (*ActionScriptCredential, error) { + h.credOnce.Do(func() { + h.cred, h.credErr = MintActionScriptCredential(h.runCtx, h.tokens, h.actorUserID) }) - return r.cred, r.credErr + return h.cred, h.credErr } // markWritePending persists the reconciliation marker once per execution. The @@ -433,70 +550,32 @@ func (r *scriptRun) ensureCredential() (*ActionScriptCredential, error) { // mutating node in a flow reuses the first node's persisted marker instead of // re-updating a log that is already reconciliation_required. It is a no-op when // there is no durable execution log to recover. -func (r *scriptRun) markWritePending() error { - if r.marker == nil || r.executionLogID <= 0 { +func (h *scriptHost) markWritePending() error { + if h.marker == nil || h.executionLogID <= 0 { return nil } - if r.writeMarked != nil && *r.writeMarked { + if h.writeMarked != nil && *h.writeMarked { return nil } - if err := r.marker.MarkScriptWritePending(r.executionLogID); err != nil { + if err := h.marker.MarkScriptWritePending(h.executionLogID); err != nil { return err } - if r.writeMarked != nil { - *r.writeMarked = true + if h.writeMarked != nil { + *h.writeMarked = true } return nil } -// fail records the first fatal policy error and interrupts the VM. Interrupts -// are uncatchable, so an authorization or budget violation cannot be turned -// into a successful step. -func (r *scriptRun) fail(err error) { - if r.fatal == nil { - r.fatal = err - } - r.vm.Interrupt(err) -} - -// responseValue converts a bounded API response into a detached JS object. -func (r *scriptRun) responseValue(response ScriptAPIResponse) sobek.Value { - result := r.vm.NewObject() - _ = result.Set("status", response.Status) - _ = result.Set("ok", response.Status >= 200 && response.Status < 300) - _ = result.Set("truncated", response.Truncated) - var decoded any - if len(response.Body) > 0 && json.Unmarshal(response.Body, &decoded) == nil { - _ = result.Set("body", decoded) - } else { - _ = result.Set("body", string(response.Body)) - } - return result -} - -// consoleFn returns a bounded console sink. Output is truncated rather than -// dropped silently once the byte budget is exhausted. -func (r *scriptRun) consoleFn(level string) func(sobek.FunctionCall) sobek.Value { - return func(call sobek.FunctionCall) sobek.Value { - parts := make([]string, 0, len(call.Arguments)) - for _, arg := range call.Arguments { - parts = append(parts, scriptValueString(arg)) - } - r.appendConsole(level + ": " + strings.Join(parts, " ")) - return sobek.Undefined() - } -} - -func (r *scriptRun) appendConsole(line string) { +func (h *scriptHost) appendConsole(line string) { if len(line) > maxScriptConsoleEntryBytes { line = line[:maxScriptConsoleEntryBytes] + "…[truncated]" } - if len(r.console) >= maxScriptConsoleEntries || r.consoleBytes+len(line) > maxScriptConsoleBytes { - r.consoleCut = true + if len(h.console) >= maxScriptConsoleEntries || h.consoleBytes+len(line) > maxScriptConsoleBytes { + h.consoleCut = true return } - r.console = append(r.console, line) - r.consoleBytes += len(line) + h.console = append(h.console, line) + h.consoleBytes += len(line) } // scriptValueString renders a console argument as bounded text. Objects are diff --git a/internal/services/actioncatalog/catalog.go b/internal/services/actioncatalog/catalog.go index 06e289886..b5fef0791 100644 --- a/internal/services/actioncatalog/catalog.go +++ b/internal/services/actioncatalog/catalog.go @@ -357,7 +357,7 @@ func Build() (*Catalog, error) { if err := registerNode[models.ExecuteScriptNodeConfig](c, nodeSpec{ Type: models.ActionNodeExecuteScript, Label: "Run script", - Description: "Run a JavaScript function body with the effective executor's identity. The script can call the v2 REST API through a server-minted, short-lived token; the return value is stored in the configured output variable.", + Description: "Run a JavaScript function body with the effective executor's identity. The script can call the v2 REST API through a server-minted, short-lived token; the return value is stored in the configured output variable. Runs in an isolated worker process with a per-script memory and time budget, so a runaway script cannot exhaust the server.", Category: CategoryIntegration, }); err != nil { return nil, err diff --git a/internal/services/script_worker.go b/internal/services/script_worker.go new file mode 100644 index 000000000..5ff74c815 --- /dev/null +++ b/internal/services/script_worker.go @@ -0,0 +1,514 @@ +package services + +import ( + "bufio" + "context" + "encoding/json" + "errors" + "fmt" + "io" + "os" + "os/exec" + "runtime" + "runtime/debug" + "strings" + "sync" + "sync/atomic" + "time" + + "github.com/grafana/sobek" +) + +// EnvScriptWorker selects the isolated script-worker mode. The server binary +// and test binaries check it before any other initialization and then run +// RunScriptWorker instead of the normal entry point. +const EnvScriptWorker = "WINDSHIFT_SCRIPT_WORKER" + +// Budgets for the worker process. The heap budget is the operator-controlled +// per-script ceiling; the kill grace lets a worker report its own timeout or +// memory failure before the parent force-kills it. +const ( + defaultScriptMemoryMB = 128 + // defaultScriptConcurrency is the action-script admission ceiling when the + // operator leaves concurrent_scripts unset. Each execution is a process, so + // an unset limit must not mean unbounded spawning. + defaultScriptConcurrency = 4 + scriptMemoryPollInterval = 25 * time.Millisecond + scriptWorkerKillGrace = 2 * time.Second + // scriptWorkerRSSOverhead is the non-heap headroom the parent allows on top + // of the heap budget before the RSS backstop kills a worker, so the worker's + // own heap monitor normally fires first. + scriptWorkerRSSOverhead = 32 << 20 + // scriptWorkerMaxFrameBytes bounds one newline-delimited JSON frame on the + // worker pipe. The parent rejects an over-budget frame before decoding it, so + // a script cannot make the API process allocate on script-controlled input. + scriptWorkerMaxFrameBytes = 1 << 20 +) + +// errScriptWorkerFrameTooLarge marks a protocol frame that exceeded the wire +// budget. The parent fails the node instead of decoding it. +var errScriptWorkerFrameTooLarge = errors.New("script worker frame exceeds wire budget") + +// readScriptWorkerFrame reads one newline-terminated JSON frame, failing once +// the accumulated bytes pass max. It never holds more than max+1 bytes of the +// peer's output, so a hostile frame is rejected before json.Unmarshal runs. +func readScriptWorkerFrame(reader *bufio.Reader, limit int) ([]byte, error) { + frame := make([]byte, 0, 512) + for { + chunk, err := reader.ReadSlice('\n') + if len(frame)+len(chunk) > limit { + return nil, errScriptWorkerFrameTooLarge + } + frame = append(frame, chunk...) + switch { + case err == nil: + return frame, nil + case errors.Is(err, bufio.ErrBufferFull): + continue + default: + return frame, err + } + } +} + +// Worker protocol message kinds. +const ( + scriptMessageRun = "run" + scriptMessageReady = "ready" + scriptMessageConsole = "console" + scriptMessageAPIRequest = "api_request" + scriptMessageAPIResponse = "api_response" + scriptMessageAPIFatal = "api_fatal" + scriptMessageAPIRecover = "api_error" + scriptMessageResult = "result" + scriptMessageError = "error" +) + +// Worker failure kinds. +const ( + scriptErrorTimeout = "timeout" + scriptErrorMemory = "memory" + scriptErrorPolicy = "policy" + scriptErrorRuntime = "runtime" +) + +// errScriptMemory is the interrupt value the in-worker memory monitor raises. +// Like errScriptTimeout it is a bare string so the parent can classify it +// without importing worker internals. +const errScriptMemory = "script memory limit exceeded" + +// scriptWorkerMessage is the single wire shape for every worker message. The +// Type field selects which of the remaining fields are populated; unused +// fields are omitted so the encoding stays small and forward compatible. +type scriptWorkerMessage struct { + Type string `json:"type"` + + // run + Source string `json:"source,omitempty"` + TimeoutMS int `json:"timeout_ms,omitempty"` + DeadlineUnixNano int64 `json:"deadline_unix_nano,omitempty"` + MemoryBytes int64 `json:"memory_bytes,omitempty"` + Globals map[string]any `json:"globals,omitempty"` + + // console + Level string `json:"level,omitempty"` + Message string `json:"message,omitempty"` + + // api_request / api_response + ID int `json:"id,omitempty"` + Method string `json:"method,omitempty"` + Path string `json:"path,omitempty"` + Body json.RawMessage `json:"body,omitempty"` + Status int `json:"status,omitempty"` + Response json.RawMessage `json:"response,omitempty"` + Truncated bool `json:"truncated,omitempty"` + + // result / error + Output json.RawMessage `json:"output,omitempty"` + ErrorKind string `json:"error_kind,omitempty"` +} + +// RunScriptWorker is the isolated child entry point. It executes exactly one +// script request from in and writes progress and the terminal result to out. +// It never touches the database, configuration, or any other server state. +func RunScriptWorker(in io.Reader, out io.Writer) { + encoder := json.NewEncoder(out) + var writeMu sync.Mutex + send := func(msg scriptWorkerMessage) { + writeMu.Lock() + defer writeMu.Unlock() + _ = encoder.Encode(msg) + } + + reader := bufio.NewReader(in) + frame, err := readScriptWorkerFrame(reader, scriptWorkerMaxFrameBytes) + if err != nil { + send(scriptWorkerMessage{Type: scriptMessageError, ErrorKind: scriptErrorRuntime, Message: "script worker: invalid run request"}) + return + } + var request scriptWorkerMessage + if err := json.Unmarshal(frame, &request); err != nil || request.Type != scriptMessageRun { + send(scriptWorkerMessage{Type: scriptMessageError, ErrorKind: scriptErrorRuntime, Message: "script worker: invalid run request"}) + return + } + if request.MemoryBytes > 0 { + debug.SetMemoryLimit(request.MemoryBytes) + } + send(scriptWorkerMessage{Type: scriptMessageReady}) + + output, err := runWorkerScript(reader, send, request) + if err != nil { + kind, message := classifyWorkerError(err) + send(scriptWorkerMessage{Type: scriptMessageError, ErrorKind: kind, Message: message}) + return + } + send(scriptWorkerMessage{Type: scriptMessageResult, Output: output}) +} + +// runWorkerScript builds a fresh Sobek realm, binds the explicit globals, and +// runs the script under the timeout and memory watchdogs. The realm is never +// reused: sobek cannot reset a mutated realm, and a fresh process per +// execution is what keeps one script from observing another's state. +func runWorkerScript(reader *bufio.Reader, send func(scriptWorkerMessage), request scriptWorkerMessage) (json.RawMessage, error) { + vm := sobek.New() + for name, value := range request.Globals { + if err := vm.Set(name, value); err != nil { + return nil, fmt.Errorf("bind %s: %w", name, err) + } + } + + bridge := &workerBridge{vm: vm, reader: reader, send: send} + if err := vm.Set("windshift", map[string]any{ + "api": map[string]any{"request": bridge.apiRequest}, + }); err != nil { + return nil, err + } + if err := vm.Set("console", map[string]any{ + "log": bridge.consoleFn("log"), + "info": bridge.consoleFn("info"), + "warn": bridge.consoleFn("warn"), + "error": bridge.consoleFn("error"), + "debug": bridge.consoleFn("debug"), + }); err != nil { + return nil, err + } + + program, err := sobek.Compile("action_script", "(function() {\n"+request.Source+"\n})()", false) + if err != nil { + return nil, fmt.Errorf("syntax error: %w", err) + } + + // One absolute deadline covers setup, JS, and REST calls. The parent sets + // it before launch, so a worker that spends its budget initializing cannot + // still run a fresh full timeout afterwards. + deadline := time.Now().Add(time.Duration(request.TimeoutMS) * time.Millisecond) + if request.DeadlineUnixNano > 0 { + deadline = time.Unix(0, request.DeadlineUnixNano) + } + timeoutCtx, cancel := context.WithDeadline(context.Background(), deadline) + defer cancel() + // The deadline is absolute and may already have passed if startup consumed + // the budget. Fail before running so a slow start cannot still execute JS. + if err := timeoutCtx.Err(); err != nil { + return nil, err + } + + stopMonitor := make(chan struct{}) + defer close(stopMonitor) + if request.MemoryBytes > 0 { + go monitorWorkerMemory(vm, request.MemoryBytes, stopMonitor) + } + + result, err := runScriptProgram(vm, program, timeoutCtx) + if err != nil { + return nil, err + } + encoded, err := json.Marshal(result) + if err != nil { + return nil, fmt.Errorf("result is not JSON-serializable: %w", err) + } + return encoded, nil +} + +// monitorWorkerMemory interrupts a runaway script once its live heap passes the +// per-script budget. debug.SetMemoryLimit makes the collector work against the +// same ceiling; this monitor is the hard stop that ends the execution. +func monitorWorkerMemory(vm *sobek.Runtime, budget int64, stop <-chan struct{}) { + ticker := time.NewTicker(scriptMemoryPollInterval) + defer ticker.Stop() + var stats runtime.MemStats + for { + select { + case <-stop: + return + case <-ticker.C: + runtime.ReadMemStats(&stats) + if int64(stats.HeapAlloc) > budget { //nolint:gosec // G115: heap sizes are far below MaxInt64 + vm.Interrupt(errScriptMemory) + return + } + } + } +} + +// scriptPolicyViolation carries a fatal bridge-policy refusal back to the +// parent as an interrupt value. Interrupts are uncatchable, so a script cannot +// swallow a policy denial. +type scriptPolicyViolation struct{ Reason string } + +func (e *scriptPolicyViolation) Error() string { return "script api policy violation: " + e.Reason } + +// workerBridge translates the two host calls a script can make into protocol +// messages. Every call is synchronous: the worker blocks until the parent +// answers, so the parent stays the sole authority on credentials, budgets, and +// policy. +type workerBridge struct { + vm *sobek.Runtime + reader *bufio.Reader + send func(scriptWorkerMessage) + nextID int +} + +func (b *workerBridge) apiRequest(call sobek.FunctionCall) sobek.Value { + options := call.Argument(0) + if scriptValueMissing(options) { + panic(b.vm.NewTypeError("windshift.api.request(options) requires an options object")) + } + obj := options.ToObject(b.vm) + methodVal := scriptObjectGet(obj, "method") + pathVal := scriptObjectGet(obj, "path") + if scriptValueMissing(methodVal) || scriptValueMissing(pathVal) { + panic(b.vm.NewTypeError("windshift.api.request requires method and path")) + } + method := strings.TrimSpace(methodVal.String()) + path := pathVal.String() + + var body json.RawMessage + if bodyVal := scriptObjectGet(obj, "body"); !scriptValueMissing(bodyVal) { + encoded, err := json.Marshal(bodyVal.Export()) + if err != nil { + panic(b.vm.NewTypeError("body must be JSON-serializable: " + err.Error())) + } + if len(encoded) > maxScriptRequestBodyBytes { + b.vm.Interrupt(&scriptPolicyViolation{Reason: fmt.Sprintf("request body exceeds %d bytes", maxScriptRequestBodyBytes)}) + return sobek.Undefined() + } + body = encoded + } + + b.nextID++ + id := b.nextID + b.send(scriptWorkerMessage{Type: scriptMessageAPIRequest, ID: id, Method: method, Path: path, Body: body}) + + var response scriptWorkerMessage + frame, err := readScriptWorkerFrame(b.reader, scriptWorkerMaxFrameBytes) + if err != nil { + b.vm.Interrupt(fmt.Errorf("script worker: api bridge closed: %w", err)) + return sobek.Undefined() + } + if err := json.Unmarshal(frame, &response); err != nil { + b.vm.Interrupt(errors.New("script worker: invalid api bridge message")) + return sobek.Undefined() + } + if response.ID != id { + b.vm.Interrupt(errors.New("script worker: api bridge out of sync")) + return sobek.Undefined() + } + switch response.Type { + case scriptMessageAPIResponse: + return b.responseValue(response) + case scriptMessageAPIFatal: + b.vm.Interrupt(&scriptPolicyViolation{Reason: response.Message}) + return sobek.Undefined() + case scriptMessageAPIRecover: + // A transient dispatch failure is catchable, matching the in-process + // executor: only policy violations are uncatchable. + panic(b.vm.NewGoError(fmt.Errorf("windshift.api.request failed: %s", response.Message))) + default: + b.vm.Interrupt(errors.New("script worker: unexpected api bridge message")) + return sobek.Undefined() + } +} + +// responseValue mirrors the in-process response shape: status, ok, truncated, +// and a body decoded from JSON when it parses, else the raw text. +func (b *workerBridge) responseValue(response scriptWorkerMessage) sobek.Value { + result := b.vm.NewObject() + _ = result.Set("status", response.Status) + _ = result.Set("ok", response.Status >= 200 && response.Status < 300) + _ = result.Set("truncated", response.Truncated) + if len(response.Response) > 0 { + var decoded any + if err := json.Unmarshal(response.Response, &decoded); err == nil { + _ = result.Set("body", decoded) + } else { + _ = result.Set("body", string(response.Response)) + } + } else { + _ = result.Set("body", "") + } + return result +} + +// consoleFn forwards one bounded console line to the parent. The parent owns +// the entry and byte budgets; the worker only caps the individual line so a +// single call cannot send an unbounded message. +func (b *workerBridge) consoleFn(level string) func(sobek.FunctionCall) sobek.Value { + return func(call sobek.FunctionCall) sobek.Value { + parts := make([]string, 0, len(call.Arguments)) + for _, arg := range call.Arguments { + parts = append(parts, scriptValueString(arg)) + } + line := strings.Join(parts, " ") + // Cap the wire line one byte over the entry budget so the parent still + // sees an over-budget line and appends its truncation marker. + if len(line) > maxScriptConsoleEntryBytes+1 { + line = line[:maxScriptConsoleEntryBytes+1] + } + b.send(scriptWorkerMessage{Type: scriptMessageConsole, Level: level, Message: line}) + return sobek.Undefined() + } +} + +// classifyWorkerError maps a worker-side error to the protocol failure kind and +// a bounded message. It never formats a script-backed value. +func classifyWorkerError(err error) (kind, message string) { + if errors.Is(err, context.DeadlineExceeded) { + return scriptErrorTimeout, "script execution timed out" + } + var interrupted *sobek.InterruptedError + if errors.As(err, &interrupted) { + switch value := interrupted.Value().(type) { + case string: + switch value { + case errScriptTimeout: + return scriptErrorTimeout, "script execution timed out" + case errScriptMemory: + return scriptErrorMemory, "script memory limit exceeded" + } + case *scriptPolicyViolation: + return scriptErrorPolicy, value.Reason + case error: + return scriptErrorRuntime, boundedScriptText(value.Error()) + } + } + return scriptErrorRuntime, boundedScriptText(err.Error()) +} + +// ScriptWorkerProcess is one isolated worker process executing one script. +type ScriptWorkerProcess interface { + Stdin() io.Writer + Stdout() io.Reader + RSSBytes() (int64, error) + Kill() error + Wait() error +} + +// ScriptWorkerLauncher starts an isolated worker for a single execution. It is +// an interface so tests can run the worker in-process and so a pooled or +// out-of-process launcher can replace it without touching the executor. +type ScriptWorkerLauncher interface { + Launch(ctx context.Context) (ScriptWorkerProcess, error) +} + +// SubprocessScriptLauncher runs the worker as a child of the current binary, +// selected by EnvScriptWorker. The child shares the binary but not the address +// space, so a runaway allocation is killed by the OS instead of the server. +type SubprocessScriptLauncher struct{} + +var defaultScriptWorkerLauncher ScriptWorkerLauncher = SubprocessScriptLauncher{} + +func (SubprocessScriptLauncher) Launch(ctx context.Context) (ScriptWorkerProcess, error) { + executable, err := os.Executable() + if err != nil { + return nil, fmt.Errorf("resolve worker executable: %w", err) + } + cmd := exec.CommandContext(ctx, executable) //nolint:gosec // G204: the worker is this binary + cmd.Env = append(withoutEnv(os.Environ(), EnvScriptWorker), EnvScriptWorker+"=1") + stdin, err := cmd.StdinPipe() + if err != nil { + return nil, err + } + stdout, err := cmd.StdoutPipe() + if err != nil { + return nil, err + } + stderr, err := cmd.StderrPipe() + if err != nil { + return nil, err + } + if err := cmd.Start(); err != nil { + return nil, fmt.Errorf("start script worker: %w", err) + } + proc := &subprocessScriptWorker{cmd: cmd, stdin: stdin, stdout: stdout} + go proc.drainStderr(stderr) + return proc, nil +} + +type subprocessScriptWorker struct { + cmd *exec.Cmd + stdin io.WriteCloser + stdout io.ReadCloser +} + +func (w *subprocessScriptWorker) Stdin() io.Writer { return w.stdin } +func (w *subprocessScriptWorker) Stdout() io.Reader { return w.stdout } + +func (w *subprocessScriptWorker) RSSBytes() (int64, error) { + if w.cmd.Process == nil { + return 0, nil + } + return processRSSBytes(w.cmd.Process.Pid) +} + +func (w *subprocessScriptWorker) Kill() error { + if w.cmd.Process == nil { + return nil + } + _ = w.stdin.Close() + return w.cmd.Process.Kill() +} + +func (w *subprocessScriptWorker) Wait() error { return w.cmd.Wait() } + +// drainStderr consumes the child's stderr so a chatty worker cannot block on a +// full pipe. Worker diagnostics are deliberately not surfaced to scripts. +func (w *subprocessScriptWorker) drainStderr(stderr io.Reader) { + _, _ = io.Copy(io.Discard, stderr) +} + +// withoutEnv drops any existing assignment for key so the appended value wins. +func withoutEnv(env []string, key string) []string { + prefix := key + "=" + filtered := env[:0] + for _, entry := range env { + if !strings.HasPrefix(entry, prefix) { + filtered = append(filtered, entry) + } + } + return filtered +} + +// watchWorkerMemory is the parent-side hard backstop: if the child's resident +// set passes its own baseline plus the budget, the parent kills it. The child's +// in-process monitor normally fires first and reports an explainable failure. +func watchWorkerMemory(proc ScriptWorkerProcess, limit int64, stop <-chan struct{}, exceeded *atomic.Bool) { + ticker := time.NewTicker(scriptMemoryPollInterval) + defer ticker.Stop() + for { + select { + case <-stop: + return + case <-ticker.C: + rss, err := proc.RSSBytes() + if err != nil || rss <= 0 { + continue + } + if rss > limit { + exceeded.Store(true) + _ = proc.Kill() + return + } + } + } +} diff --git a/internal/services/script_worker_rss_linux.go b/internal/services/script_worker_rss_linux.go new file mode 100644 index 000000000..65905d03e --- /dev/null +++ b/internal/services/script_worker_rss_linux.go @@ -0,0 +1,29 @@ +//go:build linux + +package services + +import ( + "fmt" + "os" + "strconv" + "strings" +) + +// processRSSBytes reads the resident set size of a process from procfs. It is +// the parent-side backstop that bounds a runaway worker's real memory, not just +// its Go heap. +func processRSSBytes(pid int) (int64, error) { + raw, err := os.ReadFile(fmt.Sprintf("/proc/%d/statm", pid)) + if err != nil { + return 0, err + } + fields := strings.Fields(string(raw)) + if len(fields) < 2 { + return 0, fmt.Errorf("unexpected statm format for pid %d", pid) + } + residentPages, err := strconv.ParseInt(fields[1], 10, 64) + if err != nil { + return 0, err + } + return residentPages * int64(os.Getpagesize()), nil +} diff --git a/internal/services/script_worker_rss_other.go b/internal/services/script_worker_rss_other.go new file mode 100644 index 000000000..382ad3ba5 --- /dev/null +++ b/internal/services/script_worker_rss_other.go @@ -0,0 +1,8 @@ +//go:build !linux + +package services + +// processRSSBytes is unavailable off Linux. The worker's own heap monitor still +// stops a runaway allocation and reports an explainable failure; the parent +// simply cannot add the RSS backstop. +func processRSSBytes(int) (int64, error) { return 0, nil } diff --git a/main.go b/main.go index 43fb84918..6ea1c9a2a 100644 --- a/main.go +++ b/main.go @@ -29,6 +29,7 @@ import ( "windshift/internal/logger" "windshift/internal/middleware" "windshift/internal/server" + "windshift/internal/services" "windshift/internal/tui" "windshift/internal/utils" @@ -61,6 +62,14 @@ func printBanner() { } func main() { + // The isolated script worker is selected by environment so the same binary + // can host both roles. It must run before config, logging, or the database + // are touched: a worker owns no server state. + if os.Getenv(services.EnvScriptWorker) == "1" { + services.RunScriptWorker(os.Stdin, os.Stdout) + return + } + if len(os.Args) > 1 && os.Args[1] == "healthcheck" { // TLS_CERT/TLS_KEY are the supported way to tell both the server and // this subcommand that the internal listener terminates TLS directly.