Skip to content

armgit / Pulse

Public Imported from GitHub
0

Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.

Keep Assistant result responses non-executable

pulse-triage[bot]483debd031a8
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
index bf577a95d9..df9628a04c 100644
--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
@@ -24,6 +24,12 @@ and 120/180-second bounds remain: client cancellation still ends request-bound
provider work. Native JSON independent-reader, cancellation and persisted-delete
regressions exercise this boundary with synthetic text, not tools or agents.
+The synchronous result transport also pins non-executable media: JSON or plain
+text with `nosniff`, never HTML/SVG/JavaScript from a downstream type or HTTP
+sniffing. It preserves result bytes, status, current-authority checks and
+execution/cancellation lifetime. Native HTTP and both actual core-handler
+round-trip regressions use text-only fixtures, not agent execution.
+
### Assistant result streams do not own agent execution lifetime
Assistant HTTP result readers recheck current token authority at their serialized
diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.md
index 2cc02cdc3d..cab0350298 100644
--- a/docs/release-control/v6/internal/subsystems/api-contracts.md
+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md
@@ -52,6 +52,31 @@ undisclosed headers/bodyless refusal, admitted prefixes, closure, transport erro
and no bypass. These are synthetic source proofs, not installed/private-binary
recovery, exposure or release evidence.
+### Non-executable media at the Assistant result boundary
+
+The synchronous writer on the existing execute and Kubernetes analysis result
+routes admits only `application/json` or `text/plain; charset=utf-8`, with
+`X-Content-Type-Options: nosniff` on the actual response transport. Valid JSON
+media parameters are normalized to the JSON type. Missing, malformed or other
+handler types fall back to plain text; none may turn a result into HTML, SVG or
+JavaScript. Alternate-case media headers are discarded before the canonical
+headers are set. Payload bytes, status and other admitted headers are preserved:
+JSON is not HTML-escaped twice, parsed or buffered by this boundary.
+
+This does not change admission, withdrawal checks, request cancellation or the
+extension licence gate. Undisclosed withdrawn responses still return the generic
+401 without handler headers; committed responses cannot change media later.
+The actual core handlers already marshal their successful payloads as JSON and
+return plain errors. The narrower writer contract also prevents a downstream
+implementation from omitting a type and relying on HTTP content sniffing.
+
+`token_response_media_test.go` exercises native HTTP with omitted, malformed,
+HTML/XHTML/SVG/JavaScript, JSON and plain-text types, explicit and implicit status,
+JSON round-trip and noncanonical headers. `TestContract_AssistantJSONMediaBoundary`
+checks both real handlers through the full Router with token and session readers,
+a text-only local provider and HTML-shaped data. These are source regressions,
+not installed/private-binary acceptance or a security-scanner disposition.
+
### Assistant streams use current token authority at disclosure
The existing POST `execute/stream`, `investigate-alert` and `chat` routes
diff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.md
index d59e390469..db88246d4d 100644
--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md
+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md
@@ -30,6 +30,12 @@ does not delete evidence, reset recovery state, widen grants or cancel a recover
job. Native JSON independent-reader and persisted-token-delete regressions cover
the disclosure boundary without replaying a recovery workload or changing data.
+Assistant synchronous results are returned as JSON or plain text with
+`nosniff`; omitted or executable downstream media cannot make recovery-related
+result text render as HTML. The transport does not rewrite result bytes,
+mutate saved evidence or cancel work. Native media and core-handler round-trip
+regressions do not establish original workload or filesystem recovery.
+
### Assistant reader withdrawal is not a recovery mutation
The shared API stream guard also covers Assistant results, not recovery-state
diff --git a/internal/api/assistant_json_media_test.go b/internal/api/assistant_json_media_test.go
new file mode 100644
index 0000000000..bf17c229b5
--- /dev/null
+++ b/internal/api/assistant_json_media_test.go
@@ -0,0 +1,51 @@
+package api
+
+import (
+ "encoding/json"
+ "io"
+ "net/http"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/config"
+)
+
+// Exercise actual execute/Kubernetes handlers, a held local text-only provider
+// and the full Router. Markup must round-trip as data, not escaped twice or
+// rendered as an HTML response. This is not a private-binary/licence proof.
+func assistantJSONMediaReply(t *testing.T, kind, transport string) (http.Header, int, []byte) {
+ t.Helper()
+ f := newAssistantJSONFixture(t, kind, []string{config.ScopeAIExecute})
+ f.primary.result = responseMediaMarkup
+ raw := f.token
+ if transport == "session" {
+ raw = "synthetic-assistant-media-session"
+ GetSessionStore().CreateSession(raw, time.Hour, "fixture", "127.0.0.1", f.router.config.AuthUser)
+ t.Cleanup(func() { GetSessionStore().DeleteSession(raw) })
+ }
+ result := f.begin(t, "primary", raw, transport)
+ f.primary.unblock()
+ var got assistantJSONResult
+ select {
+ case got = <-result:
+ case <-time.After(5 * time.Second):
+ t.Fatal("JSON media response did not finish")
+ }
+ if got.err != nil {
+ t.Fatal(got.err)
+ }
+ defer got.response.Body.Close()
+ body, err := io.ReadAll(got.response.Body)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var value AIExecuteResponse
+ if got.response.StatusCode != http.StatusOK || json.Unmarshal(body, &value) != nil || value.Content != responseMediaMarkup {
+ t.Fatalf("actual %s response did not round-trip: %d %q", kind, got.response.StatusCode, body)
+ }
+ if got.response.Header.Get("Content-Type") != "application/json" || got.response.Header.Get("X-Content-Type-Options") != "nosniff" || strings.Contains(string(body), "<script>") {
+ t.Fatalf("actual %s response not safe as data: %v %q", kind, got.response.Header, body)
+ }
+ return got.response.Header, got.response.StatusCode, body
+}
diff --git a/internal/api/assistant_stream_lifetime_test.go b/internal/api/assistant_stream_lifetime_test.go
index 5b20a99749..f865b19386 100644
--- a/internal/api/assistant_stream_lifetime_test.go
+++ b/internal/api/assistant_stream_lifetime_test.go
@@ -32,6 +32,7 @@ type assistantProviderGate struct {
enterOnce, releaseOnce sync.Once
calls atomic.Int32
cancelled atomic.Bool
+ result string // Set before the request; empty retains the ordinary fixture text.
}
func newAssistantProviderGate() *assistantProviderGate {
@@ -114,6 +115,9 @@ func newAssistantStreamFixture(t *testing.T, kind string, scopes []string, write
return
}
content = assistantPrivateResult
+ if gate.result != "" {
+ content = gate.result
+ }
}
_ = json.NewEncoder(w).Encode(map[string]any{
"model": "llama3", "message": map[string]any{"role": "assistant", "content": content},
diff --git a/internal/api/contract_test.go b/internal/api/contract_test.go
index 17e954a68a..6e21543924 100644
--- a/internal/api/contract_test.go
+++ b/internal/api/contract_test.go
@@ -29020,3 +29020,15 @@ func TestContract_AssistantJSONWithdrawAfterPersistedTokenDelete(t *testing.T) {
func TestContractSessionReadLogoutBoundary(t *testing.T) {
sessionReadBrowserEvidence(t)
}
+
+// The existing JSON result routes must preserve hostile-shaped provider text
+// as data, for actual token and session readers through the complete Router.
+func TestContract_AssistantJSONMediaBoundary(t *testing.T) {
+ for _, kind := range []string{"execute", "kubernetes"} {
+ for _, transport := range []string{"header", "session"} {
+ t.Run(kind+"/"+transport, func(t *testing.T) {
+ assistantJSONMediaReply(t, kind, transport)
+ })
+ }
+ }
+}
diff --git a/internal/api/token_response_authority.go b/internal/api/token_response_authority.go
index b5fb5f753f..9998a48c8b 100644
--- a/internal/api/token_response_authority.go
+++ b/internal/api/token_response_authority.go
@@ -2,7 +2,9 @@ package api
import (
"io"
+ "mime"
"net/http"
+ "strings"
"sync"
"github.com/rcourtman/pulse-go-rewrite/internal/config"
@@ -76,8 +78,23 @@ func (w *tokenResponseWriter) commitLocked(status int) {
header := w.writer.Header()
clear(header)
for key, values := range w.header {
+ if strings.EqualFold(key, "Content-Type") || strings.EqualFold(key, "X-Content-Type-Options") {
+ continue
+ }
header[key] = append([]string(nil), values...)
}
+ // These result endpoints serve JSON or plain-text errors, never HTML.
+ // Bind non-executable media to the actual transport, not just the
+ // handler's private header map. Missing, malformed or unexpected
+ // types must not allow HTTP sniffing or an extension to render HTML.
+ // Leave payload bytes alone: HTML-escaping JSON would corrupt data.
+ mediaType, err := mime.ParseMediaType(w.header.Get("Content-Type"))
+ if err == nil && mediaType == "application/json" {
+ header.Set("Content-Type", "application/json")
+ } else {
+ header.Set("Content-Type", "text/plain; charset=utf-8")
+ }
+ header.Set("X-Content-Type-Options", "nosniff")
w.writer.WriteHeader(status)
// Informational headers do not commit the final response.
w.started = status >= 200 || status == http.StatusSwitchingProtocols
diff --git a/internal/api/token_response_media_test.go b/internal/api/token_response_media_test.go
new file mode 100644
index 0000000000..387164f39f
--- /dev/null
+++ b/internal/api/token_response_media_test.go
@@ -0,0 +1,149 @@
+package api
+
+import (
+ "encoding/json"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/utils"
+)
+
+const responseMediaMarkup = `<script>globalThis.__pulseMediaExecuted=true</script><p>Synthetic result</p>`
+
+type responseMediaCase struct {
+ name, contentType, wantType string
+}
+
+var responseMediaCases = []responseMediaCase{
+ {"missing", "", "text/plain; charset=utf-8"},
+ {"html", "text/html", "text/plain; charset=utf-8"},
+ {"xhtml", "application/xhtml+xml", "text/plain; charset=utf-8"},
+ {"svg", "image/svg+xml", "text/plain; charset=utf-8"},
+ {"javascript", "application/javascript", "text/plain; charset=utf-8"},
+ {"malformed", "application/json; broken", "text/plain; charset=utf-8"},
+ {"json", "application/json", "application/json"},
+ {"json_parameters", "Application/JSON; charset=utf-8", "application/json"},
+ {"plain", "text/plain", "text/plain; charset=utf-8"},
+}
+
+// Use a real HTTP server: ResponseRecorder does not reproduce the transport's
+// automatic HTML sniff when a downstream writer omits Content-Type.
+func requestResponseMedia(t *testing.T, media responseMediaCase, explicit bool) (http.Header, int, []byte) {
+ t.Helper()
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ writer := &tokenResponseWriter{writer: w, header: w.Header().Clone(), allowed: func() bool { return true }}
+ defer writer.close()
+ if media.contentType != "" {
+ writer.Header().Set("Content-Type", media.contentType)
+ }
+ writer.Header().Set("X-Synthetic-Result", "preserved")
+ if explicit {
+ writer.WriteHeader(http.StatusAccepted)
+ }
+ if _, err := writer.Write([]byte(responseMediaMarkup)); err != nil {
+ t.Error(err)
+ }
+ }))
+ defer server.Close()
+ response, err := server.Client().Get(server.URL)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer response.Body.Close()
+ body, err := io.ReadAll(response.Body)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return response.Header, response.StatusCode, body
+}
+
+func TestTokenResponseWriterNativeMedia(t *testing.T) {
+ for _, media := range responseMediaCases {
+ for _, explicit := range []bool{false, true} {
+ name := media.name + "/implicit"
+ if explicit {
+ name = media.name + "/explicit"
+ }
+ t.Run(name, func(t *testing.T) {
+ headers, status, body := requestResponseMedia(t, media, explicit)
+ wantStatus := http.StatusOK
+ if explicit {
+ wantStatus = http.StatusAccepted
+ }
+ if status != wantStatus || string(body) != responseMediaMarkup || headers.Get("X-Synthetic-Result") != "preserved" {
+ t.Fatalf("response changed: status=%d headers=%v body=%q", status, headers, body)
+ }
+ if headers.Get("Content-Type") != media.wantType || headers.Get("X-Content-Type-Options") != "nosniff" {
+ t.Fatalf("executable/ambiguous media escaped the result boundary: type=%q nosniff=%q", headers.Get("Content-Type"), headers.Get("X-Content-Type-Options"))
+ }
+ })
+ }
+ }
+}
+
+func TestTokenResponseWriterJSONRoundTrip(t *testing.T) {
+ value := responseMediaMarkup + " & quotes \" line\u2028paragraph\u2029"
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ writer := &tokenResponseWriter{writer: w, header: w.Header().Clone(), allowed: func() bool { return true }}
+ defer writer.close()
+ if err := utils.WriteJSONResponse(writer, map[string]string{"content": value}); err != nil {
+ t.Error(err)
+ }
+ }))
+ defer server.Close()
+ response, err := server.Client().Get(server.URL)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer response.Body.Close()
+ body, err := io.ReadAll(response.Body)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var got map[string]string
+ if response.StatusCode != http.StatusOK || json.Unmarshal(body, &got) != nil || got["content"] != value {
+ t.Fatalf("JSON changed: %d %q", response.StatusCode, body)
+ }
+ if response.Header.Get("Content-Type") != "application/json" || response.Header.Get("X-Content-Type-Options") != "nosniff" || strings.Contains(string(body), "<script>") {
+ t.Fatalf("JSON response not safe as data: %v %q", response.Header, body)
+ }
+}
+
+func TestTokenResponseWriterMediaCannotChangeAfterCommit(t *testing.T) {
+ base := httptest.NewRecorder()
+ writer := &tokenResponseWriter{writer: base, header: base.Header().Clone(), allowed: func() bool { return true }}
+ defer writer.close()
+ writer.Header().Set("Content-Type", "application/json")
+ writer.WriteHeader(http.StatusOK)
+ writer.Header().Set("Content-Type", "text/html")
+ writer.Header().Del("X-Content-Type-Options")
+ if _, err := writer.Write([]byte(`{"content":"<script>not executable</script>"}`)); err != nil {
+ t.Fatal(err)
+ }
+ response := base.Result()
+ defer response.Body.Close()
+ if response.Header.Get("Content-Type") != "application/json" || response.Header.Get("X-Content-Type-Options") != "nosniff" {
+ t.Fatalf("committed response media changed: %v", response.Header)
+ }
+}
+
+func TestTokenResponseWriterNonCanonicalMediaHeaders(t *testing.T) {
+ base := httptest.NewRecorder()
+ writer := &tokenResponseWriter{writer: base, header: base.Header().Clone(), allowed: func() bool { return true }}
+ defer writer.close()
+ writer.Header().Set("Content-Type", "application/json")
+ writer.Header()["content-type"] = []string{"text/html"}
+ writer.Header()["CONTENT-TYPE"] = []string{"image/svg+xml"}
+ writer.Header()["x-content-type-options"] = []string{"invalid"}
+ if _, err := writer.Write([]byte(`{"content":"<script>data</script>"}`)); err != nil {
+ t.Fatal(err)
+ }
+ response := base.Result()
+ defer response.Body.Close()
+ if len(response.Header.Values("Content-Type")) != 1 || response.Header.Get("Content-Type") != "application/json" || len(response.Header.Values("X-Content-Type-Options")) != 1 || response.Header.Get("X-Content-Type-Options") != "nosniff" || len(response.Header) != 2 {
+ t.Fatalf("alternate-case media headers survived: %v", response.Header)
+ }
+}