interactive: a refusal before the upgrade keeps its status and body (rootfs plan 6 task 13)
x/net's client turns any answer other than 101 into ErrBadStatus and drops the response. DialFrame now reads it again from the handshake recorder's copy (x/net drains the body through it) and returns a *RefusedError with the status, the headers and up to MaxRefusalBody of the body, still matching websocket.ErrBadStatus. The CLI prints the console's own sentence from the one dial, with no second request.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
internal/interactive/frames.go+42 −0internal/interactive/frames_test.go+95 −0
Intent
<task-notification> <task-id>ae96b54b0de505047</task-id> <tool-use-id>toolu_01MgL73EcYJYNfWADDqKkGC5</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/ba9fa944-a429-4788-9b3c-f2b2f42617f3/tasks/ae96b54b0de505047.output</output-file> <status>completed</status> <summary>Agent "Plan 6 Task 12 fix round 2" finished</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note> <result>Both census tidy-ups are in commit `14939489`. It sits on top of `a3e1028d` and is not pushed. New overlay seal: `3b892312ed4cc4067fc57e30cdd53398a6e9654428b76f3003ab8b8b55ccc98b` `TestPlan9B8RecordWriteCensus` and `TestPlan14RootReadCensus` pass, and `make census-card` is clean.</result> <usage><subagent_tokens>157353</subagent_tokens><tool_uses>66</tool_uses><duration_ms>876444</duration_ms></usage> </task-notification>
<task-notification> <task-id>bod1tzaoi</task-id> <tool-use-id>toolu_013TUnTXXAstqakU2HCKH7Zc</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/ba9fa944-a429-4788-9b3c-f2b2f42617f3/tasks/bod1tzaoi.output</output-file> <status>completed</status> <summary>Background command "Watch for the Task 12 fix commit as a fallback notice" completed (exit code 0)</summary> </task-notification>
<task-notification> <task-id>baekk8c0f</task-id> <tool-use-id>toolu_01YVvtV4j4cDwqXtHjtKVTi4</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/ba9fa944-a429-4788-9b3c-f2b2f42617f3/tasks/baekk8c0f.output</output-file> <status>completed</status> <summary>Background command "Run Astra census check of Task 12" completed (exit code 0)</summary> </task-notification>
<cross-session-message from="uds:/run/user/1001/cc-socks/1370079.sock" from-name="platform-54" from-mode="bypass"> From platform-54: the r10r drill is done. The dev console was down about 58 s in total (20:07:43Z, then 20:08:04-20:09:01Z) and back by 20:09:16Z. The hostname history is active again with box-2 included, and its floor is now v0.33.0, so no console older than v0.33.0 may run on dev. box-2 is terminated and detached, and r10r is back to box-1 only. shop, railsdemo and cable are now LABELLED box-1, following their bindings; nothing moved, and shop/railsdemo returned 200 on all 155 probes. One thing to expect: box-1's local copies of shop and railsdemo have no assignment marker yet, so on their next restart box-1 sets each copy aside and restores from the fleet bucket. The replicas are there; just expect a slower first wake. The drill's throwaway app drillcheck is in the Trash. </cross-session-message>
diff --git a/internal/interactive/frames.go b/internal/interactive/frames.go| index 4c38fb6b4..50362f926 100644 |
| --- a/internal/interactive/frames.go |
| +++ b/internal/interactive/frames.go |
| @@ -243,6 +243,12 @@ func DialFrame(ctx context.Context, url, origin string, header http.Header, maxF |
| raw.Close() |
| return nil, ctx.Err() |
| } |
| + if errors.Is(err, websocket.ErrBadStatus) { |
| + rec.stopped = true |
| + raw.Close() |
| + err = readRefusal(rec) |
| + return nil, err |
| + } |
| if err == nil { |
| err = raw.SetDeadline(time.Time{}) |
| } |
| @@ -258,6 +264,42 @@ func DialFrame(ctx context.Context, url, origin string, header http.Header, maxF |
| return ws, nil |
| } |
| +// RefusedError is DialFrame's error for a server that answered the upgrade |
| +// request with an HTTP response other than 101: its status, its headers |
| +// and up to MaxRefusalBody bytes of its body, so a caller can show the |
| +// door's own refusal without asking again. It matches |
| +// websocket.ErrBadStatus. |
| +type RefusedError struct { |
| + Status int |
| + Header http.Header |
| + Body []byte |
| +} |
| + |
| +func (e *RefusedError) Error() string { |
| + return fmt.Sprintf("interactive: the server refused the upgrade with status %d", e.Status) |
| +} |
| + |
| +func (e *RefusedError) Unwrap() error { return websocket.ErrBadStatus } |
| + |
| +// MaxRefusalBody bounds the body a RefusedError keeps. |
| +const MaxRefusalBody = 64 << 10 |
| + |
| +// readRefusal reads again the refusal x/net turned into ErrBadStatus. x/net |
| +// read the response's head through rec and then drained its body (closing |
| +// it reads it to the end), so rec's copy is the whole response unless it |
| +// passed maxHandshake; a copy cut there gives a body cut short, which is |
| +// kept as it came. A body that never ends holds x/net's drain until the |
| +// dial's context ends, as any stalled handshake does. |
| +func readRefusal(rec *handshakeRecorder) error { |
| + resp, err := http.ReadResponse(bufio.NewReader(bytes.NewReader(rec.buf.Bytes())), nil) |
| + if err != nil { |
| + return websocket.ErrBadStatus |
| + } |
| + defer resp.Body.Close() |
| + body, _ := io.ReadAll(io.LimitReader(resp.Body, MaxRefusalBody)) |
| + return &RefusedError{Status: resp.StatusCode, Header: resp.Header, Body: body} |
| +} |
| + |
| // dialTransport opens the TCP or TLS connection cfg.Location names, as |
| // x/net's own dial does. |
| func dialTransport(ctx context.Context, cfg *websocket.Config) (net.Conn, error) { |
diff --git a/internal/interactive/frames_test.go b/internal/interactive/frames_test.go| index 4bab1c415..14423b690 100644 |
| --- a/internal/interactive/frames_test.go |
| +++ b/internal/interactive/frames_test.go |
| @@ -502,3 +502,98 @@ func TestDialRequiresTheNegotiatedSubprotocol(t *testing.T) { |
| } |
| ws.Close() |
| } |
| + |
| +// TestDialRefusalCarriesStatusAndBody: a door that answers the upgrade with |
| +// an HTTP refusal is a *RefusedError holding its status, its headers and |
| +// its body, whole, including a body that arrives after the headers in a |
| +// write of its own. It still matches websocket.ErrBadStatus. |
| +func TestDialRefusalCarriesStatusAndBody(t *testing.T) { |
| + const body = `{"error":"interactive sessions are off for shop. an owner can turn them on with carlos apps set shop --interactive on"}` |
| + big := `{"error":"` + string(bytes.Repeat([]byte("x"), 20<<10)) + `"}` |
| + for name, tc := range map[string]struct { |
| + status int |
| + body string |
| + split bool |
| + }{ |
| + "json 409 in one write": {http.StatusConflict, body, false}, |
| + "json 429 after the headers": {http.StatusTooManyRequests, body, true}, |
| + "plain 404": {http.StatusNotFound, "404 page not found\n", false}, |
| + "a 20 KiB body after a flush": {http.StatusServiceUnavailable, big, true}, |
| + } { |
| + t.Run(name, func(t *testing.T) { |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + w.Header().Set("Retry-After", "7") |
| + w.Header().Set("Content-Length", fmt.Sprint(len(tc.body))) |
| + w.WriteHeader(tc.status) |
| + if tc.split { |
| + w.(http.Flusher).Flush() |
| + time.Sleep(50 * time.Millisecond) |
| + } |
| + io.WriteString(w, tc.body) |
| + })) |
| + t.Cleanup(srv.Close) |
| + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) |
| + defer cancel() |
| + ws, err := Dial(ctx, wsURL(t, srv), testOrigin, nil) |
| + if err == nil { |
| + ws.Close() |
| + t.Fatal("Dial succeeded against a refusal") |
| + } |
| + var re *RefusedError |
| + if !errors.As(err, &re) { |
| + t.Fatalf("Dial error = %T %v, want a *RefusedError", err, err) |
| + } |
| + if re.Status != tc.status || string(re.Body) != tc.body || re.Header.Get("Retry-After") != "7" { |
| + t.Fatalf("RefusedError = %d, %q (%d bytes), Retry-After %q; want %d and the body whole", |
| + re.Status, re.Body[:min(len(re.Body), 80)], len(re.Body), re.Header.Get("Retry-After"), tc.status) |
| + } |
| + if !errors.Is(err, websocket.ErrBadStatus) { |
| + t.Errorf("errors.Is(err, websocket.ErrBadStatus) = false") |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// TestDialRefusalBodyIsBounded: a refusal body longer than the handshake |
| +// copy is cut short, never kept past MaxRefusalBody, and a body that never |
| +// finishes ends with the dial's context. |
| +func TestDialRefusalBodyIsBounded(t *testing.T) { |
| + release := make(chan struct{}) |
| + t.Cleanup(func() { close(release) }) |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + w.Header().Set("Content-Length", fmt.Sprint(2*MaxRefusalBody)) |
| + w.WriteHeader(http.StatusConflict) |
| + w.Write(bytes.Repeat([]byte("y"), 2*MaxRefusalBody)) |
| + })) |
| + t.Cleanup(srv.Close) |
| + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) |
| + defer cancel() |
| + _, err := Dial(ctx, wsURL(t, srv), testOrigin, nil) |
| + var re *RefusedError |
| + if !errors.As(err, &re) || re.Status != http.StatusConflict || len(re.Body) == 0 || len(re.Body) > MaxRefusalBody || |
| + len(bytes.Trim(re.Body, "y")) != 0 { |
| + t.Fatalf("Dial = %v (%T); want a 409 RefusedError with at most %d bytes of the body", err, err, MaxRefusalBody) |
| + } |
| + |
| + // A body that stalls ends with the context. |
| + stall := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + w.Header().Set("Content-Length", "100") |
| + w.WriteHeader(http.StatusConflict) |
| + io.WriteString(w, `{"error":`) |
| + w.(http.Flusher).Flush() |
| + select { |
| + case <-release: |
| + case <-r.Context().Done(): |
| + } |
| + })) |
| + t.Cleanup(stall.Close) |
| + ctx2, cancel2 := context.WithTimeout(context.Background(), 300*time.Millisecond) |
| + defer cancel2() |
| + start := time.Now() |
| + if _, err = Dial(ctx2, wsURL(t, stall), testOrigin, nil); err == nil { |
| + t.Fatal("stalled Dial succeeded") |
| + } |
| + if d := time.Since(start); d > 2*time.Second { |
| + t.Fatalf("stalled Dial took %s", d) |
| + } |
| +} |