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.

Withhold withdrawn Assistant JSON results

pulse-triage[bot]a1a38e355ad5
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
index 8da31705bd..d4289ca7ee 100644
--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
@@ -15,6 +15,15 @@
## Purpose
+### Slow Assistant JSON reads do not own work cancellation
+
+The synchronous execute and Kubernetes-analysis routes retain current API-token
+authority at their result writer. Withdrawal withholds results, not an agent
+disconnect, command cancellation or new grant. Their original request context
+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.
+
### 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 3558d4e608..05b7c1c50e 100644
--- a/docs/release-control/v6/internal/subsystems/api-contracts.md
+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md
@@ -21,6 +21,37 @@
## Purpose
+### Slow Assistant JSON results use current token authority
+
+The existing POST `execute` and `kubernetes/analyze` routes revalidate the
+admitted API-token identity, principal, `ai:execute` scope and selected
+organisation/instance authority at each response write, not only before waiting
+for the provider. The Kubernetes guard sits outside the extension binding.
+Revocation, expiry, identity/principal replacement, invalid runtime role or lost
+scope/organisation/instance authority denies undisclosed results. Before a final
+response is committed, refusal returns a generic 401 without handler-specific
+headers, JSON data or false empty success. After an admitted prefix, refusal
+only stops later writes; it never appends a new HTTP error to that response.
+An already-admitted write can be in flight when authority changes.
+
+This synchronous writer exposes no streaming, hijacking, `ReaderFrom` or
+`Unwrap` escape, buffers no payload and closes at handler return. It does not
+replace the original request context, cancel admitted work on token withdrawal,
+change the 120/180-second execution bounds, or detach work from normal client
+cancellation. Session/proxy admission, licence checks, authorised payloads and
+the retired raw-command endpoint remain unchanged. No new route, tool, history
+source or grant is added.
+
+`assistant_json_lifetime_test.go` uses the full Router, native HTTP and real
+execute/Kubernetes core handlers with a held local text-only provider. Both token
+headers, independent readers, all withdrawal cases, unchanged session/proxy
+readers, client cancellation and the extension licence refusal are covered.
+`TestContract_AssistantJSONWithdrawAfterPersistedTokenDelete` exercises the real
+DELETE and durable token inventory for both JSON routes. Writer regressions pin
+undisclosed headers/bodyless refusal, admitted prefixes, closure, transport errors
+and no bypass. These are synthetic source proofs, not installed/private-binary
+recovery, exposure or release evidence.
+
### 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 95ad6a1963..8c4ee5f6c4 100644
--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md
+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md
@@ -21,6 +21,15 @@
## Purpose
+### Slow Assistant JSON refusal preserves recovery state
+
+Current token authority is also retained at the synchronous Assistant execute
+and Kubernetes result writers. Lost access returns a generic 401 before any
+final response is committed, not an empty successful recovery result. Refusal
+does not delete evidence, reset recovery state, widen grants or cancel a recovery
+job. Native JSON independent-reader and persisted-token-delete regressions cover
+the disclosure boundary without replaying a recovery workload or changing data.
+
### 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_lifetime_test.go b/internal/api/assistant_json_lifetime_test.go
new file mode 100644
index 0000000000..7de8fc9257
--- /dev/null
+++ b/internal/api/assistant_json_lifetime_test.go
@@ -0,0 +1,308 @@
+package api
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "net/http"
+ "strings"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/config"
+ "github.com/rcourtman/pulse-go-rewrite/internal/models"
+ "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"
+ internalauth "github.com/rcourtman/pulse-go-rewrite/pkg/auth"
+ "github.com/rcourtman/pulse-go-rewrite/pkg/extensions"
+)
+
+// Exercise the actual public analysis handler through the extension boundary,
+// not a stand-in result writer. This is not private-binary/licence proof.
+type assistantJSONAnalysisFixture struct {
+ extensions.AIAlertAnalysisEndpoints
+ runtime extensions.AIAlertAnalysisRuntime
+ licensed *atomic.Bool
+}
+
+func (f assistantJSONAnalysisFixture) HandleAnalyzeKubernetesCluster(w http.ResponseWriter, r *http.Request) {
+ if !f.licensed.Load() {
+ f.runtime.WriteLicenseRequired(w, featureKubernetesAIKey, "Kubernetes analysis requires Pulse Pro")
+ return
+ }
+ f.runtime.CoreHandlers.HandleAnalyzeKubernetesCluster(w, r)
+}
+
+type assistantJSONFixture struct {
+ *assistantStreamFixture
+ kind string
+ licensed *atomic.Bool
+}
+
+func newAssistantJSONFixture(t *testing.T, kind string, scopes []string) *assistantJSONFixture {
+ t.Helper()
+ licensed := &atomic.Bool{}
+ licensed.Store(true)
+ if kind == "kubernetes" {
+ aiAlertAnalysisBindMu.RLock()
+ previous := aiAlertAnalysisEndpointsBinder
+ aiAlertAnalysisBindMu.RUnlock()
+ SetAIAlertAnalysisEndpointsBinder(func(defaults extensions.AIAlertAnalysisEndpoints, runtime extensions.AIAlertAnalysisRuntime) extensions.AIAlertAnalysisEndpoints {
+ return assistantJSONAnalysisFixture{defaults, runtime, licensed}
+ })
+ defer SetAIAlertAnalysisEndpointsBinder(previous)
+ }
+ // Share the held text-only Ollama and native full-Router setup. The JSON
+ // requests below never open an SSE reader or execute a tool/agent/command.
+ f := &assistantJSONFixture{newAssistantStreamFixture(t, "json-"+kind, scopes), kind, licensed}
+ if kind == "kubernetes" {
+ registry := unifiedresources.NewRegistry(nil)
+ registry.IngestSnapshot(models.StateSnapshot{KubernetesClusters: []models.KubernetesCluster{
+ {ID: "json-primary", Name: "stream-fixture-primary"},
+ {ID: "json-control", Name: "stream-fixture-control"},
+ }})
+ f.router.aiSettingsHandler.defaultAIService.SetReadState(registry)
+ }
+ return f
+}
+
+func (f *assistantJSONFixture) request(t *testing.T, label, raw, transport string) *http.Request {
+ t.Helper()
+ req := f.assistantStreamFixture.request(t, label, raw, transport)
+ req.URL.Path = "/api/ai/execute"
+ if f.kind == "kubernetes" {
+ req.URL.Path = "/api/ai/kubernetes/analyze"
+ body := fmt.Sprintf(`{"cluster_id":"json-%s"}`, label)
+ req.Body = io.NopCloser(strings.NewReader(body))
+ req.ContentLength = int64(len(body))
+ req.GetBody = nil
+ }
+ return req
+}
+
+type assistantJSONResult struct {
+ response *http.Response
+ err error
+}
+
+func (f *assistantJSONFixture) begin(t *testing.T, label, raw, transport string) <-chan assistantJSONResult {
+ t.Helper()
+ req := f.request(t, label, raw, transport)
+ result := make(chan assistantJSONResult, 1)
+ go func() {
+ response, err := f.server.Client().Do(req)
+ result <- assistantJSONResult{response, err}
+ }()
+ gate := f.primary
+ if label == "control" {
+ gate = f.control
+ }
+ select {
+ case <-gate.entered:
+ case got := <-result:
+ if got.response != nil {
+ defer got.response.Body.Close()
+ body, _ := io.ReadAll(got.response.Body)
+ t.Fatalf("JSON request returned before its provider gate: %d %s", got.response.StatusCode, body)
+ }
+ t.Fatalf("JSON request failed before its provider gate: %v", got.err)
+ case <-time.After(5 * time.Second):
+ t.Fatal("JSON request did not reach its prompt-bound provider gate")
+ }
+ return result
+}
+
+func readAssistantJSONResult(t *testing.T, result <-chan assistantJSONResult, visible bool) {
+ t.Helper()
+ var got assistantJSONResult
+ select {
+ case got = <-result:
+ case <-time.After(5 * time.Second):
+ t.Fatal("JSON request did not finish after its provider released")
+ }
+ 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)
+ }
+ if visible {
+ var response AIExecuteResponse
+ if got.response.StatusCode != http.StatusOK || !strings.Contains(got.response.Header.Get("Content-Type"), "application/json") || json.Unmarshal(body, &response) != nil || response.Content != assistantPrivateResult {
+ t.Fatalf("authorised JSON response changed: %d %s", got.response.StatusCode, body)
+ }
+ return
+ }
+ if got.response.StatusCode != http.StatusUnauthorized || strings.Contains(string(body), assistantPrivateResult) || !strings.Contains(string(body), "Authentication required") || strings.Contains(got.response.Header.Get("Content-Type"), "application/json") {
+ t.Fatalf("withdrawn JSON reader received result/success instead of auth refusal: %d %s", got.response.StatusCode, body)
+ }
+}
+
+func TestAssistantJSONWithdrawAuthority(t *testing.T) {
+ for _, kind := range []string{"execute", "kubernetes"} {
+ for _, transport := range []string{"header", "bearer"} {
+ for _, change := range []string{"revoked", "expired", "scope_removed", "org_removed", "credential_replaced", "principal_replaced", "invalid_role", "instance_removed"} {
+ t.Run(kind+"/"+transport+"/"+change, func(t *testing.T) {
+ f := newAssistantJSONFixture(t, kind, []string{config.ScopeAIExecute})
+ control := f.begin(t, "control", assistantControlToken, "header")
+ primary := f.begin(t, "primary", f.token, transport)
+ config.Mu.Lock()
+ record := &f.router.config.APITokens[0]
+ switch change {
+ case "revoked":
+ f.router.config.RemoveAPIToken(record.ID)
+ case "expired":
+ past := time.Now().Add(-time.Second)
+ record.ExpiresAt = &past
+ case "scope_removed":
+ record.Scopes = []string{config.ScopeMonitoringRead}
+ case "org_removed":
+ record.OrgIDs = []string{"other-org"}
+ case "credential_replaced":
+ record.ID = "replacement-json-credential"
+ case "principal_replaced":
+ record.Metadata = map[string]string{apiTokenMetadataOwnerUserID: "replacement-json-principal"}
+ case "invalid_role":
+ record.Metadata = map[string]string{internalauth.RuntimeRoleMetadataKey: internalauth.RuntimeRoleActionRunner}
+ case "instance_removed":
+ record.OrgIDs = []string{"default", "another-org"}
+ }
+ config.Mu.Unlock()
+ if change != "credential_replaced" && change != "principal_replaced" {
+ fresh, err := f.server.Client().Do(f.request(t, "primary", f.token, transport))
+ if err != nil {
+ t.Fatal(err)
+ }
+ fresh.Body.Close()
+ want := http.StatusForbidden
+ if change == "revoked" || change == "expired" || change == "invalid_role" {
+ want = http.StatusUnauthorized
+ }
+ if fresh.StatusCode != want || f.primary.calls.Load() != 1 {
+ t.Fatalf("fresh JSON status/calls = %d/%d, want %d/1", fresh.StatusCode, f.primary.calls.Load(), want)
+ }
+ }
+ f.primary.unblock()
+ f.control.unblock()
+ readAssistantJSONResult(t, control, true)
+ readAssistantJSONResult(t, primary, false)
+ if f.primary.cancelled.Load() {
+ t.Fatal("result refusal changed admitted execution lifetime")
+ }
+ })
+ }
+ }
+ }
+}
+
+func TestAssistantJSONPreserveReaders(t *testing.T) {
+ for _, kind := range []string{"execute", "kubernetes"} {
+ for _, transport := range []string{"header", "session", "proxy"} {
+ t.Run(kind+"/"+transport, func(t *testing.T) {
+ f := newAssistantJSONFixture(t, kind, []string{config.ScopeAIExecute, config.ScopeSettingsRead})
+ raw := f.token
+ if transport == "session" {
+ raw = "synthetic-assistant-json-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)
+ config.Mu.Lock()
+ if transport == "header" {
+ f.router.config.APITokens[0].Scopes = []string{config.ScopeAIExecute}
+ } else {
+ f.router.config.RemoveAPIToken(f.router.config.APITokens[0].ID)
+ }
+ config.Mu.Unlock()
+ f.primary.unblock()
+ readAssistantJSONResult(t, result, true)
+ })
+ }
+ }
+}
+
+func TestAssistantJSONPreserveRequestCancellation(t *testing.T) {
+ for _, kind := range []string{"execute", "kubernetes"} {
+ t.Run(kind, func(t *testing.T) {
+ f := newAssistantJSONFixture(t, kind, []string{config.ScopeAIExecute})
+ req := f.request(t, "primary", f.token, "header")
+ ctx, cancel := context.WithCancel(req.Context())
+ defer cancel()
+ result := make(chan assistantJSONResult, 1)
+ go func() {
+ response, err := f.server.Client().Do(req.WithContext(ctx))
+ result <- assistantJSONResult{response, err}
+ }()
+ select {
+ case <-f.primary.entered:
+ case <-time.After(5 * time.Second):
+ t.Fatal("JSON execution did not reach provider")
+ }
+ cancel()
+ select {
+ case <-f.primary.finished:
+ if !f.primary.cancelled.Load() {
+ t.Fatal("JSON execution detached from request cancellation")
+ }
+ case <-time.After(5 * time.Second):
+ t.Fatal("JSON provider did not observe request cancellation")
+ }
+ got := <-result
+ if got.response != nil {
+ got.response.Body.Close()
+ }
+ if !errors.Is(got.err, context.Canceled) {
+ t.Fatalf("cancelled JSON client error = %v", got.err)
+ }
+ })
+ }
+}
+
+func TestAssistantJSONRetainLicenseGate(t *testing.T) {
+ f := newAssistantJSONFixture(t, "kubernetes", []string{config.ScopeAIExecute})
+ f.licensed.Store(false)
+ response, err := f.server.Client().Do(f.request(t, "primary", f.token, "header"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ response.Body.Close()
+ if response.StatusCode != http.StatusPaymentRequired || f.primary.calls.Load() != 0 {
+ t.Fatalf("JSON extension licence refusal = %d; provider calls = %d", response.StatusCode, f.primary.calls.Load())
+ }
+}
+
+func assistantJSONWithdrawAfterPersistedTokenDelete(t *testing.T) {
+ for _, kind := range []string{"execute", "kubernetes"} {
+ t.Run(kind, func(t *testing.T) {
+ f := newAssistantJSONFixture(t, kind, []string{config.ScopeAIExecute})
+ primary := f.begin(t, "primary", f.token, "header")
+ control := f.begin(t, "control", assistantControlToken, "bearer")
+ id := f.router.config.APITokens[0].ID
+ req, err := http.NewRequest(http.MethodDelete, f.server.URL+"/api/security/tokens/"+id, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ req.Header.Set("X-API-Token", assistantControlToken)
+ deleted, err := f.server.Client().Do(req)
+ if err != nil {
+ t.Fatal(err)
+ }
+ deleted.Body.Close()
+ if deleted.StatusCode != http.StatusNoContent {
+ t.Fatalf("JSON persisted DELETE = %d", deleted.StatusCode)
+ }
+ records, err := f.router.persistence.LoadAPITokens()
+ if err != nil || len(records) != 1 || records[0].ID == id {
+ t.Fatalf("deleted JSON token remains durable: records=%d error=%v", len(records), err)
+ }
+ f.primary.unblock()
+ f.control.unblock()
+ readAssistantJSONResult(t, control, true)
+ readAssistantJSONResult(t, primary, false)
+ })
+ }
+}
diff --git a/internal/api/contract_test.go b/internal/api/contract_test.go
index db22df1dd2..7319730758 100644
--- a/internal/api/contract_test.go
+++ b/internal/api/contract_test.go
@@ -29008,3 +29008,9 @@ func TestContract_AssistantStreamsWithdrawAfterPersistedTokenDelete(t *testing.T
func TestContract_AssistantStreamDeadlineSurvivesAPIWrappers(t *testing.T) {
TestAssistantStreamsClearNativeServerDeadline(t)
}
+
+// A persisted token DELETE must also protect results still being computed for
+// the slow JSON routes, not just their already-admitted SSE counterparts.
+func TestContract_AssistantJSONWithdrawAfterPersistedTokenDelete(t *testing.T) {
+ assistantJSONWithdrawAfterPersistedTokenDelete(t)
+}
diff --git a/internal/api/router_routes_ai_relay.go b/internal/api/router_routes_ai_relay.go
index 53f4735723..4bd9c5afaf 100644
--- a/internal/api/router_routes_ai_relay.go
+++ b/internal/api/router_routes_ai_relay.go
@@ -48,10 +48,12 @@ func (r *Router) registerAIRelayRoutesGroup() {
r.mux.HandleFunc("/api/ai/test/{provider}", RequirePermission(r.config, r.authorizer, auth.ActionWrite, auth.ResourceSettings, RequireScope(config.ScopeSettingsWrite, r.aiSettingsHandler.HandleTestProvider)))
// AI models list - require ai:chat scope (needed to select a model for chat)
r.mux.HandleFunc("/api/ai/models", RequireAuth(r.config, RequireScope(config.ScopeAIChat, r.aiSettingsHandler.HandleListModels)))
- r.mux.HandleFunc("/api/ai/execute", RequireAdmin(r.config, RequireScope(config.ScopeAIExecute, r.aiSettingsHandler.HandleExecute)))
+ r.mux.HandleFunc("/api/ai/execute", RequireAdmin(r.config, RequireScope(config.ScopeAIExecute,
+ retainTokenResponseAuthority(r.config, config.ScopeAIExecute, true, r.aiSettingsHandler.HandleExecute))))
r.mux.HandleFunc("/api/ai/execute/stream", RequireAdmin(r.config, RequireScope(config.ScopeAIExecute,
retainTokenStreamAuthority(r.config, config.ScopeAIExecute, true, r.aiSettingsHandler.HandleExecuteStream))))
- r.mux.HandleFunc("/api/ai/kubernetes/analyze", RequireAdmin(r.config, RequireScope(config.ScopeAIExecute, r.aiAlertAnalysisEndpoints.HandleAnalyzeKubernetesCluster)))
+ r.mux.HandleFunc("/api/ai/kubernetes/analyze", RequireAdmin(r.config, RequireScope(config.ScopeAIExecute,
+ retainTokenResponseAuthority(r.config, config.ScopeAIExecute, true, r.aiAlertAnalysisEndpoints.HandleAnalyzeKubernetesCluster))))
r.mux.HandleFunc("/api/ai/investigate-alert", RequireAdmin(r.config, RequireScope(config.ScopeAIExecute,
retainTokenStreamAuthority(r.config, config.ScopeAIExecute, true, r.aiAlertAnalysisEndpoints.HandleInvestigateAlert))))
diff --git a/internal/api/token_response_authority.go b/internal/api/token_response_authority.go
new file mode 100644
index 0000000000..4dac33a43f
--- /dev/null
+++ b/internal/api/token_response_authority.go
@@ -0,0 +1,109 @@
+package api
+
+import (
+ "io"
+ "net/http"
+ "sync"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/config"
+)
+
+// retainTokenResponseAuthority is for slow, synchronous result handlers, after
+// their normal auth/admin/scope gates. A token may be withdrawn while the
+// handler waits for a provider. Keep the original work/context lifetime, but
+// recheck authority at disclosure, including headers and error responses.
+func retainTokenResponseAuthority(cfg *config.Config, scope string, instanceAdmin bool, next http.HandlerFunc) http.HandlerFunc {
+ return func(w http.ResponseWriter, r *http.Request) {
+ revalidate := tokenStreamSnapshotRevalidator(cfg, r, scope)
+ if revalidate == nil {
+ // No new authentication policy for session/proxy requests.
+ next(w, r)
+ return
+ }
+ allowed := func() bool {
+ current, ok := revalidate()
+ return ok && (!instanceAdmin || tokenActsForInstance(current))
+ }
+ if !allowed() {
+ http.Error(w, "Authentication required", http.StatusUnauthorized)
+ return
+ }
+ writer := &tokenResponseWriter{writer: w, header: w.Header().Clone(), allowed: allowed}
+ defer writer.close()
+ next(writer, r)
+ // A bodyless handler must not implicitly return 200 after withdrawal.
+ writer.WriteHeader(http.StatusOK)
+ }
+}
+
+// Only synchronous HTTP response operations are exposed: no Flusher, Hijacker,
+// ReaderFrom or Unwrap bypass. Payload bytes are never buffered. A denied first
+// write produces a generic 401, not false-success/empty JSON; after any admitted
+// response bytes, denial only stops further output, never appends an auth error.
+type tokenResponseWriter struct {
+ writer http.ResponseWriter
+ header http.Header
+ allowed func() bool
+ mu sync.Mutex
+ started bool
+ closed bool
+}
+
+func (w *tokenResponseWriter) Header() http.Header { return w.header }
+
+func (w *tokenResponseWriter) permitLocked() bool {
+ if w.closed {
+ return false
+ }
+ if !w.allowed() {
+ w.closed = true
+ if !w.started {
+ // Handler-specific headers remain private until an authorised
+ // commit; preserve only the outer middleware's existing headers.
+ http.Error(w.writer, "Authentication required", http.StatusUnauthorized)
+ }
+ return false
+ }
+ return true
+}
+
+func (w *tokenResponseWriter) commitLocked(status int) {
+ if !w.started {
+ header := w.writer.Header()
+ clear(header)
+ for key, values := range w.header {
+ header[key] = append([]string(nil), values...)
+ }
+ w.writer.WriteHeader(status)
+ // Informational headers do not commit the final response.
+ w.started = status >= 200 || status == http.StatusSwitchingProtocols
+ }
+}
+
+func (w *tokenResponseWriter) WriteHeader(status int) {
+ w.mu.Lock()
+ defer w.mu.Unlock()
+ if w.permitLocked() {
+ w.commitLocked(status)
+ }
+}
+
+func (w *tokenResponseWriter) Write(p []byte) (int, error) {
+ w.mu.Lock()
+ defer w.mu.Unlock()
+ if !w.permitLocked() {
+ return 0, io.ErrClosedPipe
+ }
+ w.commitLocked(http.StatusOK)
+ n, err := w.writer.Write(p)
+ if err != nil {
+ w.closed = true
+ }
+ return n, err
+}
+
+func (w *tokenResponseWriter) close() {
+ w.mu.Lock()
+ defer w.mu.Unlock()
+ w.closed = true
+}
diff --git a/internal/api/token_response_authority_test.go b/internal/api/token_response_authority_test.go
new file mode 100644
index 0000000000..8f9a294872
--- /dev/null
+++ b/internal/api/token_response_authority_test.go
@@ -0,0 +1,159 @@
+package api
+
+import (
+ "errors"
+ "fmt"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/config"
+)
+
+type tokenResponseStatusRecorder struct {
+ *httptest.ResponseRecorder
+ statuses []int
+}
+
+func (w *tokenResponseStatusRecorder) WriteHeader(status int) {
+ w.statuses = append(w.statuses, status)
+ w.ResponseRecorder.WriteHeader(status)
+}
+
+func TestTokenResponseWriterWithholdsWithdrawnHeadersAndBody(t *testing.T) {
+ for _, explicitStatus := range []bool{false, true} {
+ t.Run(fmt.Sprint(explicitStatus), func(t *testing.T) {
+ base := &tokenResponseStatusRecorder{ResponseRecorder: httptest.NewRecorder()}
+ base.Header().Set("X-Outer-Policy", "preserved")
+ writer := &tokenResponseWriter{writer: base, header: base.Header().Clone(), allowed: func() bool { return false }}
+ writer.Header().Set("Content-Type", "application/json")
+ writer.Header().Set("Content-Length", "9999")
+ writer.Header().Set("Content-Encoding", "synthetic")
+ writer.Header().Set("X-Private-Result", assistantPrivateResult)
+ if explicitStatus {
+ writer.WriteHeader(http.StatusOK)
+ }
+ if n, err := writer.Write([]byte(assistantPrivateResult)); n != 0 || !errors.Is(err, io.ErrClosedPipe) {
+ t.Fatalf("withdrawn write = %d, %v", n, err)
+ }
+ if base.Code != http.StatusUnauthorized || base.Body.String() != "Authentication required\n" || strings.Contains(base.Header().Get("Content-Type"), "json") {
+ t.Fatalf("withdrawn response = %d %v %s", base.Code, base.Header(), base.Body)
+ }
+ if base.Header().Get("X-Outer-Policy") != "preserved" || base.Header().Get("X-Private-Result") != "" || base.Header().Get("Content-Encoding") != "" || base.Header().Get("Content-Length") != "" {
+ t.Fatal("handler headers escaped before authorised commitment, or outer headers were lost")
+ }
+ })
+ }
+}
+
+func TestTokenResponseWriterStopsAdmittedResponseWithoutAppendingError(t *testing.T) {
+ base := httptest.NewRecorder()
+ allowed := true
+ writer := &tokenResponseWriter{writer: base, header: base.Header().Clone(), allowed: func() bool { return allowed }}
+ writer.Header().Set("Content-Type", "application/json")
+ writer.WriteHeader(http.StatusAccepted)
+ if _, err := writer.Write([]byte(`{"admitted":`)); err != nil {
+ t.Fatal(err)
+ }
+ allowed = false
+ if n, err := writer.Write([]byte(assistantPrivateResult)); n != 0 || !errors.Is(err, io.ErrClosedPipe) {
+ t.Fatalf("withdrawn later write = %d, %v", n, err)
+ }
+ // Even a regrant must not resurrect an already refused response.
+ allowed = true
+ writer.WriteHeader(http.StatusInternalServerError)
+ if _, err := writer.Write([]byte("late result")); !errors.Is(err, io.ErrClosedPipe) {
+ t.Fatal("denied response reopened")
+ }
+ if base.Code != http.StatusAccepted || base.Body.String() != `{"admitted":` || base.Header().Get("Content-Type") != "application/json" {
+ t.Fatalf("response changed after its admitted prefix: %d %s", base.Code, base.Body)
+ }
+}
+
+func TestTokenResponseAuthorityBodylessClosureAndPanic(t *testing.T) {
+ for _, stage := range []string{"authorised", "bodyless_withdrawal", "panic"} {
+ t.Run(stage, func(t *testing.T) {
+ cfg := newTestConfigWithTokens(t, newTokenRecord(t, scopedReadToken, []string{config.ScopeAIExecute}, nil))
+ var retained http.ResponseWriter
+ original := httptest.NewRequest(http.MethodPost, "/api/ai/execute", nil)
+ original.Header.Set("X-API-Token", scopedReadToken)
+ handler := retainTokenResponseAuthority(cfg, config.ScopeAIExecute, true, func(w http.ResponseWriter, req *http.Request) {
+ retained = w
+ if req != original && req.Context().Done() != original.Context().Done() {
+ t.Fatal("response policy changed request cancellation")
+ }
+ if stage == "bodyless_withdrawal" {
+ config.Mu.Lock()
+ cfg.RemoveAPIToken(cfg.APITokens[0].ID)
+ config.Mu.Unlock()
+ }
+ if stage == "panic" {
+ panic("synthetic handler failure")
+ }
+ })
+ base := &tokenResponseStatusRecorder{ResponseRecorder: httptest.NewRecorder()}
+ func() {
+ defer func() {
+ if r := recover(); (r != nil) != (stage == "panic") {
+ t.Fatalf("handler panic changed: %v", r)
+ }
+ }()
+ AuthContextMiddleware(cfg, nil, handler).ServeHTTP(base, original)
+ }()
+ if stage == "bodyless_withdrawal" && base.Code != http.StatusUnauthorized {
+ t.Fatal("bodyless handler returned false success after withdrawal")
+ }
+ if stage == "panic" && len(base.statuses) != 0 {
+ t.Fatal("guard wrote a response while a handler panic was unwinding")
+ }
+ for _, supported := range []bool{
+ implementsResponseFlusher(retained),
+ func() bool { _, ok := retained.(http.Hijacker); return ok }(),
+ func() bool { _, ok := retained.(io.ReaderFrom); return ok }(),
+ func() bool { _, ok := retained.(interface{ Unwrap() http.ResponseWriter }); return ok }(),
+ } {
+ if supported {
+ t.Fatal("synchronous result writer exposed a bypass")
+ }
+ }
+ if _, err := retained.Write([]byte("late result")); !errors.Is(err, io.ErrClosedPipe) {
+ t.Fatalf("write after handler return = %v", err)
+ }
+ })
+ }
+}
+
+func TestTokenResponseAuthorityRefusesStaleAdmissionBeforeWork(t *testing.T) {
+ cfg := newTestConfigWithTokens(t, newTokenRecord(t, scopedReadToken, []string{config.ScopeAIExecute}, nil))
+ called := false
+ guard := retainTokenResponseAuthority(cfg, config.ScopeAIExecute, true, func(http.ResponseWriter, *http.Request) { called = true })
+ between := func(w http.ResponseWriter, r *http.Request) {
+ config.Mu.Lock()
+ cfg.RemoveAPIToken(cfg.APITokens[0].ID)
+ config.Mu.Unlock()
+ guard(w, r)
+ }
+ req := httptest.NewRequest(http.MethodPost, "/api/ai/execute", nil)
+ req.Header.Set("X-API-Token", scopedReadToken)
+ base := httptest.NewRecorder()
+ AuthContextMiddleware(cfg, nil, between).ServeHTTP(base, req)
+ if called || base.Code != http.StatusUnauthorized {
+ t.Fatal("stale admission started work")
+ }
+}
+
+func implementsResponseFlusher(w http.ResponseWriter) bool { _, ok := w.(http.Flusher); return ok }
+
+func TestTokenResponseWriterKeepsTransportFailure(t *testing.T) {
+ base := &failingWriter{}
+ writer := &tokenResponseWriter{writer: base, header: base.Header().Clone(), allowed: func() bool { return true }}
+ _, first := writer.Write([]byte("admitted"))
+ if first == nil || errors.Is(first, io.ErrClosedPipe) {
+ t.Fatalf("transport error changed: %v", first)
+ }
+ if _, err := writer.Write([]byte("later")); !errors.Is(err, io.ErrClosedPipe) {
+ t.Fatal("transport failure did not close result writer")
+ }
+}