Skip to content

High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.

standardize selected API errors with RFC 7807 Problem Details

Djain9124da32086b5e9
diff --git a/PR_RFC7807_ERROR_STANDARDIZATION.md b/PR_RFC7807_ERROR_STANDARDIZATION.md
new file mode 100644
index 00000000..44554242
--- /dev/null
+++ b/PR_RFC7807_ERROR_STANDARDIZATION.md
@@ -0,0 +1,228 @@
+# PR: Standardize Selected API Errors with RFC 7807 Problem Details
+
+## Title
+Adopt RFC 7807 `application/problem+json` for streamed capability/precondition failures and websocket proxy pre-upgrade errors
+
+## Summary
+This PR introduces a shared `Problem` response helper and migrates a focused set of inconsistent plain-text API failures to RFC 7807-style Problem Details responses.
+
+The rollout is intentionally incremental to avoid breaking existing clients that still parse legacy `application/json` error payloads.
+
+## Why
+PinchTab currently returns mixed error formats across endpoints:
+- legacy JSON payloads (via `httpx.Error`/`httpx.ErrorCode`)
+- plain-text responses via `http.Error` in several API paths
+
+This inconsistency makes client-side error handling fragile and complicates schema-driven integration.
+
+## Scope
+### Added
+- Shared Problem Details type and writer helper:
+ - `internal/httpx/httpx.go`
+ - `type ProblemDetails`
+ - `func Problem(...)`
+
+### Migrated to Problem Details
+- Websocket proxy pre-upgrade failures:
+ - `internal/handlers/proxy_ws.go`
+ - `invalid_backend_target` (502)
+ - `backend_unavailable` (502)
+ - `hijack_unsupported` (500)
+
+- Screencast precondition failure:
+ - `internal/handlers/screencast.go`
+ - `tab_not_found` (404)
+
+- Network stream capability failure:
+ - `internal/handlers/network.go`
+ - `streaming_not_supported` (500)
+
+- Dashboard SSE capability failures:
+ - `internal/dashboard/dashboard.go`
+ - `streaming_not_supported` (500)
+ - `streaming_deadline_unsupported` (500)
+
+- Orchestrator logs SSE capability failures:
+ - `internal/orchestrator/handlers_instances.go`
+ - `streaming_not_supported` (500)
+ - `streaming_deadline_unsupported` (500)
+
+### Tests Added/Updated
+- `internal/httpx/httpx_test.go`
+ - `TestProblem`
+
+- `internal/handlers/network_test.go`
+ - `TestHandleNetworkStream_StreamingNotSupportedReturnsProblem`
+
+- `internal/handlers/screencast_test.go`
+ - `TestHandleScreencast_TabNotFoundReturnsProblem`
+
+- `internal/dashboard/dashboard_test.go`
+ - `TestDashboardHandleSSE_StreamingNotSupportedReturnsProblem`
+ - `TestDashboardHandleSSE_StreamingDeadlineUnsupportedReturnsProblem`
+
+- `internal/orchestrator/handlers_instances_stream_test.go`
+ - `TestHandleLogsStreamByID_StreamingNotSupportedReturnsProblem`
+ - `TestHandleLogsStreamByID_StreamingDeadlineUnsupportedReturnsProblem`
+
+### Docs
+- `docs/endpoints.md`
+ - Added an "Error Response Format" section documenting transition-state behavior:
+ - legacy `application/json`
+ - RFC 7807 `application/problem+json`
+
+## Behavior Changes
+### Before
+Some of the above failure paths returned plain-text bodies from `http.Error`.
+
+### After
+Those paths now return:
+- `Content-Type: application/problem+json`
+- RFC 7807-style payload (with project-specific extension fields):
+ - `type`
+ - `title`
+ - `status`
+ - `detail`
+ - `code`
+ - optional `retryable`
+ - optional `details`
+
+## Backward Compatibility
+- This PR does **not** replace legacy JSON errors globally.
+- Existing `httpx.Error` / `httpx.ErrorCode` responses remain unchanged for non-migrated endpoints.
+- Client integrations should parse errors based on `Content-Type` during this migration window.
+
+## Validation
+### Targeted package tests (fresh run, no cache)
+```bash
+go test -count=1 ./internal/httpx ./internal/handlers ./internal/dashboard ./internal/orchestrator
+```
+Result: pass
+
+### Additional targeted regression run
+```bash
+go test ./internal/handlers ./internal/dashboard ./internal/orchestrator
+```
+Result: pass
+
+### Full-suite note
+A previous `go test ./...` run encountered environment-level Windows Application Control execution blocks for some temp test binaries in unrelated packages. This is not caused by this PR's code changes.
+
+## Risk Assessment
+### Low-to-moderate API contract risk
+- Risk: clients hard-coded to plain-text parsing on migrated endpoints
+- Mitigation:
+ - narrow migration scope
+ - explicit docs update in `docs/endpoints.md`
+ - preserve legacy JSON paths outside migrated set
+
+### Operational risk
+- Minimal: changes are response-shape-only on failure branches and do not alter success paths.
+
+## Follow-ups (recommended)
+1. Introduce a central compatibility strategy for eventual convergence (legacy + problem details under one abstraction).
+2. Migrate additional high-traffic API error paths incrementally with endpoint-level tests.
+3. Add OpenAPI error schema annotations for `application/problem+json` where applicable.
+
+## Reviewer Checklist
+- [ ] Confirm migrated endpoints now return `application/problem+json` on targeted failures
+- [ ] Confirm problem payload includes expected `code` values
+- [ ] Confirm no regressions in stream success behavior
+- [ ] Confirm docs reflect transition-state error behavior
+
+---
+
+## GitHub PR Body (Detailed, Ready to Paste)
+
+### What changed
+This PR introduces a shared RFC 7807-style Problem Details writer and replaces selected plain-text `http.Error` responses with `application/problem+json` payloads.
+
+### Endpoint impact matrix
+
+| Area | File | Condition | Status | Code | Content-Type |
+|---|---|---|---:|---|---|
+| WS proxy | `internal/handlers/proxy_ws.go` | invalid backend target | 502 | `invalid_backend_target` | `application/problem+json` |
+| WS proxy | `internal/handlers/proxy_ws.go` | backend dial unavailable | 502 | `backend_unavailable` | `application/problem+json` |
+| WS proxy | `internal/handlers/proxy_ws.go` | hijack unsupported | 500 | `hijack_unsupported` | `application/problem+json` |
+| Screencast | `internal/handlers/screencast.go` | tab context not found | 404 | `tab_not_found` | `application/problem+json` |
+| Network SSE | `internal/handlers/network.go` | writer does not support stream flush | 500 | `streaming_not_supported` | `application/problem+json` |
+| Dashboard SSE | `internal/dashboard/dashboard.go` | writer does not support stream flush | 500 | `streaming_not_supported` | `application/problem+json` |
+| Dashboard SSE | `internal/dashboard/dashboard.go` | write deadline control unsupported | 500 | `streaming_deadline_unsupported` | `application/problem+json` |
+| Orchestrator logs SSE | `internal/orchestrator/handlers_instances.go` | writer does not support stream flush | 500 | `streaming_not_supported` | `application/problem+json` |
+| Orchestrator logs SSE | `internal/orchestrator/handlers_instances.go` | write deadline control unsupported | 500 | `streaming_deadline_unsupported` | `application/problem+json` |
+
+### Shared helper introduced
+- Added `ProblemDetails` and `Problem(...)` in `internal/httpx/httpx.go`.
+- Payload is sanitized via existing `SanitizeErrorMessage(...)` path.
+- The helper sets `Content-Type: application/problem+json` and emits:
+ - `type`
+ - `title`
+ - `status`
+ - `detail`
+ - optional extension fields `code`, `retryable`, `details`
+
+### Before/after example
+
+Before:
+```http
+HTTP/1.1 500 Internal Server Error
+Content-Type: text/plain; charset=utf-8
+
+streaming not supported
+```
+
+After:
+```http
+HTTP/1.1 500 Internal Server Error
+Content-Type: application/problem+json
+
+{
+ "type": "about:blank",
+ "title": "Internal Server Error",
+ "status": 500,
+ "detail": "streaming not supported",
+ "code": "streaming_not_supported"
+}
+```
+
+### Test coverage added
+- `internal/httpx/httpx_test.go`
+ - `TestProblem`
+- `internal/handlers/network_test.go`
+ - `TestHandleNetworkStream_StreamingNotSupportedReturnsProblem`
+- `internal/handlers/screencast_test.go`
+ - `TestHandleScreencast_TabNotFoundReturnsProblem`
+- `internal/dashboard/dashboard_test.go`
+ - `TestDashboardHandleSSE_StreamingNotSupportedReturnsProblem`
+ - `TestDashboardHandleSSE_StreamingDeadlineUnsupportedReturnsProblem`
+- `internal/orchestrator/handlers_instances_stream_test.go`
+ - `TestHandleLogsStreamByID_StreamingNotSupportedReturnsProblem`
+ - `TestHandleLogsStreamByID_StreamingDeadlineUnsupportedReturnsProblem`
+
+### Validation run commands and result
+```bash
+go test -count=1 ./internal/httpx ./internal/handlers ./internal/dashboard ./internal/orchestrator
+```
+Result: pass
+
+```bash
+go test ./internal/handlers ./internal/dashboard ./internal/orchestrator
+```
+Result: pass
+
+### Compatibility and rollout notes
+- This PR intentionally does not replace all legacy error responses.
+- Existing `httpx.Error` / `httpx.ErrorCode` behavior remains for non-migrated paths.
+- During migration, clients should parse error payloads by `Content-Type`.
+
+### Rollback strategy
+- If integration issues are found, rollback is low risk:
+ - revert handler callsites from `httpx.Problem(...)` back to previous behavior in the listed files
+ - keep helper code in `internal/httpx/httpx.go` if desired (unused helper is safe)
+
+### Risks
+- Primary risk: clients that assumed plain-text errors on these exact endpoints.
+- Mitigations:
+ - small, targeted migration surface
+ - explicit docs update in `docs/endpoints.md`
+ - direct endpoint-level tests for each migrated capability path
diff --git a/docs/endpoints.md b/docs/endpoints.md
index 3c9e9488..1089ea6f 100644
--- a/docs/endpoints.md
+++ b/docs/endpoints.md
@@ -394,3 +394,20 @@ These gates are not ordinary feature toggles. Enabling them is a documented, non
- clipboard routes -> `security.allowClipboard`
- attach routes -> `security.attach`
- screencast routes -> `security.allowScreencast`
+
+## Error Response Format
+
+PinchTab currently uses two JSON error shapes during a transition period:
+
+- Legacy JSON errors: `application/json` with fields like `error` and `code`
+- Problem Details errors: `application/problem+json` (RFC 7807 style)
+
+Problem Details is currently used for selected precondition and capability failures, including:
+
+- websocket proxy pre-upgrade backend/hijack failures
+- network stream unsupported streaming capability
+- dashboard SSE unsupported streaming capability or deadline control
+- instance logs SSE unsupported streaming capability or deadline control
+- screencast tab-not-found precondition failure
+
+Additional endpoints may be migrated over time. Clients should tolerate both error content types and branch on `Content-Type` when parsing failures.
diff --git a/internal/dashboard/dashboard.go b/internal/dashboard/dashboard.go
index f3bcd6fc..2946de4f 100644
--- a/internal/dashboard/dashboard.go
+++ b/internal/dashboard/dashboard.go
@@ -400,7 +400,7 @@ func (d *Dashboard) handleAgentSSE(w http.ResponseWriter, r *http.Request) {
func (d *Dashboard) handleSSE(w http.ResponseWriter, r *http.Request) {
flusher, ok := w.(http.Flusher)
if !ok {
- http.Error(w, "streaming not supported", http.StatusInternalServerError)
+ httpx.Problem(w, http.StatusInternalServerError, "streaming_not_supported", "streaming not supported", false, nil)
return
}
@@ -408,7 +408,7 @@ func (d *Dashboard) handleSSE(w http.ResponseWriter, r *http.Request) {
// deadline for this response so the stream is not terminated after
// http.Server.WriteTimeout elapses.
if err := http.NewResponseController(w).SetWriteDeadline(time.Time{}); err != nil {
- http.Error(w, "streaming deadline unsupported", http.StatusInternalServerError)
+ httpx.Problem(w, http.StatusInternalServerError, "streaming_deadline_unsupported", "streaming deadline unsupported", false, nil)
return
}
diff --git a/internal/dashboard/dashboard_test.go b/internal/dashboard/dashboard_test.go
index b4f88240..3275ecd9 100644
--- a/internal/dashboard/dashboard_test.go
+++ b/internal/dashboard/dashboard_test.go
@@ -18,6 +18,76 @@ func TestNewDashboard(t *testing.T) {
}
}
+type noFlusherDashboardResponseWriter struct {
+ header http.Header
+ body bytes.Buffer
+ status int
+}
+
+func (w *noFlusherDashboardResponseWriter) Header() http.Header {
+ if w.header == nil {
+ w.header = make(http.Header)
+ }
+ return w.header
+}
+
+func (w *noFlusherDashboardResponseWriter) Write(b []byte) (int, error) {
+ if w.status == 0 {
+ w.status = http.StatusOK
+ }
+ return w.body.Write(b)
+}
+
+func (w *noFlusherDashboardResponseWriter) WriteHeader(statusCode int) {
+ w.status = statusCode
+}
+
+func TestDashboardHandleSSE_StreamingNotSupportedReturnsProblem(t *testing.T) {
+ d := NewDashboard(nil)
+ req := httptest.NewRequest(http.MethodGet, "/api/events", nil)
+ w := &noFlusherDashboardResponseWriter{}
+
+ d.handleSSE(w, req)
+
+ if w.status != http.StatusInternalServerError {
+ t.Fatalf("status = %d, want %d", w.status, http.StatusInternalServerError)
+ }
+ if ct := w.Header().Get("Content-Type"); ct != "application/problem+json" {
+ t.Fatalf("content-type = %q, want application/problem+json", ct)
+ }
+
+ var payload map[string]any
+ if err := json.Unmarshal(w.body.Bytes(), &payload); err != nil {
+ t.Fatalf("decode problem payload: %v", err)
+ }
+ if payload["code"] != "streaming_not_supported" {
+ t.Fatalf("code = %v, want streaming_not_supported", payload["code"])
+ }
+}
+
+func TestDashboardHandleSSE_StreamingDeadlineUnsupportedReturnsProblem(t *testing.T) {
+ d := NewDashboard(nil)
+ req := httptest.NewRequest(http.MethodGet, "/api/events", nil)
+ w := httptest.NewRecorder()
+
+ d.handleSSE(w, req)
+
+ if w.Code != http.StatusInternalServerError {
+ t.Fatalf("status = %d, want %d", w.Code, http.StatusInternalServerError)
+ }
+ if ct := w.Header().Get("Content-Type"); ct != "application/problem+json" {
+ t.Fatalf("content-type = %q, want application/problem+json", ct)
+ }
+
+ var payload map[string]any
+ if err := json.Unmarshal(w.Body.Bytes(), &payload); err != nil {
+ t.Fatalf("decode problem payload: %v", err)
+ }
+ if payload["code"] != "streaming_deadline_unsupported" {
+ t.Fatalf("code = %v, want streaming_deadline_unsupported", payload["code"])
+ }
+}
+
func TestDashboardBroadcastSystemEvent(t *testing.T) {
d := NewDashboard(nil)
diff --git a/internal/handlers/network.go b/internal/handlers/network.go
index a1778e57..d79bb153 100644
--- a/internal/handlers/network.go
+++ b/internal/handlers/network.go
@@ -217,7 +217,7 @@ func (h *Handlers) HandleNetworkClear(w http.ResponseWriter, r *http.Request) {
func (h *Handlers) HandleNetworkStream(w http.ResponseWriter, r *http.Request) {
flusher, ok := w.(http.Flusher)
if !ok {
- http.Error(w, "streaming not supported", http.StatusInternalServerError)
+ httpx.Problem(w, http.StatusInternalServerError, "streaming_not_supported", "streaming not supported", false, nil)
return
}
diff --git a/internal/handlers/network_test.go b/internal/handlers/network_test.go
index 11ec39e2..0f3c69a3 100644
--- a/internal/handlers/network_test.go
+++ b/internal/handlers/network_test.go
@@ -1,6 +1,7 @@
package handlers
import (
+ "bytes"
"context"
"encoding/json"
"fmt"
@@ -14,6 +15,30 @@ import (
"github.com/pinchtab/pinchtab/internal/config"
)
+type noFlusherResponseWriter struct {
+ header http.Header
+ body bytes.Buffer
+ status int
+}
+
+func (w *noFlusherResponseWriter) Header() http.Header {
+ if w.header == nil {
+ w.header = make(http.Header)
+ }
+ return w.header
+}
+
+func (w *noFlusherResponseWriter) Write(b []byte) (int, error) {
+ if w.status == 0 {
+ w.status = http.StatusOK
+ }
+ return w.body.Write(b)
+}
+
+func (w *noFlusherResponseWriter) WriteHeader(statusCode int) {
+ w.status = statusCode
+}
+
// networkMockBridge extends mockBridge with a real NetworkMonitor.
type networkMockBridge struct {
mockBridge
@@ -587,6 +612,29 @@ func TestHandleNetworkStream_NilMonitor(t *testing.T) {
}
}
+func TestHandleNetworkStream_StreamingNotSupportedReturnsProblem(t *testing.T) {
+ h := newNetworkTestHandler(bridge.NewNetworkMonitor(100))
+
+ req := httptest.NewRequest("GET", "/network/stream", nil)
+ w := &noFlusherResponseWriter{}
+ h.HandleNetworkStream(w, req)
+
+ if w.status != http.StatusInternalServerError {
+ t.Fatalf("expected 500, got %d", w.status)
+ }
+ if ct := w.Header().Get("Content-Type"); ct != "application/problem+json" {
+ t.Fatalf("expected application/problem+json, got %q", ct)
+ }
+
+ var payload map[string]any
+ if err := json.Unmarshal(w.body.Bytes(), &payload); err != nil {
+ t.Fatalf("decode problem payload: %v", err)
+ }
+ if payload["code"] != "streaming_not_supported" {
+ t.Fatalf("code = %v, want streaming_not_supported", payload["code"])
+ }
+}
+
func TestHandleTabNetworkStream_MissingTabID(t *testing.T) {
nm := bridge.NewNetworkMonitor(100)
h := newNetworkTestHandler(nm)
diff --git a/internal/handlers/proxy_ws.go b/internal/handlers/proxy_ws.go
index f2d6d582..eb57d6d7 100644
--- a/internal/handlers/proxy_ws.go
+++ b/internal/handlers/proxy_ws.go
@@ -11,6 +11,7 @@ import (
"net/textproto"
"net/url"
+ "github.com/pinchtab/pinchtab/internal/httpx"
internalurls "github.com/pinchtab/pinchtab/internal/urls"
)
@@ -20,7 +21,7 @@ const proxyWSBackendAuthorizationHeader = "X-Pinchtab-Proxy-Authorization"
func ProxyWebSocket(w http.ResponseWriter, r *http.Request, targetURL string) {
parsed, err := url.Parse(targetURL)
if err != nil {
- http.Error(w, "invalid backend target", http.StatusBadGateway)
+ httpx.Problem(w, http.StatusBadGateway, "invalid_backend_target", "invalid backend target", false, nil)
slog.Error("ws proxy: invalid target", "target", internalurls.RedactForLog(targetURL), "err", err)
return
}
@@ -39,7 +40,7 @@ func ProxyWebSocket(w http.ResponseWriter, r *http.Request, targetURL string) {
backend, err = net.Dial("tcp", host)
}
if err != nil {
- http.Error(w, "backend unavailable", http.StatusBadGateway)
+ httpx.Problem(w, http.StatusBadGateway, "backend_unavailable", "backend unavailable", true, nil)
slog.Error("ws proxy: backend dial failed", "target", host, "err", err)
return
}
@@ -47,7 +48,7 @@ func ProxyWebSocket(w http.ResponseWriter, r *http.Request, targetURL string) {
hj, ok := w.(http.Hijacker)
if !ok {
- http.Error(w, "server doesn't support hijacking", http.StatusInternalServerError)
+ httpx.Problem(w, http.StatusInternalServerError, "hijack_unsupported", "server does not support hijacking", false, nil)
return
}
client, _, err := hj.Hijack()
diff --git a/internal/handlers/screencast.go b/internal/handlers/screencast.go
index c5b2bb56..4922aa75 100644
--- a/internal/handlers/screencast.go
+++ b/internal/handlers/screencast.go
@@ -54,7 +54,7 @@ func (h *Handlers) HandleScreencast(w http.ResponseWriter, r *http.Request) {
ctx, resolvedTabID, err := h.tabContext(r, tabID)
if err != nil {
- http.Error(w, "tab not found", 404)
+ httpx.Problem(w, http.StatusNotFound, "tab_not_found", "tab not found", false, nil)
return
}
if _, ok := h.enforceCurrentTabDomainPolicy(w, r, ctx, resolvedTabID); !ok {
diff --git a/internal/handlers/screencast_test.go b/internal/handlers/screencast_test.go
index 654cb871..9ea83cb3 100644
--- a/internal/handlers/screencast_test.go
+++ b/internal/handlers/screencast_test.go
@@ -2,6 +2,7 @@ package handlers
import (
"context"
+ "encoding/json"
"net/http"
"net/http/httptest"
"testing"
@@ -84,6 +85,30 @@ func TestHandleScreencast_Disabled(t *testing.T) {
}
}
+func TestHandleScreencast_TabNotFoundReturnsProblem(t *testing.T) {
+ cfg := &config.RuntimeConfig{AllowScreencast: true}
+ h := New(&mockBridge{failTab: true}, cfg, nil, nil, nil)
+ req := httptest.NewRequest("GET", "/screencast?tabId=missing", nil)
+ w := httptest.NewRecorder()
+
+ h.HandleScreencast(w, req)
+
+ if w.Code != http.StatusNotFound {
+ t.Fatalf("expected 404, got %d", w.Code)
+ }
+ if ct := w.Header().Get("Content-Type"); ct != "application/problem+json" {
+ t.Fatalf("expected application/problem+json, got %q", ct)
+ }
+
+ var payload map[string]any
+ if err := json.Unmarshal(w.Body.Bytes(), &payload); err != nil {
+ t.Fatalf("decode problem payload: %v", err)
+ }
+ if payload["code"] != "tab_not_found" {
+ t.Fatalf("code = %v, want tab_not_found", payload["code"])
+ }
+}
+
func TestCreateScreencastExecutionContext_UsesTopFrameNamedWorld(t *testing.T) {
origGetFrameTree := getScreencastFrameTree
origCreateWorld := createScreencastIsolatedWorld
diff --git a/internal/httpx/httpx.go b/internal/httpx/httpx.go
index 7bbc6f95..46033de1 100644
--- a/internal/httpx/httpx.go
+++ b/internal/httpx/httpx.go
@@ -18,6 +18,17 @@ const (
maxErrorMessageBytes = 1024
)
+type ProblemDetails struct {
+ Type string `json:"type"`
+ Title string `json:"title"`
+ Status int `json:"status"`
+ Detail string `json:"detail,omitempty"`
+ Instance string `json:"instance,omitempty"`
+ Code string `json:"code,omitempty"`
+ Retryable bool `json:"retryable,omitempty"`
+ Details map[string]any `json:"details,omitempty"`
+}
+
func JSON(w http.ResponseWriter, code int, data any) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(code)
@@ -51,6 +62,31 @@ func ErrorCode(w http.ResponseWriter, status int, code, message string, retryabl
JSON(w, status, payload)
}
+func Problem(w http.ResponseWriter, status int, code, detail string, retryable bool, details map[string]any) {
+ title := http.StatusText(status)
+ if title == "" {
+ title = "Error"
+ }
+
+ payload := ProblemDetails{
+ Type: "about:blank",
+ Title: title,
+ Status: status,
+ Detail: SanitizeErrorMessage(detail),
+ Code: code,
+ Details: details,
+ }
+ if retryable {
+ payload.Retryable = true
+ }
+
+ w.Header().Set("Content-Type", "application/problem+json")
+ w.WriteHeader(status)
+ if err := json.NewEncoder(w).Encode(payload); err != nil {
+ slog.Error("problem encode", "err", err)
+ }
+}
+
func DecodeJSONBody(w http.ResponseWriter, r *http.Request, maxBytes int64, dst any) error {
if maxBytes <= 0 {
maxBytes = DefaultMaxJSONBodyBytes
diff --git a/internal/httpx/httpx_test.go b/internal/httpx/httpx_test.go
index af9c949e..9f0c61fe 100644
--- a/internal/httpx/httpx_test.go
+++ b/internal/httpx/httpx_test.go
@@ -1,6 +1,7 @@
package httpx
import (
+ "encoding/json"
"fmt"
"net/http"
"net/http/httptest"
@@ -90,3 +91,42 @@ func TestStatusForJSONDecodeError(t *testing.T) {
t.Fatalf("StatusForJSONDecodeError(max bytes) = %d, want %d", got, http.StatusRequestEntityTooLarge)
}
}
+
+func TestProblem(t *testing.T) {
+ w := httptest.NewRecorder()
+ Problem(w, http.StatusBadGateway, "backend_unavailable", "backend \x1b[31m unavailable", true, map[string]any{"service": "bridge"})
+
+ if w.Code != http.StatusBadGateway {
+ t.Fatalf("expected status 502, got %d", w.Code)
+ }
+ if ct := w.Header().Get("Content-Type"); ct != "application/problem+json" {
+ t.Fatalf("expected content-type application/problem+json, got %q", ct)
+ }
+
+ var got ProblemDetails
+ if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil {
+ t.Fatalf("failed to decode problem payload: %v", err)
+ }
+
+ if got.Type != "about:blank" {
+ t.Fatalf("Type = %q, want about:blank", got.Type)
+ }
+ if got.Title != http.StatusText(http.StatusBadGateway) {
+ t.Fatalf("Title = %q, want %q", got.Title, http.StatusText(http.StatusBadGateway))
+ }
+ if got.Status != http.StatusBadGateway {
+ t.Fatalf("Status = %d, want %d", got.Status, http.StatusBadGateway)
+ }
+ if strings.Contains(got.Detail, "\x1b") {
+ t.Fatalf("expected sanitized detail, got %q", got.Detail)
+ }
+ if got.Code != "backend_unavailable" {
+ t.Fatalf("Code = %q, want backend_unavailable", got.Code)
+ }
+ if !got.Retryable {
+ t.Fatalf("Retryable = false, want true")
+ }
+ if got.Details["service"] != "bridge" {
+ t.Fatalf("details.service = %v, want bridge", got.Details["service"])
+ }
+}
diff --git a/internal/orchestrator/handlers_instances.go b/internal/orchestrator/handlers_instances.go
index 9e3d613f..958afb84 100644
--- a/internal/orchestrator/handlers_instances.go
+++ b/internal/orchestrator/handlers_instances.go
@@ -158,12 +158,12 @@ func (o *Orchestrator) handleLogsByID(w http.ResponseWriter, r *http.Request) {
func (o *Orchestrator) handleLogsStreamByID(w http.ResponseWriter, r *http.Request) {
flusher, ok := w.(http.Flusher)
if !ok {
- http.Error(w, "streaming not supported", http.StatusInternalServerError)
+ httpx.Problem(w, http.StatusInternalServerError, "streaming_not_supported", "streaming not supported", false, nil)
return
}
if err := http.NewResponseController(w).SetWriteDeadline(time.Time{}); err != nil {
- http.Error(w, "streaming deadline unsupported", http.StatusInternalServerError)
+ httpx.Problem(w, http.StatusInternalServerError, "streaming_deadline_unsupported", "streaming deadline unsupported", false, nil)
return
}
diff --git a/internal/orchestrator/handlers_instances_stream_test.go b/internal/orchestrator/handlers_instances_stream_test.go
new file mode 100644
index 00000000..3f6df9b2
--- /dev/null
+++ b/internal/orchestrator/handlers_instances_stream_test.go
@@ -0,0 +1,79 @@
+package orchestrator
+
+import (
+ "bytes"
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+)
+
+type noFlusherOrchestratorResponseWriter struct {
+ header http.Header
+ body bytes.Buffer
+ status int
+}
+
+func (w *noFlusherOrchestratorResponseWriter) Header() http.Header {
+ if w.header == nil {
+ w.header = make(http.Header)
+ }
+ return w.header
+}
+
+func (w *noFlusherOrchestratorResponseWriter) Write(b []byte) (int, error) {
+ if w.status == 0 {
+ w.status = http.StatusOK
+ }
+ return w.body.Write(b)
+}
+
+func (w *noFlusherOrchestratorResponseWriter) WriteHeader(statusCode int) {
+ w.status = statusCode
+}
+
+func TestHandleLogsStreamByID_StreamingNotSupportedReturnsProblem(t *testing.T) {
+ o := NewOrchestratorWithRunner(t.TempDir(), &mockRunner{portAvail: true})
+ req := httptest.NewRequest(http.MethodGet, "/instances/inst-1/logs/stream", nil)
+ w := &noFlusherOrchestratorResponseWriter{}
+
+ o.handleLogsStreamByID(w, req)
+
+ if w.status != http.StatusInternalServerError {
+ t.Fatalf("status = %d, want %d", w.status, http.StatusInternalServerError)
+ }
+ if ct := w.Header().Get("Content-Type"); ct != "application/problem+json" {
+ t.Fatalf("content-type = %q, want application/problem+json", ct)
+ }
+
+ var payload map[string]any
+ if err := json.Unmarshal(w.body.Bytes(), &payload); err != nil {
+ t.Fatalf("decode problem payload: %v", err)
+ }
+ if payload["code"] != "streaming_not_supported" {
+ t.Fatalf("code = %v, want streaming_not_supported", payload["code"])
+ }
+}
+
+func TestHandleLogsStreamByID_StreamingDeadlineUnsupportedReturnsProblem(t *testing.T) {
+ o := NewOrchestratorWithRunner(t.TempDir(), &mockRunner{portAvail: true})
+ req := httptest.NewRequest(http.MethodGet, "/instances/inst-1/logs/stream", nil)
+ w := httptest.NewRecorder()
+
+ o.handleLogsStreamByID(w, req)
+
+ if w.Code != http.StatusInternalServerError {
+ t.Fatalf("status = %d, want %d", w.Code, http.StatusInternalServerError)
+ }
+ if ct := w.Header().Get("Content-Type"); ct != "application/problem+json" {
+ t.Fatalf("content-type = %q, want application/problem+json", ct)
+ }
+
+ var payload map[string]any
+ if err := json.Unmarshal(w.Body.Bytes(), &payload); err != nil {
+ t.Fatalf("decode problem payload: %v", err)
+ }
+ if payload["code"] != "streaming_deadline_unsupported" {
+ t.Fatalf("code = %v, want streaming_deadline_unsupported", payload["code"])
+ }
+}