diff --git a/.golangci.yml b/.golangci.yml index 67eea2bd..7a53464a 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -83,6 +83,11 @@ linters: - linters: - containedctx path: connecthttp/interceptor_ext_test.go + # Stands in for the window where the deadline has passed but the + # context's timer has not yet set Err. + - linters: + - containedctx + path: internal/wstransport/close_test.go # blockUntilResponseReady returns the shared response, whose body is # closed once by CloseRead rather than at each call site. - linters: @@ -174,6 +179,17 @@ linters: - forbidigo path: internal/memhttp text: use of `log.(New|Logger|Lshortfile)` forbidden by pattern .* + # The WebSocket session re-panics after closing the hijacked connection, + # so the panic still reaches whatever would have recovered it. + - linters: + - forbidigo + path: internal/wstransport/session.go + text: use of `panic` forbidden by pattern .* + # A panicking handler is the subject of the test, and it silences + # net/http's expected panic trace with its own logger. + - linters: + - forbidigo + path: internal/wstransport/lifecycle_ext_test.go # The migration CLI writes its report to stdout. - linters: - forbidigo diff --git a/cmd/connect-go-v2-migrate/testdata/build/go.mod.txt b/cmd/connect-go-v2-migrate/testdata/build/go.mod.txt index aeb82008..a41ed9af 100644 --- a/cmd/connect-go-v2-migrate/testdata/build/go.mod.txt +++ b/cmd/connect-go-v2-migrate/testdata/build/go.mod.txt @@ -8,4 +8,6 @@ require ( google.golang.org/protobuf v1.36.11 ) +require github.com/coder/websocket v1.8.15 // indirect + replace connectrpc.com/connect/v2 => REPLACE_DIR diff --git a/cmd/connect-go-v2-migrate/testdata/build/go.sum b/cmd/connect-go-v2-migrate/testdata/build/go.sum index 1ac57354..ebd349eb 100644 --- a/cmd/connect-go-v2-migrate/testdata/build/go.sum +++ b/cmd/connect-go-v2-migrate/testdata/build/go.sum @@ -1,5 +1,7 @@ connectrpc.com/connect v1.20.0 h1:6TNDAB+WeNd2uolWNlYczB5E0KNNaVMNUEx8JEUsPmQ= connectrpc.com/connect v1.20.0/go.mod h1:A2ygJrukXwWy32vkCAAHNVguZrqZ+jeZ9rGRnGR4dN4= +github.com/coder/websocket v1.8.15 h1:6B2JPeOGlpff2Uz6vOEH1Vzpi0iUz20A+lPVhPHtNUA= +github.com/coder/websocket v1.8.15/go.mod h1:NX3SzP+inril6yawo5CQXx8+fk145lPDC6pumgx0mVg= github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE= diff --git a/connecthttp/connecthttp.go b/connecthttp/connecthttp.go index e8fb4a03..78ac9b03 100644 --- a/connecthttp/connecthttp.go +++ b/connecthttp/connecthttp.go @@ -32,6 +32,7 @@ import ( "connectrpc.com/connect/v2" "connectrpc.com/connect/v2/connectgzip" "connectrpc.com/connect/v2/connectproto" + "connectrpc.com/connect/v2/internal/wstransport" ) // HTTPClient is the HTTP client surface the transport drives. The @@ -44,6 +45,7 @@ type HTTPClient interface { // ClientInfo is the HTTP metadata for a client RPC, carried on // [connect.CallInfo.TransportInfo]. Its methods are safe for concurrent use. // They return zero values until the request is sent or the response arrives. +// For an RPC over WebSocket, the request and response are the handshake's. type ClientInfo struct { request atomic.Pointer[http.Request] response atomic.Pointer[http.Response] @@ -129,7 +131,8 @@ func (c *ClientInfo) loadResponse() *http.Response { } // ServerInfo is the HTTP metadata for a server RPC, carried on -// [connect.CallInfo.TransportInfo]. +// [connect.CallInfo.TransportInfo]. For an RPC over WebSocket, the request is +// the handshake's. type ServerInfo struct { request *http.Request } @@ -216,12 +219,30 @@ func NewTransport(httpClient HTTPClient, baseURL string, options ...Option) conn for _, opt := range options { opt.apply(&opts) } - return &transport{ + httpTransport := &transport{ httpClient: httpClient, baseURLPtr: parsed, baseURLErr: err, options: opts, } + if opts.websocketSelector == nil && len(opts.conditional) == 0 { + return httpTransport + } + websocketClient := websocketHTTPClient(httpClient) + base := newWebSocketRoute(&opts, websocketClient, baseURL) + if base.err != nil { + // The URL or codec set is unusable for WebSocket. Reporting it from + // every RPC beats returning an HTTP-only transport that silently + // ignores the selector the caller supplied. + return &brokenTransport{err: base.err} + } + return &hybridTransport{ + fallback: httpTransport, + options: &opts, + httpClient: websocketClient, + baseURL: baseURL, + base: base, + } } // defaultOptions returns the options with the defaults every transport and @@ -254,6 +275,14 @@ func defaultCompressors() []connect.Compressor { // plus a per-service catch-all that routes RPC requests for unknown methods // through [connect.Server.Call]. Non-RPC requests get a plain 404, and // requests for unknown services fall through to mux. +// +// Every route also serves Connect over WebSocket unless [WithoutWebSocket] is +// given, because which transport carries an RPC is the client's choice. A +// WebSocket client sends its request headers in a message after the +// handshake, so a header that this deployment's own proxies set, and that a +// client must not be able to forge, belongs on the deny list that +// [WithWebSocketInfrastructureHeaders] configures; identity headers added by +// an authenticating proxy are the usual example. func Mount(mux ServeMux, server *connect.Server, options ...Option) { opts := defaultOptions() for _, opt := range options { @@ -265,14 +294,16 @@ func Mount(mux ServeMux, server *connect.Server, options ...Option) { if spec.StreamType == connect.StreamTypeBidi { procedureHandler = requireHTTP2(procedureHandler) } - mux.Handle(spec.Procedure, procedureHandler) + mux.Handle(spec.Procedure, withWebSocket( + server, procedureHandler, opts.forSpec(spec), wstransport.WithProcedure(spec.Procedure), + )) // "/package.Service/Method" -> subtree pattern "/package.Service/". if idx := strings.LastIndexByte(spec.Procedure, '/'); idx > 0 { services[spec.Procedure[:idx+1]] = struct{}{} } } for service := range services { - mux.Handle(service, newUnknownMethodHandler(server, &opts)) + mux.Handle(service, withWebSocket(server, newUnknownMethodHandler(server, &opts), &opts)) } } @@ -401,24 +432,24 @@ func (t *transport) newClientState(spec connect.Spec) *clientState { if !slices.ContainsFunc(opts.compressors, func(c connect.Compressor) bool { return c.Name() == opts.sendCompressor }) { - return &clientState{err: connect.Errorf(connect.CodeUnknown, "unknown compression %q", opts.sendCompressor)} + return &clientState{opts: opts, err: connect.Errorf(connect.CodeUnknown, "unknown compression %q", opts.sendCompressor)} } } sendCodecName := opts.getSendCodecName() if sendCodecName == "" { - return &clientState{err: connect.Errorf(connect.CodeUnknown, "no codecs registered")} + return &clientState{opts: opts, err: connect.Errorf(connect.CodeUnknown, "no codecs registered")} } if !slices.ContainsFunc(opts.codecs, func(c connect.Codec) bool { return c.Name() == sendCodecName }) { - return &clientState{err: connect.Errorf(connect.CodeUnknown, "unknown codec %q", sendCodecName)} + return &clientState{opts: opts, err: connect.Errorf(connect.CodeUnknown, "unknown codec %q", sendCodecName)} } if t.baseURLErr != nil { - return &clientState{err: connect.Errorf(connect.CodeUnavailable, "invalid base URL: %v", t.baseURLErr)} + return &clientState{opts: opts, err: connect.Errorf(connect.CodeUnavailable, "invalid base URL: %v", t.baseURLErr)} } client, err := t.newProtocolClient(spec, opts) if err != nil { - return &clientState{err: err} + return &clientState{opts: opts, err: err} } return &clientState{opts: opts, sendCodecName: sendCodecName, client: client} } @@ -444,6 +475,14 @@ type options struct { // Server-only ([NewTransport] ignores these). requireConnectProtocolHeader bool + websocketDisabled bool + + // Client-only, and the switch that turns WebSocket on there: a nil + // selector means every RPC goes over HTTP. + websocketSelector Selector + websocketFallbackOnErr bool + websocketClientOptions []wstransport.ClientOption + websocketServerOptions []wstransport.ServerOption // conditional holds per-procedure option functions registered with // WithConditionalOptions. They are evaluated against each spec by forSpec. @@ -484,6 +523,8 @@ func (o *options) clone() *options { opts := *o opts.codecs = slices.Clone(o.codecs) opts.compressors = slices.Clone(o.compressors) + opts.websocketClientOptions = slices.Clone(o.websocketClientOptions) + opts.websocketServerOptions = slices.Clone(o.websocketServerOptions) opts.conditional = nil return &opts } diff --git a/connecthttp/connecthttp_test.go b/connecthttp/connecthttp_test.go index 6386f7d6..1c70e619 100644 --- a/connecthttp/connecthttp_test.go +++ b/connecthttp/connecthttp_test.go @@ -28,7 +28,7 @@ import ( func TestTransportCachesClientState(t *testing.T) { t.Parallel() var calls atomic.Int32 - transport, ok := NewTransport( + transport := httpTransport(t, NewTransport( http.DefaultClient, "http://localhost", WithConditionalOptions(func(spec connect.Spec) []Option { @@ -38,8 +38,7 @@ func TestTransportCachesClientState(t *testing.T) { } return nil }), - ).(*transport) - assert.True(t, ok) + )) // The cache keys by procedure. This Schema would panic as a map key. specA := connect.Spec{ StreamType: connect.StreamTypeUnary, @@ -74,8 +73,7 @@ func TestTransportCachesClientState(t *testing.T) { func TestTransportCachesClientStateErrors(t *testing.T) { t.Parallel() - transport, ok := NewTransport(http.DefaultClient, "http://[bad").(*transport) - assert.True(t, ok) + transport := httpTransport(t, NewTransport(http.DefaultClient, "http://[bad")) spec := connect.Spec{StreamType: connect.StreamTypeUnary, Procedure: "/svc/A"} _, err := transport.NewClientStream(t.Context(), spec) assert.Equal(t, connect.CodeOf(err), connect.CodeUnavailable) @@ -83,8 +81,7 @@ func TestTransportCachesClientStateErrors(t *testing.T) { } func TestTransportCachedClientStateNoAllocs(t *testing.T) { //nolint:paralleltest // AllocsPerRun can't run in parallel - transport, ok := NewTransport(http.DefaultClient, "http://localhost").(*transport) - assert.True(t, ok) + transport := httpTransport(t, NewTransport(http.DefaultClient, "http://localhost")) spec := connect.Spec{StreamType: connect.StreamTypeUnary, Procedure: "/svc/A"} transport.clientStateForSpec(spec) allocs := testing.AllocsPerRun(100, func() { @@ -92,3 +89,18 @@ func TestTransportCachedClientStateNoAllocs(t *testing.T) { //nolint:paralleltes }) assert.Equal(t, allocs, 0) } + +// httpTransport returns the Connect-over-HTTP transport that client uses. +// Conditional options make NewTransport return a hybridTransport, since they +// may select WebSocket for some procedures. +func httpTransport(tb testing.TB, client connect.Transport) *transport { + tb.Helper() + if hybrid, ok := client.(*hybridTransport); ok { + client = hybrid.fallback + } + httpClient, ok := client.(*transport) + if !ok { + tb.Fatalf("NewTransport returned %T, not a Connect-over-HTTP transport", client) + } + return httpClient +} diff --git a/connecthttp/error.go b/connecthttp/error.go index 7f177cba..c457ae34 100644 --- a/connecthttp/error.go +++ b/connecthttp/error.go @@ -21,12 +21,12 @@ import ( "io" "net/http" "net/url" - "os" "strings" "syscall" "time" "connectrpc.com/connect/v2" + "connectrpc.com/connect/v2/internal/connecterr" ) const commonErrorsURL = "https://connectrpc.com/docs/go/common-errors" @@ -80,10 +80,10 @@ func IsNotModifiedError(err error) bool { return errors.Is(err, errNotModified) } -// asError unwraps any error and looks for a non-nil *connect.Error. +// asError unwraps any error and looks for a non-nil *connect.Error. See +// [connecterr.AsError]. func asError(err error) (*connect.Error, bool) { - connectErr, ok := errors.AsType[*connect.Error](err) - return connectErr, ok && connectErr != nil // Protect against typed nils (*connect.Error)(nil). + return connecterr.AsError(err) } // wrapIfUncoded ensures that all errors are wrapped. It leaves already-wrapped @@ -102,53 +102,16 @@ func wrapIfUncoded(err error) error { } // scrubHandlerError converts a handler's returned error into the wire -// verdict: only a locally authored *connect.Error keeps its code, message, -// and details. Remote errors become [connect.CodeInternal] and other errors -// [connect.CodeUnknown] (context errors keep their codes), all with no -// message. The original error stays attached as a local-only cause. +// verdict. See [connecterr.ScrubHandlerError]. func scrubHandlerError(err error) error { - if err == nil { - return nil - } - if cerr, ok := asError(err); ok { - if cerr.IsRemote() { - return connect.NewError(connect.CodeInternal, "").WithCause(err) - } - return err - } - code := connect.CodeUnknown - switch { - case errors.Is(err, context.Canceled): - code = connect.CodeCanceled - case errors.Is(err, context.DeadlineExceeded), errors.Is(err, os.ErrDeadlineExceeded): - code = connect.CodeDeadlineExceeded - } - return connect.NewError(code, "").WithCause(err) + return connecterr.ScrubHandlerError(err) } // wrapIfContextError applies connect.CodeCanceled or connect.CodeDeadlineExceeded to Go's // context.Canceled and context.DeadlineExceeded errors, but only if they // haven't already been wrapped. func wrapIfContextError(err error) error { - if err == nil { - return nil - } - if _, ok := asError(err); ok { - return err - } - if errors.Is(err, context.Canceled) { - return connect.NewError(connect.CodeCanceled, err.Error()).WithCause(err) - } - if errors.Is(err, context.DeadlineExceeded) { - return connect.NewError(connect.CodeDeadlineExceeded, err.Error()).WithCause(err) - } - // Ick, some dial errors can be returned as os.ErrDeadlineExceeded - // instead of context.DeadlineExceeded :( - // https://github.com/golang/go/issues/64449 - if errors.Is(err, os.ErrDeadlineExceeded) { - return connect.NewError(connect.CodeDeadlineExceeded, err.Error()).WithCause(err) - } - return err + return connecterr.WrapIfContextError(err) } // isClientDisconnected reports whether err is a connection failure caused by @@ -187,20 +150,7 @@ func wrapIfClientTransportError(err error) error { // wrapIfContextDone wraps errors with connect.CodeCanceled or connect.CodeDeadlineExceeded // if the context is done. It leaves already-wrapped errors unchanged. func wrapIfContextDone(ctx context.Context, err error) error { - if err == nil { - return nil - } - err = wrapIfContextError(err) - if _, ok := asError(err); ok { - return err - } - ctxErr := ctx.Err() - if errors.Is(ctxErr, context.Canceled) { - return connect.NewError(connect.CodeCanceled, err.Error()).WithCause(err) - } else if errors.Is(ctxErr, context.DeadlineExceeded) { - return connect.NewError(connect.CodeDeadlineExceeded, err.Error()).WithCause(err) - } - return err + return connecterr.WrapIfContextDone(ctx, err) } // wrapIfLikelyH2CNotConfiguredError adds a wrapping error that has a message @@ -322,18 +272,7 @@ func wrapIfRSTError(ctx context.Context, err error) error { } // wrapIfMaxBytesError wraps errors returned reading from a http.MaxBytesHandler -// whose limit has been exceeded. +// whose limit has been exceeded. See [connecterr.WrapIfMaxBytesError]. func wrapIfMaxBytesError(err error, tmpl string, args ...any) error { - if err == nil { - return nil - } - if _, ok := asError(err); ok { - return err - } - maxBytesErr, ok := errors.AsType[*http.MaxBytesError](err) - if !ok { - return err - } - prefix := fmt.Sprintf(tmpl, args...) - return connect.Errorf(connect.CodeResourceExhausted, "%s: exceeded %d byte http.MaxBytesReader limit", prefix, maxBytesErr.Limit) + return connecterr.WrapIfMaxBytesError(err, tmpl, args...) } diff --git a/connecthttp/option.go b/connecthttp/option.go index 82731273..45e9a8ac 100644 --- a/connecthttp/option.go +++ b/connecthttp/option.go @@ -18,6 +18,7 @@ import ( "slices" "connectrpc.com/connect/v2" + "connectrpc.com/connect/v2/internal/wstransport" ) // Option configures [NewTransport], [Mount], and [NewErrorWriter]. A single @@ -283,3 +284,73 @@ func (o conditionalOption) apply(opts *options) { } opts.conditional = append(opts.conditional, o.conditional) } + +// WithoutWebSocket stops [Mount] registering the WebSocket transport, leaving +// each route serving plain HTTP only. +// +// Mount registers both by default because which transport carries an RPC is +// the client's choice: a server that offered only HTTP would reject a client +// that chose to upgrade. Turn it off when nothing will upgrade, or when a +// WebSocket endpoint is something the deployment does not want exposed. +// +// [NewTransport] ignores this option; a client enables WebSocket by supplying +// a selector to [WithWebSocket]. +func WithoutWebSocket() Option { + return withoutWebSocketOption{} +} + +type withoutWebSocketOption struct{} + +func (withoutWebSocketOption) apply(o *options) { o.websocketDisabled = true } + +// WithWebSocket routes the RPCs selector picks over WebSocket, and everything +// else over HTTP. Without it a transport is HTTP-only. +// +// [SelectStreaming] is the usual choice: streaming RPCs upgrade, unary RPCs +// stay on HTTP, where they cost no handshake. [SelectAll] and [SelectBidi] are +// the broader and narrower alternatives. +// +// One set of options configures both wires, so a codec or a size limit set +// here applies whichever way an RPC travels. [Mount] ignores this option; +// a server accepts whatever a client chooses. +func WithWebSocket(selector Selector) Option { + return webSocketOption{selector: selector} +} + +type webSocketOption struct{ selector Selector } + +func (o webSocketOption) apply(opts *options) { opts.websocketSelector = o.selector } + +// WithFallbackOnUpgradeError retries an RPC over HTTP when the WebSocket +// handshake fails, so a client reaches a server that does not speak WebSocket +// at all — an older deployment, or a proxy that refuses upgrades. +// +// It costs a round trip on every stream: the handshake has to complete before +// [connect.Client] returns a stream, because once it has, an upgrade failure +// surfaces from Send and there is no longer anywhere to fall back to. Without +// this option the handshake happens lazily, on first use. +// +// A canceled or expired call is not retried: that is the caller's doing, not a +// peer that lacks WebSocket support. +func WithFallbackOnUpgradeError() Option { + return fallbackOnUpgradeErrorOption{} +} + +type fallbackOnUpgradeErrorOption struct{} + +func (fallbackOnUpgradeErrorOption) apply(o *options) { o.websocketFallbackOnErr = true } + +// webSocketServerOptionsOption carries server-side settings to the internal +// transport. The named WithWebSocket* options are the public way in. +type webSocketServerOptionsOption []wstransport.ServerOption + +func (o webSocketServerOptionsOption) apply(opts *options) { + opts.websocketServerOptions = append(opts.websocketServerOptions, o...) +} + +// webSocketClientOptionsOption is the client-side twin. +type webSocketClientOptionsOption []wstransport.ClientOption + +func (o webSocketClientOptionsOption) apply(opts *options) { + opts.websocketClientOptions = append(opts.websocketClientOptions, o...) +} diff --git a/connecthttp/protocol_connect.go b/connecthttp/protocol_connect.go index c4850dd4..57509500 100644 --- a/connecthttp/protocol_connect.go +++ b/connecthttp/protocol_connect.go @@ -31,8 +31,8 @@ import ( "time" "connectrpc.com/connect/v2" - "connectrpc.com/connect/v2/connectproto" "connectrpc.com/connect/v2/internal/bufferpool" + "connectrpc.com/connect/v2/internal/connectwire" ) const ( @@ -593,7 +593,7 @@ func (cc *connectUnaryClientConn) unmarshalResponseError(response *http.Response // code not set? default to one implied by HTTP status wireErr.Code = httpToCode(response.StatusCode) } - return wireErr.asError() + return wireErr.AsError() } type connectStreamingClientConn struct { @@ -954,7 +954,7 @@ func (u *connectStreamingUnmarshaler) Unmarshal(message any) *connect.Error { } } u.trailer = end.Trailer - u.endStreamErr = end.Error.asError() + u.endStreamErr = end.Error.AsError() return errSpecialEnvelope } @@ -1220,115 +1220,17 @@ func (u *connectUnaryUnmarshaler) UnmarshalFunc(message any, unmarshal func(cont return nil } -// connectWireDetail adapts a [connect.ErrorDetail] to the Connect protocol's -// error detail object. -type connectWireDetail connect.ErrorDetail - -func (d *connectWireDetail) MarshalJSON() ([]byte, error) { - wire := struct { - Type string `json:"type"` - Value string `json:"value"` - Debug json.RawMessage `json:"debug,omitempty"` - }{ - Type: d.Type, - Value: base64.RawStdEncoding.EncodeToString(d.Value), - } - if json.Valid(d.Debug) { - wire.Debug = json.RawMessage(d.Debug) - } else if msg, err := connectproto.ErrorDetailToAny((*connect.ErrorDetail)(d)).UnmarshalNew(); err == nil { - var buffer bytes.Buffer - var codec connectproto.JSONCodec - if err := codec.MarshalWrite(context.Background(), &buffer, msg); err == nil { - wire.Debug = buffer.Bytes() - } - } - return json.Marshal(wire) -} - -func (d *connectWireDetail) UnmarshalJSON(data []byte) error { - var wire struct { - Type string `json:"type"` - Value string `json:"value"` - Debug json.RawMessage `json:"debug,omitempty"` - } - if err := json.Unmarshal(data, &wire); err != nil { - return err - } - value, err := connect.DecodeBinaryHeader(wire.Value) - if err != nil { - return fmt.Errorf("decode base64: %w", err) - } - *d = connectWireDetail{ - Type: wire.Type, - Value: value, - Debug: wire.Debug, - } - return nil -} - -type connectWireError struct { - Code connect.Code `json:"code"` - Message string `json:"message,omitempty"` - Details []*connectWireDetail `json:"details,omitempty"` -} +// The Connect protocol's wire error and end-of-stream envelope live in +// internal/connectwire so that non-HTTP transports can share them. These +// aliases keep the in-package spellings. +type ( + connectWireDetail = connectwire.WireDetail + connectWireError = connectwire.WireError + connectEndStreamMessage = connectwire.EndStreamMessage +) func newConnectWireError(err error) *connectWireError { - wire := &connectWireError{ - Code: connect.CodeUnknown, - Message: err.Error(), - } - if connectErr, ok := asError(err); ok { - wire.Code = connectErr.Code() - wire.Message = connectErr.Message() - if details := connectErr.Details(); len(details) > 0 { - wire.Details = make([]*connectWireDetail, len(details)) - for i, detail := range details { - wire.Details[i] = (*connectWireDetail)(detail) - } - } - } - return wire -} - -func (e *connectWireError) asError() *connect.Error { - if e == nil { - return nil - } - if e.Code < connect.CodeCanceled || e.Code > connect.CodeUnauthenticated { - e.Code = connect.CodeUnknown - } - err := connect.NewError(e.Code, e.Message).WithRemote() - if len(e.Details) > 0 { - for _, detail := range e.Details { - err = err.WithDetail((*connect.ErrorDetail)(detail)) - } - } - return err -} - -func (e *connectWireError) UnmarshalJSON(data []byte) error { - // We want to be lenient if the JSON has an unrecognized or invalid code. - // So if that occurs, we leave the code unset but can still de-serialize - // the other fields from the input JSON. - var wireError struct { - Code string `json:"code"` - Message string `json:"message"` - Details []*connectWireDetail `json:"details"` - } - err := json.Unmarshal(data, &wireError) - if err != nil { - return err - } - e.Message = wireError.Message - e.Details = wireError.Details - // This will leave e.Code unset if we can't unmarshal the given string. - _ = e.Code.UnmarshalText([]byte(wireError.Code)) - return nil -} - -type connectEndStreamMessage struct { - Error *connectWireError `json:"error,omitempty"` - Trailer http.Header `json:"metadata,omitempty"` + return connectwire.NewWireError(err) } func connectCodeToHTTP(code connect.Code) int { diff --git a/connecthttp/websocket.go b/connecthttp/websocket.go new file mode 100644 index 00000000..c0190397 --- /dev/null +++ b/connecthttp/websocket.go @@ -0,0 +1,257 @@ +// Copyright 2021-2026 The Connect Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// WebSocket composition. This package owns the entry points — Mount and +// NewTransport — and internal/wstransport owns the protocol, so the dependency +// runs one way and a caller configures both wires from one set of options. + +package connecthttp + +import ( + "context" + "errors" + "net/http" + "net/url" + "sync" + + "connectrpc.com/connect/v2" + "connectrpc.com/connect/v2/internal/wstransport" +) + +// hybridTransport opens each stream on WebSocket or fallback according to the +// [Selector] in effect for its spec. +type hybridTransport struct { + fallback *transport + options *options + httpClient *http.Client + baseURL string + // base serves every spec when no conditional options are registered. + base *webSocketRoute + // routes caches each procedure's route when conditional options are + // registered, since they may configure WebSocket differently per spec. + routes sync.Map // procedure string -> *webSocketRoute +} + +// webSocketRoute is the WebSocket configuration in effect for a spec. +type webSocketRoute struct { + // transport is nil when selector is. + transport connect.Transport + err error + selector Selector + fallbackOnError bool +} + +func newWebSocketRoute(opts *options, httpClient *http.Client, baseURL string) *webSocketRoute { + route := &webSocketRoute{ + selector: opts.websocketSelector, + fallbackOnError: opts.websocketFallbackOnErr, + } + if route.selector == nil { + return route + } + clientOptions := opts.websocketClientOpts(httpClient) + if opts.websocketFallbackOnErr { + clientOptions = append(clientOptions, wstransport.WithEagerDial()) + } + route.transport, route.err = wstransport.NewTransport(baseURL, clientOptions...) + return route +} + +func (t *hybridTransport) route(spec connect.Spec) *webSocketRoute { + if len(t.options.conditional) == 0 { + return t.base + } + if cached, ok := t.routes.Load(spec.Procedure); ok { + if route, ok := cached.(*webSocketRoute); ok { + return route + } + } + route := newWebSocketRoute(t.fallback.clientStateForSpec(spec).opts, t.httpClient, t.baseURL) + actual, _ := t.routes.LoadOrStore(spec.Procedure, route) + if stored, ok := actual.(*webSocketRoute); ok { + return stored + } + return route +} + +func (t *hybridTransport) NewClientStream(ctx context.Context, spec connect.Spec) (connect.ClientStream, error) { + route := t.route(spec) + if route.selector == nil || !route.selector(spec) { + return t.fallback.NewClientStream(ctx, spec) + } + if route.err != nil { + return nil, route.err + } + ctx, info := ensureClientCallInfo(ctx) + // websocketHTTPClient records the handshake here. + info.TransportInfo = &ClientInfo{} + stream, err := route.transport.NewClientStream(ctx, spec) + if err == nil { + return stream, nil + } + // A canceled call is the caller's doing, not a peer that lacks WebSocket + // support, so retrying on the fallback would only obscure the cause. + if !route.fallbackOnError || ctx.Err() != nil { + return nil, err + } + stream, fallbackErr := t.fallback.NewClientStream(ctx, spec) + if fallbackErr != nil { + return nil, errors.Join(err, fallbackErr) + } + // The WebSocket error is dropped here. A fallback transport is typically + // lazy, so it usually succeeds at this point and fails later from Send, by + // which time only its own error is left to report. + return stream, nil +} + +// websocketServerOpts translates the settings both wires share, so a codec or +// limit set once applies whichever way an RPC travels. Options with no +// WebSocket meaning are not forwarded; WebSocket-only settings come from the +// WithWebSocket* options. +func (o *options) websocketServerOpts() []wstransport.ServerOption { + forwarded := []wstransport.ServerOption{ + wstransport.WithCodecs(o.codecs...), + wstransport.WithReadMaxBytes(o.readMaxBytes), + wstransport.WithSendMaxBytes(o.sendMaxBytes), + } + // Only when set. Zero means "no minimum" to both packages, but their + // defaults differ — this one leaves it unset, and forwarding that would + // silently turn off the WebSocket half's own 512-byte floor and compress + // every 3-byte control message. + if o.compressMinBytes > 0 { + forwarded = append(forwarded, wstransport.WithCompressMinBytes(o.compressMinBytes)) + } + return append(forwarded, o.websocketServerOptions...) +} + +// websocketClientOpts is the client-side twin. +func (o *options) websocketClientOpts(httpClient *http.Client) []wstransport.ClientOption { + forwarded := []wstransport.ClientOption{ + wstransport.WithCodecs(o.codecs...), + wstransport.WithReadMaxBytes(o.readMaxBytes), + wstransport.WithSendMaxBytes(o.sendMaxBytes), + } + if o.compressMinBytes > 0 { + forwarded = append(forwarded, wstransport.WithCompressMinBytes(o.compressMinBytes)) + } + // The effective name, not the option: without WithSendCodec the first + // registered codec is the default, as it is over HTTP. + if name := o.getSendCodecName(); name != "" { + forwarded = append(forwarded, wstransport.WithSendCodec(name)) + } + forwarded = append(forwarded, wstransport.WithHTTPClient(httpClient)) + return append(forwarded, o.websocketClientOptions...) +} + +// ensureClientCallInfo returns the CallInfo on ctx, attaching a new one if +// there is none, as the HTTP transport does. +func ensureClientCallInfo(ctx context.Context) (context.Context, *connect.CallInfo) { + if info, ok := connect.CallInfoForClientContext(ctx); ok { + return ctx, info + } + return connect.NewClientContext(ctx) +} + +// websocketHTTPClient returns the [*http.Client] the handshake goes through, +// so that it travels the same client as HTTP RPCs do. A client that is not an +// *http.Client is adapted rather than replaced, and either way the handshake is +// recorded on the call's [ClientInfo]. +func websocketHTTPClient(httpClient HTTPClient) *http.Client { + standard, isStandard := httpClient.(*http.Client) + if httpClient == nil || (isStandard && standard == nil) { + standard, isStandard = http.DefaultClient, true + } + if !isStandard { + return &http.Client{Transport: &handshakeRecorder{roundTrip: func(request *http.Request) (*http.Response, error) { + response, err := httpClient.Do(request) + // The adapter's own http.Client wraps the error again. + if urlErr, ok := errors.AsType[*url.Error](err); ok { + return response, urlErr.Err + } + return response, err + }}} + } + recording := *standard + next := standard.Transport + if next == nil { + next = http.DefaultTransport + } + recording.Transport = &handshakeRecorder{roundTrip: next.RoundTrip} + return &recording +} + +// handshakeRecorder stores a WebSocket handshake on the [ClientInfo] of the +// call that made it, as the HTTP transport stores each request. +type handshakeRecorder struct { + roundTrip func(*http.Request) (*http.Response, error) +} + +func (r *handshakeRecorder) RoundTrip(request *http.Request) (*http.Response, error) { + response, err := r.roundTrip(request) + if info, ok := ClientInfoForContext(request.Context()); ok { + info.request.Store(request) + if response != nil { + info.response.Store(response) + } + } + return response, err +} + +// withWebSocket serves handler's route over WebSocket too, configured by opts, +// so that per-procedure options reach both transports. A route whose options +// disable WebSocket refuses upgrades instead. +// +// Both transports share every path, because which one carries an RPC is the +// client's choice: a server serving only HTTP would reject a client that +// upgraded. +func withWebSocket( + server *connect.Server, + handler http.Handler, + opts *options, + extra ...wstransport.ServerOption, +) http.Handler { + if opts.websocketDisabled { + return refuseUpgrade(handler) + } + serverOptions := append(opts.websocketServerOpts(), extra...) + serverOptions = append(serverOptions, wstransport.WithTransportInfo(func(request *http.Request) any { + return &ServerInfo{request: request} + })) + return wstransport.Upgrade(server, handler, serverOptions...) +} + +// refuseUpgrade answers a WebSocket upgrade with 400, as an endpoint +// restricted to Connect over HTTP must (RFC 008 §4.2). Left to the HTTP +// handler, the handshake's GET would get an unrelated status. +func refuseUpgrade(handler http.Handler) http.Handler { + return http.HandlerFunc(func(responseWriter http.ResponseWriter, request *http.Request) { + if wstransport.IsUpgrade(request) { + http.Error( + responseWriter, + "this endpoint serves Connect over HTTP only, not over WebSocket", + http.StatusBadRequest, + ) + return + } + handler.ServeHTTP(responseWriter, request) + }) +} + +// brokenTransport reports a configuration error from every RPC, which is where +// a caller will actually see it. +type brokenTransport struct{ err error } + +func (t *brokenTransport) NewClientStream(context.Context, connect.Spec) (connect.ClientStream, error) { + return nil, t.err +} diff --git a/connecthttp/websocket_options.go b/connecthttp/websocket_options.go new file mode 100644 index 00000000..ef95fddc --- /dev/null +++ b/connecthttp/websocket_options.go @@ -0,0 +1,224 @@ +// Copyright 2021-2026 The Connect Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// The WebSocket transport's public surface. The implementation is in +// internal/wstransport: Connect is protobuf-first, so which wire carries an +// RPC is an implementation detail, and a caller configures it through the +// options here rather than assembling a transport by hand. + +package connecthttp + +import ( + "log/slog" + "net/http" + "time" + + "connectrpc.com/connect/v2" + "connectrpc.com/connect/v2/internal/wstransport" +) + +// Selector reports whether spec's RPC should travel over WebSocket. A false +// result leaves it on HTTP. See [WithWebSocket]. +type Selector func(spec connect.Spec) bool + +// SelectStreaming routes every streaming RPC over WebSocket and leaves unary +// RPCs on HTTP, where a handshake would buy nothing. It is the usual choice. +func SelectStreaming(spec connect.Spec) bool { + return spec.StreamType != connect.StreamTypeUnary +} + +// SelectBidi routes only bidirectional RPCs over WebSocket. Server-streaming +// works over plain HTTP, so this is the narrower alternative to +// [SelectStreaming]. +func SelectBidi(spec connect.Spec) bool { + return spec.StreamType == connect.StreamTypeBidi +} + +// SelectAll routes every RPC over WebSocket, including unary ones. +func SelectAll(connect.Spec) bool { + return true +} + +// ProtocolNameConnectWebSocket is what [connect.CallInfo].Protocol reports for +// an RPC carried over WebSocket, as connect.ProtocolNameConnect is for one +// over HTTP. +const ProtocolNameConnectWebSocket = wstransport.ProtocolConnectWebSocket + +// IsWebSocketUpgrade reports whether request is a WebSocket handshake, so +// middleware can tell the two transports apart before either handler runs. +func IsWebSocketUpgrade(request *http.Request) bool { + return wstransport.IsUpgrade(request) +} + +// TextCodec is an optional interface for a [connect.Codec] whose encoding is +// UTF-8 text. Only the WebSocket transport consults it: a codec registered +// with [WithCodecs] travels as the subprotocol connectrpc.1+ and its name, and +// its bodies go in text frames if it implements TextCodec and IsText returns +// true, or binary frames otherwise. The proto and json codecs are binary and +// text by definition. A codec name must be a lower-case HTTP token to be +// offered over WebSocket. +type TextCodec = wstransport.TextCodec + +// ProtocolFault classifies a peer's framing mistake, so a monitor can tell a +// client that consistently sends unknown markers from one that mismatches a +// frame type once. The Connect code alone cannot: every framing fault is +// Internal, separable only by matching message strings. +type ProtocolFault = wstransport.ProtocolFault + +// The framing mistakes a peer can make. See [ProtocolFault]. +const ( + // FaultMarker is a message that is empty, has an unknown marker or one for + // the other direction, or breaks the rules for C. + FaultMarker = wstransport.FaultMarker + // FaultFrameType is a frame whose type does not match its payload. + FaultFrameType = wstransport.FaultFrameType + // FaultSizeLimit is a message past the configured read limit. + FaultSizeLimit = wstransport.FaultSizeLimit + // FaultMetadata is a malformed, missing, or repeated metadata message. + FaultMetadata = wstransport.FaultMetadata + // FaultMessageEncoding is a payload the negotiated codec cannot decode. + FaultMessageEncoding = wstransport.FaultMessageEncoding + // FaultTextEncoding is a text message that is not valid UTF-8. + FaultTextEncoding = wstransport.FaultTextEncoding +) + +// WithWebSocketCheckOrigin replaces the default same-origin check on the +// handshake. Returning false refuses it with 403. +// +// The default matters: a browser attaches the user's cookies to a WebSocket +// handshake and performs no CORS preflight, so an allow-all policy lets any +// page open an authenticated stream. A handshake carrying no Origin header is +// not from a browser and is allowed either way. +func WithWebSocketCheckOrigin(check func(*http.Request) bool) Option { + return webSocketServerOptionsOption{wstransport.WithCheckOrigin(check)} +} + +// WithWebSocketMaxTimeout bounds every WebSocket RPC, whatever deadline the +// client asked for. The effective deadline is the shorter of the two. +// +// The bound is what makes waiting for a client's opening message safe: without +// it, a peer that upgrades and then goes silent holds the connection forever. +// The default is an hour — long-lived streams are the reason this transport +// exists, and a short default would sever the subscriptions it carries. +func WithWebSocketMaxTimeout(timeout time.Duration) Option { + return webSocketServerOptionsOption{wstransport.WithMaxTimeout(timeout)} +} + +// WithWebSocketHandshakeTimeout bounds the handshake. The connection outlives +// it; only the upgrade is bounded. A server applies it to the wait for the +// client's opening metadata message, so that a client which upgrades and then +// sends nothing is hung up on. The default is 10 seconds; zero means no bound. +func WithWebSocketHandshakeTimeout(timeout time.Duration) Option { + return webSocketBothOption{wstransport.WithHandshakeTimeout(timeout)} +} + +// WithWebSocketInfrastructureHeaders replaces the request headers a client may +// not set in its metadata message because this deployment's own infrastructure +// sets them. A trailing "*" matches any suffix. +// +// The default is Forwarded, X-Forwarded-*, and X-Real-IP. It does not affect +// the names the Fetch standard forbids as request headers, or the ones the +// protocol controls; those are reserved whatever a deployment configures. +func WithWebSocketInfrastructureHeaders(names ...string) Option { + return webSocketServerOptionsOption{wstransport.WithInfrastructureHeaders(names...)} +} + +// WithWebSocketLogger replaces [slog.Default] for WebSocket session errors. +func WithWebSocketLogger(logger *slog.Logger) Option { + return webSocketServerOptionsOption{wstransport.WithLogger(logger)} +} + +// ServerProtocolErrorHandler observes a client's framing mistake. It cannot +// change the outcome: the error reaches the peer and the handler either way, +// so this is for logging, metrics, and rate limiting. +type ServerProtocolErrorHandler func(peerAddr string, request *http.Request, fault ProtocolFault, err *connect.Error) + +// WithWebSocketServerProtocolErrorHandler registers a handler for framing +// faults a client commits. +// +// A framing fault is reported to the peer and is a successful outcome from the +// session's point of view, so it never reaches [WithWebSocketLogger]. This is +// the hook that says which kind of mistake it was and who made it. +func WithWebSocketServerProtocolErrorHandler(handler ServerProtocolErrorHandler) Option { + if handler == nil { + return webSocketServerOptionsOption(nil) + } + return webSocketServerOptionsOption{wstransport.WithServerProtocolErrorHandler( + func(info wstransport.SessionInfo, fault wstransport.ProtocolFault, err *connect.Error) { + handler(info.Request.RemoteAddr, info.Request, fault, err) + }, + )} +} + +// ClientProtocolErrorHandler observes a server's framing mistake, the mirror +// of [ServerProtocolErrorHandler]. +type ClientProtocolErrorHandler func(spec connect.Spec, fault ProtocolFault, err *connect.Error) + +// WithWebSocketClientProtocolErrorHandler registers a handler for framing +// faults a server commits, which is the only way a client learns that a server +// misframed rather than simply failed. +func WithWebSocketClientProtocolErrorHandler(handler ClientProtocolErrorHandler) Option { + if handler == nil { + return webSocketClientOptionsOption(nil) + } + return webSocketClientOptionsOption{wstransport.WithClientProtocolErrorHandler( + func(spec connect.Spec, fault wstransport.ProtocolFault, err *connect.Error) { + handler(spec, fault, err) + }, + )} +} + +// WithoutWebSocketCompression disables permessage-deflate on the handshake, +// leaving WebSocket messages uncompressed. It has no effect on the HTTP half, +// which negotiates a Connect content encoding instead. +// +// Compression is on by default, with no-context-takeover imposed in both +// directions. Turn it off when the payloads are already compressed, or when +// the CPU matters more than the bytes. +func WithoutWebSocketCompression() Option { + return webSocketBothOption{wstransport.WithoutCompression()} +} + +// WithWebSocketKeepAlive sets how often each side sends a WebSocket Ping, so +// that a proxy which drops idle connections sees traffic on a quiet stream. +// The interval must be clearly shorter than the idle timeout of every proxy +// and load balancer between client and server; an interval equal to it races +// the proxy's timer. Common idle timeouts are 60 to 100 seconds. The default is +// 30 seconds; zero or less turns keep-alive off. +// +// A peer heard nothing from for the keep-alive timeout, neither a message nor +// a Pong, is hung up on with close code 1011 from a server or 3102 from a +// client, and the RPC fails. See [WithWebSocketKeepAliveTimeout]. +func WithWebSocketKeepAlive(interval time.Duration) Option { + return webSocketBothOption{wstransport.WithKeepAlive(interval)} +} + +// WithWebSocketKeepAliveTimeout sets how long each side lets a peer send +// nothing before hanging up on it. The default is five minutes, and anything +// shorter than two keep-alive intervals is raised to that. +// +// The timeout includes a peer whose application has stopped taking messages, +// since it then stops reading its connection and answering Pings too. +func WithWebSocketKeepAliveTimeout(timeout time.Duration) Option { + return webSocketBothOption{wstransport.WithKeepAliveTimeout(timeout)} +} + +// webSocketBothOption carries a setting that applies to whichever side is +// being configured. +type webSocketBothOption [1]wstransport.Option + +func (o webSocketBothOption) apply(opts *options) { + opts.websocketServerOptions = append(opts.websocketServerOptions, o[0]) + opts.websocketClientOptions = append(opts.websocketClientOptions, o[0]) +} diff --git a/connecthttp/websocket_test.go b/connecthttp/websocket_test.go new file mode 100644 index 00000000..c745db48 --- /dev/null +++ b/connecthttp/websocket_test.go @@ -0,0 +1,87 @@ +// Copyright 2021-2026 The Connect Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package connecthttp + +import ( + "net/http" + "slices" + "sync" + "sync/atomic" + "testing" + "time" + + "connectrpc.com/connect/v2" + "connectrpc.com/connect/v2/internal/assert" +) + +// Options appended for one spec must not land in another's, which they would +// if two clones shared a backing array with room to grow. +func TestForSpecClonesWebSocketOptions(t *testing.T) { + t.Parallel() + opts := defaultOptions() + WithWebSocketKeepAlive(time.Second).apply(&opts) + opts.websocketServerOptions = slices.Grow(opts.websocketServerOptions, 4) + opts.websocketClientOptions = slices.Grow(opts.websocketClientOptions, 4) + WithConditionalOptions(func(connect.Spec) []Option { + return []Option{WithWebSocketKeepAliveTimeout(time.Minute)} + }).apply(&opts) + + first := opts.forSpec(connect.Spec{Procedure: "/a.A/One"}) + second := opts.forSpec(connect.Spec{Procedure: "/a.A/Two"}) + assert.Equal(t, len(opts.websocketServerOptions), 1) + assert.Equal(t, len(first.websocketServerOptions), 2) + assert.True(t, &first.websocketServerOptions[1] != &second.websocketServerOptions[1]) + assert.True(t, &first.websocketClientOptions[1] != &second.websocketClientOptions[1]) +} + +// The hybrid transport's WebSocket routes and its fallback's client state are +// both per procedure. They share one resolution of the conditional options, +// so the callback runs once per procedure even when first calls race. +func TestHybridTransportResolvesConditionalOptionsOnce(t *testing.T) { + t.Parallel() + var calls atomic.Int32 + hybrid, ok := NewTransport( + http.DefaultClient, + "http://localhost", + WithConditionalOptions(func(connect.Spec) []Option { + calls.Add(1) + return []Option{WithWebSocket(SelectStreaming)} + }), + ).(*hybridTransport) + if !ok { + t.Fatal("conditional options must produce a hybridTransport") + } + spec := connect.Spec{StreamType: connect.StreamTypeUnary, Procedure: "/svc/A"} + + start := make(chan struct{}) + var group sync.WaitGroup + for range 8 { + group.Go(func() { + <-start + hybrid.route(spec) + }) + group.Go(func() { + <-start + hybrid.fallback.clientStateForSpec(spec) + }) + } + close(start) + group.Wait() + // A unary call routes to the fallback, through both caches. + _, err := hybrid.NewClientStream(t.Context(), spec) + assert.Nil(t, err) + assert.Equal(t, calls.Load(), int32(1)) + assert.True(t, hybrid.route(spec).selector != nil) +} diff --git a/go.mod b/go.mod index 5b6a69f1..0c2f6443 100644 --- a/go.mod +++ b/go.mod @@ -6,3 +6,5 @@ require ( github.com/google/go-cmp v0.7.0 google.golang.org/protobuf v1.36.11 ) + +require github.com/coder/websocket v1.8.15 diff --git a/go.sum b/go.sum index 296be183..79d667ee 100644 --- a/go.sum +++ b/go.sum @@ -1,3 +1,5 @@ +github.com/coder/websocket v1.8.15 h1:6B2JPeOGlpff2Uz6vOEH1Vzpi0iUz20A+lPVhPHtNUA= +github.com/coder/websocket v1.8.15/go.mod h1:NX3SzP+inril6yawo5CQXx8+fk145lPDC6pumgx0mVg= github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE= diff --git a/internal/conformance/go.mod b/internal/conformance/go.mod index 9b8d0878..e1c31d29 100644 --- a/internal/conformance/go.mod +++ b/internal/conformance/go.mod @@ -13,6 +13,7 @@ require ( github.com/andybalholm/brotli v1.2.6 // indirect github.com/antlr4-go/antlr/v4 v4.13.1 // indirect github.com/cenkalti/backoff/v4 v4.3.0 // indirect + github.com/coder/websocket v1.8.15 // indirect github.com/desertbit/timer v1.0.1 // indirect github.com/golang/snappy v1.0.0 // indirect github.com/google/cel-go v0.29.0 // indirect diff --git a/internal/conformance/go.sum b/internal/conformance/go.sum index bf7bfdfb..65e2e765 100644 --- a/internal/conformance/go.sum +++ b/internal/conformance/go.sum @@ -54,6 +54,8 @@ github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDk github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc= github.com/cockroachdb/datadriven v0.0.0-20190809214429-80d97fb3cbaa/go.mod h1:zn76sxSg3SzpJ0PPJaLDCu+Bu0Lg3sKTORVIj19EIF8= github.com/codahale/hdrhistogram v0.0.0-20161010025455-3a0bb77429bd/go.mod h1:sE/e/2PUdi/liOCUjSTXgM1o87ZssimdTWN964YiIeI= +github.com/coder/websocket v1.8.15 h1:6B2JPeOGlpff2Uz6vOEH1Vzpi0iUz20A+lPVhPHtNUA= +github.com/coder/websocket v1.8.15/go.mod h1:NX3SzP+inril6yawo5CQXx8+fk145lPDC6pumgx0mVg= github.com/coreos/go-semver v0.2.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3EedlOD2RNk= github.com/coreos/go-systemd v0.0.0-20180511133405-39ca1b05acc7/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4= github.com/coreos/pkg v0.0.0-20160727233714-3ac0863d7acf/go.mod h1:E3G3o1h8I7cfcXa63jLwjI0eiQQMgzzUDFVpN/nH/eA= diff --git a/internal/connecterr/connecterr.go b/internal/connecterr/connecterr.go new file mode 100644 index 00000000..8dad37a2 --- /dev/null +++ b/internal/connecterr/connecterr.go @@ -0,0 +1,123 @@ +// Copyright 2021-2026 The Connect Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// Package connecterr holds the error-coding helpers shared by transports and +// by the framing packages they build on. +package connecterr + +import ( + "context" + "errors" + "fmt" + "net/http" + "os" + + "connectrpc.com/connect/v2" +) + +// AsError uses errors.As to unwrap any error and look for a non-nil +// *connect.Error. +func AsError(err error) (*connect.Error, bool) { + connectErr, ok := errors.AsType[*connect.Error](err) + // A handler returning a nil *connect.Error as error boxes a typed nil. + return connectErr, ok && connectErr != nil +} + +// ScrubHandlerError converts a handler's returned error into the wire +// verdict: only a locally authored *connect.Error keeps its code, message, +// and details. Remote errors become [connect.CodeInternal] and other errors +// [connect.CodeUnknown] (context errors keep their codes), all with no +// message. The original error stays attached as a local-only cause. +func ScrubHandlerError(err error) error { + if err == nil { + return nil + } + if connectErr, ok := AsError(err); ok { + if connectErr.IsRemote() { + return connect.NewError(connect.CodeInternal, "").WithCause(err) + } + return err + } + code := connect.CodeUnknown + switch { + case errors.Is(err, context.Canceled): + code = connect.CodeCanceled + case errors.Is(err, context.DeadlineExceeded), errors.Is(err, os.ErrDeadlineExceeded): + code = connect.CodeDeadlineExceeded + } + return connect.NewError(code, "").WithCause(err) +} + +// WrapIfContextError applies connect.CodeCanceled or +// connect.CodeDeadlineExceeded to Go's context.Canceled and +// context.DeadlineExceeded errors, but only if they haven't already been +// wrapped. +func WrapIfContextError(err error) error { + if err == nil { + return nil + } + if _, ok := AsError(err); ok { + return err + } + if errors.Is(err, context.Canceled) { + return connect.NewError(connect.CodeCanceled, err.Error()).WithCause(err) + } + if errors.Is(err, context.DeadlineExceeded) { + return connect.NewError(connect.CodeDeadlineExceeded, err.Error()).WithCause(err) + } + // Ick, some dial errors can be returned as os.ErrDeadlineExceeded + // instead of context.DeadlineExceeded :( + // https://github.com/golang/go/issues/64449 + if errors.Is(err, os.ErrDeadlineExceeded) { + return connect.NewError(connect.CodeDeadlineExceeded, err.Error()).WithCause(err) + } + return err +} + +// WrapIfContextDone wraps errors with connect.CodeCanceled or +// connect.CodeDeadlineExceeded if the context is done. It leaves +// already-wrapped errors unchanged. +func WrapIfContextDone(ctx context.Context, err error) error { + if err == nil { + return nil + } + err = WrapIfContextError(err) + if _, ok := AsError(err); ok { + return err + } + ctxErr := ctx.Err() + if errors.Is(ctxErr, context.Canceled) { + return connect.NewError(connect.CodeCanceled, err.Error()).WithCause(err) + } else if errors.Is(ctxErr, context.DeadlineExceeded) { + return connect.NewError(connect.CodeDeadlineExceeded, err.Error()).WithCause(err) + } + return err +} + +// WrapIfMaxBytesError wraps errors returned reading from a +// http.MaxBytesHandler whose limit has been exceeded. +func WrapIfMaxBytesError(err error, tmpl string, args ...any) error { + if err == nil { + return nil + } + if _, ok := AsError(err); ok { + return err + } + maxBytesErr, ok := errors.AsType[*http.MaxBytesError](err) + if !ok { + return err + } + prefix := fmt.Sprintf(tmpl, args...) + return connect.Errorf(connect.CodeResourceExhausted, "%s: exceeded %d byte http.MaxBytesReader limit", prefix, maxBytesErr.Limit) +} diff --git a/internal/connecterr/connecterr_test.go b/internal/connecterr/connecterr_test.go new file mode 100644 index 00000000..2860ee63 --- /dev/null +++ b/internal/connecterr/connecterr_test.go @@ -0,0 +1,50 @@ +// Copyright 2021-2026 The Connect Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package connecterr + +import ( + "errors" + "fmt" + "testing" + + "connectrpc.com/connect/v2" + "connectrpc.com/connect/v2/internal/assert" +) + +func TestAsErrorRejectsTypedNil(t *testing.T) { + t.Parallel() + var typedNil *connect.Error + for name, err := range map[string]error{ + "bare": typedNil, + "wrapped": fmt.Errorf("handler: %w", typedNil), + } { + t.Run(name, func(t *testing.T) { + t.Parallel() + connectErr, ok := AsError(err) + assert.False(t, ok) + assert.Nil(t, connectErr) + }) + } +} + +func TestScrubHandlerErrorTypedNil(t *testing.T) { + t.Parallel() + scrubbed := ScrubHandlerError((*connect.Error)(nil)) + connectErr, ok := errors.AsType[*connect.Error](scrubbed) + assert.True(t, ok) + assert.NotNil(t, connectErr) + assert.Equal(t, connectErr.Code(), connect.CodeUnknown) + assert.Equal(t, connectErr.Message(), "") +} diff --git a/internal/connectwire/connectwire.go b/internal/connectwire/connectwire.go new file mode 100644 index 00000000..de6f4c90 --- /dev/null +++ b/internal/connectwire/connectwire.go @@ -0,0 +1,157 @@ +// Copyright 2021-2026 The Connect Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// Package connectwire implements the Connect protocol's JSON error +// representation and its end-of-stream envelope. +// +// Both are protocol concepts rather than HTTP ones, so transports other than +// net/http reuse them to terminate a stream the way Connect clients expect. +package connectwire + +import ( + "bytes" + "context" + "encoding/base64" + "encoding/json" + "fmt" + "net/http" + + "connectrpc.com/connect/v2" + "connectrpc.com/connect/v2/connectproto" + "connectrpc.com/connect/v2/internal/connecterr" +) + +// FlagEnvelopeEndStream marks the envelope that ends a Connect stream. Its +// payload is an [EndStreamMessage]. +const FlagEnvelopeEndStream = 0b00000010 + +// WireDetail adapts a [connect.ErrorDetail] to the Connect protocol's error +// detail object. +type WireDetail connect.ErrorDetail + +// MarshalJSON implements [json.Marshaler]. +func (d *WireDetail) MarshalJSON() ([]byte, error) { + wire := struct { + Type string `json:"type"` + Value string `json:"value"` + Debug json.RawMessage `json:"debug,omitempty"` + }{ + Type: d.Type, + Value: base64.RawStdEncoding.EncodeToString(d.Value), + } + if json.Valid(d.Debug) { + wire.Debug = json.RawMessage(d.Debug) + } else if msg, err := connectproto.ErrorDetailToAny((*connect.ErrorDetail)(d)).UnmarshalNew(); err == nil { + var buffer bytes.Buffer + var codec connectproto.JSONCodec + if err := codec.MarshalWrite(context.Background(), &buffer, msg); err == nil { + wire.Debug = buffer.Bytes() + } + } + return json.Marshal(wire) +} + +// UnmarshalJSON implements [json.Unmarshaler]. +func (d *WireDetail) UnmarshalJSON(data []byte) error { + var wire struct { + Type string `json:"type"` + Value string `json:"value"` + Debug json.RawMessage `json:"debug,omitempty"` + } + if err := json.Unmarshal(data, &wire); err != nil { + return err + } + value, err := connect.DecodeBinaryHeader(wire.Value) + if err != nil { + return fmt.Errorf("decode base64: %w", err) + } + *d = WireDetail{ + Type: wire.Type, + Value: value, + Debug: wire.Debug, + } + return nil +} + +// WireError is the Connect protocol's JSON error object. +type WireError struct { + Code connect.Code `json:"code"` + Message string `json:"message,omitempty"` + Details []*WireDetail `json:"details,omitempty"` +} + +// NewWireError converts err into its wire representation, defaulting to +// [connect.CodeUnknown] for errors that carry no code. +func NewWireError(err error) *WireError { + wire := &WireError{ + Code: connect.CodeUnknown, + Message: err.Error(), + } + if connectErr, ok := connecterr.AsError(err); ok { + wire.Code = connectErr.Code() + wire.Message = connectErr.Message() + if details := connectErr.Details(); len(details) > 0 { + wire.Details = make([]*WireDetail, len(details)) + for i, detail := range details { + wire.Details[i] = (*WireDetail)(detail) + } + } + } + return wire +} + +// AsError converts the wire representation back into a [connect.Error] marked +// as a peer's verdict. +func (e *WireError) AsError() *connect.Error { + if e == nil { + return nil + } + if e.Code < connect.CodeCanceled || e.Code > connect.CodeUnauthenticated { + e.Code = connect.CodeUnknown + } + err := connect.NewError(e.Code, e.Message).WithRemote() + if len(e.Details) > 0 { + for _, detail := range e.Details { + err = err.WithDetail((*connect.ErrorDetail)(detail)) + } + } + return err +} + +// UnmarshalJSON implements [json.Unmarshaler]. +func (e *WireError) UnmarshalJSON(data []byte) error { + // We want to be lenient if the JSON has an unrecognized or invalid code. + // So if that occurs, we leave the code unset but can still de-serialize + // the other fields from the input JSON. + var wireError struct { + Code string `json:"code"` + Message string `json:"message"` + Details []*WireDetail `json:"details"` + } + err := json.Unmarshal(data, &wireError) + if err != nil { + return err + } + e.Message = wireError.Message + e.Details = wireError.Details + // This will leave e.Code unset if we can't unmarshal the given string. + _ = e.Code.UnmarshalText([]byte(wireError.Code)) + return nil +} + +// EndStreamMessage is the JSON payload of the end-of-stream envelope. +type EndStreamMessage struct { + Error *WireError `json:"error,omitempty"` + Trailer http.Header `json:"metadata,omitempty"` +} diff --git a/internal/example/go.mod b/internal/example/go.mod index 2b5ac843..b60405b2 100644 --- a/internal/example/go.mod +++ b/internal/example/go.mod @@ -2,8 +2,10 @@ module connectrpc.com/connect/v2/internal/example go 1.26.0 -require connectrpc.com/connect/v2 v2.0.0-00010101000000-000000000000 - -require google.golang.org/protobuf v1.36.11 // indirect +require ( + connectrpc.com/connect/v2 v2.0.0-00010101000000-000000000000 + github.com/coder/websocket v1.8.15 + google.golang.org/protobuf v1.36.11 +) replace connectrpc.com/connect/v2 => ../../ diff --git a/internal/example/go.sum b/internal/example/go.sum index 296be183..79d667ee 100644 --- a/internal/example/go.sum +++ b/internal/example/go.sum @@ -1,3 +1,5 @@ +github.com/coder/websocket v1.8.15 h1:6B2JPeOGlpff2Uz6vOEH1Vzpi0iUz20A+lPVhPHtNUA= +github.com/coder/websocket v1.8.15/go.mod h1:NX3SzP+inril6yawo5CQXx8+fk145lPDC6pumgx0mVg= github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE= diff --git a/internal/example/websocket/all_streams/server/main.go b/internal/example/websocket/all_streams/server/main.go new file mode 100644 index 00000000..fe8c2337 --- /dev/null +++ b/internal/example/websocket/all_streams/server/main.go @@ -0,0 +1,226 @@ +// Copyright 2021-2026 The Connect Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// Command server implements every PingService RPC, covering all four stream +// types, and serves them over both Connect-over-HTTP and +// Connect-over-WebSocket. It exists for interop testing with other Connect +// implementations, such as connect-es in a browser. +// +// A browser page served from another origin needs that origin allowed: +// +// go run ./websocket/all_streams/server -addr 127.0.0.1:8080 \ +// -allow-origin http://127.0.0.1:3000 +package main + +import ( + "context" + "errors" + "flag" + "io" + "log/slog" + "net" + "net/http" + "os" + "os/signal" + "strings" + "syscall" + "time" + + "connectrpc.com/connect/v2" + "connectrpc.com/connect/v2/connecthttp" + v1 "connectrpc.com/connect/v2/internal/gen/connect/ping/v1" + pingv1connect "connectrpc.com/connect/v2/internal/gen/connect/ping/v1/pingv1connect" +) + +const ( + // requestHeaderKey is echoed back in the Ping-Header response header, so a + // client can check that its request metadata arrived. + requestHeaderKey = "X-Custom" + responseHeaderKey = "Ping-Header" + trailerKey = "Ping-Trailer" + shutdownTimeout = 5 * time.Second +) + +type pingServer struct { + pingv1connect.UnimplementedPingServiceHandler +} + +func (*pingServer) Ping(ctx context.Context, request *v1.PingRequest) (*v1.PingResponse, error) { + setResponseMetadata(ctx) + return &v1.PingResponse{Number: request.GetNumber(), Text: request.GetText()}, nil +} + +// Fail returns an error with the requested code, and a trailer alongside it. +func (*pingServer) Fail(ctx context.Context, request *v1.FailRequest) (*v1.FailResponse, error) { + setResponseMetadata(ctx) + code := request.GetCode() + if code < int32(connect.CodeCanceled) || code > int32(connect.CodeUnauthenticated) { + return nil, connect.Errorf(connect.CodeInvalidArgument, "code %d is not a Connect error code", code) + } + return nil, connect.Errorf(connect.Code(code), "failed as requested") +} + +func (*pingServer) Sum(ctx context.Context, stream pingv1connect.PingServiceSumServerStream) (*v1.SumResponse, error) { + setResponseMetadata(ctx) + var total int64 + for { + request, err := stream.Receive() + if errors.Is(err, io.EOF) { + return &v1.SumResponse{Sum: total}, nil + } + if err != nil { + return nil, err + } + total += request.GetNumber() + } +} + +func (*pingServer) CountUp( + ctx context.Context, + request *v1.CountUpRequest, + stream pingv1connect.PingServiceCountUpServerStream, +) error { + setResponseMetadata(ctx) + for number := int64(1); number <= request.GetNumber(); number++ { + if err := stream.Send(&v1.CountUpResponse{Number: number}); err != nil { + return err + } + } + return nil +} + +func (*pingServer) CumSum(ctx context.Context, stream pingv1connect.PingServiceCumSumServerStream) error { + setResponseMetadata(ctx) + var total int64 + for { + request, err := stream.Receive() + if errors.Is(err, io.EOF) { + return nil + } + if err != nil { + return err + } + total += request.GetNumber() + if err := stream.Send(&v1.CumSumResponse{Sum: total}); err != nil { + return err + } + } +} + +func main() { + address := flag.String("addr", "127.0.0.1:8080", "address to listen on") + allowedOrigins := flag.String( + "allow-origin", + "", + "comma-separated origins allowed to open WebSocket RPCs, in addition to the same origin", + ) + flag.Parse() + if err := run(*address, *allowedOrigins); err != nil { + slog.ErrorContext(context.Background(), "server failed", slog.Any("error", err)) + os.Exit(1) + } +} + +func run(address, allowedOrigins string) error { + ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) + defer stop() + + server := connect.NewServer(logInterceptor) + pingv1connect.RegisterPingServiceHandler(server, &pingServer{}) + mux := http.NewServeMux() + var mountOptions []connecthttp.Option + if allowedOrigins != "" { + mountOptions = append(mountOptions, connecthttp.WithWebSocketCheckOrigin( + newOriginCheck(strings.Split(allowedOrigins, ",")), + )) + } + connecthttp.Mount(mux, server, mountOptions...) + + var listenConfig net.ListenConfig + listener, err := listenConfig.Listen(ctx, "tcp", address) + if err != nil { + return err + } + protocols := new(http.Protocols) + // A WebSocket upgrade needs a hijackable HTTP/1.1 connection. + protocols.SetHTTP1(true) + httpServer := &http.Server{ + Handler: mux, + Protocols: protocols, + ReadHeaderTimeout: shutdownTimeout, + } + serveErr := make(chan error, 1) + go func() { + serveErr <- httpServer.Serve(listener) + }() + slog.InfoContext(ctx, "listening", slog.String("addr", listener.Addr().String())) + select { + case err := <-serveErr: + return err + case <-ctx.Done(): + } + shutdownCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), shutdownTimeout) + defer cancel() + return httpServer.Shutdown(shutdownCtx) +} + +// setResponseMetadata echoes the request's X-Custom header as a response +// header and sets a trailer, so clients can check both directions. +func setResponseMetadata(ctx context.Context) { + info, ok := connect.CallInfoForServerContext(ctx) + if !ok { + return + } + if value := info.RequestHeader().Get(requestHeaderKey); value != "" { + info.ResponseHeader().Set(responseHeaderKey, value) + } + info.ResponseTrailer().Set(trailerKey, "trailer-value") +} + +// newOriginCheck replaces the default same-origin check, so it keeps that +// rule and adds the configured origins to it. A handshake without an Origin +// header is not from a browser and is allowed. +func newOriginCheck(allowedOrigins []string) func(*http.Request) bool { + allowed := make(map[string]struct{}, len(allowedOrigins)) + for _, origin := range allowedOrigins { + allowed[strings.ToLower(strings.TrimSpace(origin))] = struct{}{} + } + return func(request *http.Request) bool { + origin := strings.ToLower(request.Header.Get("Origin")) + if origin == "" { + return true + } + if _, ok := allowed[origin]; ok { + return true + } + _, host, found := strings.Cut(origin, "://") + return found && strings.EqualFold(host, request.Host) + } +} + +func logInterceptor(next connect.ServerFunc) connect.ServerFunc { + return func(ctx context.Context, spec connect.Spec, stream connect.ServerStream) error { + protocol := "unknown" + if info, ok := connect.CallInfoForServerContext(ctx); ok { + protocol = info.Protocol + } + slog.InfoContext( + ctx, + "serving", + slog.String("procedure", spec.Procedure), + slog.String("protocol", protocol), + ) + return next(ctx, spec, stream) + } +} diff --git a/internal/example/websocket/protocol_errors/client/main.go b/internal/example/websocket/protocol_errors/client/main.go new file mode 100644 index 00000000..b22f4dec --- /dev/null +++ b/internal/example/websocket/protocol_errors/client/main.go @@ -0,0 +1,232 @@ +// Copyright 2021-2026 The Connect Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// Command client misframes on purpose, to show what the server's protocol +// error handler sees. +// +// It speaks the wire format by hand rather than through the transport, +// because the Go client cannot produce these mistakes: the transport frames +// correctly. The clients a monitor actually catches are hand-written ones — +// a browser implementation, or another language's — which is exactly what this +// stands in for. +// +// Each fault ends its connection, so every case gets a fresh one. Run the +// matching server first. +package main + +import ( + "context" + "flag" + "fmt" + "log" + "net/http" + "strings" + "time" + + "connectrpc.com/connect/v2" + "connectrpc.com/connect/v2/connecthttp" + v1 "connectrpc.com/connect/v2/internal/gen/connect/ping/v1" + pingv1connect "connectrpc.com/connect/v2/internal/gen/connect/ping/v1/pingv1connect" + "github.com/coder/websocket" + "google.golang.org/protobuf/proto" +) + +// The message markers, one BMP scalar each. +const ( + markerBody = 'B' + markerMetadata = 'M' + markerServerEndStream = 'S' +) + +func main() { + serverURL := flag.String("url", "http://localhost:8080", "base URL of the server") + flag.Parse() + + message, err := proto.Marshal(&v1.CumSumRequest{Number: 7}) + if err != nil { + log.Fatalf("marshal: %v", err) + } + + cases := []struct { + name string + send func(context.Context, *websocket.Conn) error + which string + }{ + { + name: "a well-framed message", + which: "no fault: the monitor stays silent", + send: func(ctx context.Context, conn *websocket.Conn) error { + return writeMessage(ctx, conn, false, markerBody, message) + }, + }, + { + name: "a marker nobody has defined", + which: "marker", + send: func(ctx context.Context, conn *websocket.Conn) error { + return writeMessage(ctx, conn, false, 'Z', message) + }, + }, + { + // Repeated on purpose: the server counts per client, so this is + // what a consistently broken implementation looks like in its log. + name: "the same unknown marker again", + which: "marker", + send: func(ctx context.Context, conn *websocket.Conn) error { + return writeMessage(ctx, conn, false, 'Z', message) + }, + }, + { + name: "the server's own end-of-stream marker", + which: "marker", + send: func(ctx context.Context, conn *websocket.Conn) error { + return writeMessage(ctx, conn, true, markerServerEndStream, []byte("{}")) + }, + }, + { + name: "an empty body in a text frame", + which: "frame_type", + send: func(ctx context.Context, conn *websocket.Conn) error { + // An empty JSON message is {}, never zero bytes. + return writeMessage(ctx, conn, true, markerBody, nil) + }, + }, + { + name: "a second M message", + which: "metadata", + send: func(ctx context.Context, conn *websocket.Conn) error { + return writeMessage(ctx, conn, true, markerMetadata, []byte("[]")) + }, + }, + } + + for _, test := range cases { + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + reply, err := exchange(ctx, *serverURL, test.send) + cancel() + if err != nil { + log.Printf("%-38s -> %-16s connection ended: %v", test.name, test.which, err) + continue + } + log.Printf("%-38s -> %-16s server replied: %s", test.name, test.which, reply) + } + log.Println("check the server's log: every fault above was reported to its handler") + + // The mirror image: an ordinary client, upgrading through connecthttp, + // watching for a *server* that frames its responses wrongly. Against the + // server above this stays silent; against one started with -misframe it + // reports what arrived. Run both ways to see each half. + log.Println("---") + watchForServerFaults(*serverURL) +} + +// watchForServerFaults makes one ordinary RPC with a client-side protocol +// error handler registered, which is the only way a client learns that a +// server misframed rather than simply failed. +func watchForServerFaults(serverURL string) { + transport := connecthttp.NewTransport( + http.DefaultClient, + serverURL, + connecthttp.WithWebSocket(connecthttp.SelectStreaming), + connecthttp.WithWebSocketClientProtocolErrorHandler( + func(spec connect.Spec, fault connecthttp.ProtocolFault, err *connect.Error) { + log.Printf("the server misframed a response to %s: %s — %v", + spec.Procedure, fault, err) + }, + ), + ) + client := pingv1connect.NewPingServiceClient(connect.NewClient(transport)) + + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + stream, err := client.CumSum(ctx) + if err != nil { + log.Fatalf("CumSum: %v", err) + } + defer func() { _ = stream.Close() }() + if err := stream.Send(&v1.CumSumRequest{Number: 7}); err != nil { + log.Printf("Send: %v", err) + return + } + response, err := stream.Receive() + if err != nil { + log.Printf("Receive failed: %v (the handler above says why, if it was a framing fault)", err) + return + } + log.Printf("server framed its response correctly: Sum=%d", response.Sum) +} + +// exchange opens one connection, sends one thing, and reports what came back. +func exchange( + ctx context.Context, + serverURL string, + send func(context.Context, *websocket.Conn) error, +) (string, error) { + url := "ws" + strings.TrimPrefix(serverURL, "http") + pingv1connect.PingServiceCumSumProcedure + conn, response, err := websocket.Dial(ctx, url, &websocket.DialOptions{ + Subprotocols: []string{"connectrpc.1+proto"}, + }) + if response != nil && response.Body != nil { + _ = response.Body.Close() + } + if err != nil { + return "", err + } + defer func() { _ = conn.CloseNow() }() + + // Every stream opens with exactly one M message, empty when the client has + // no metadata to send. Starting with a B or C is invalid. + if err := writeMessage(ctx, conn, true, markerMetadata, []byte("[]")); err != nil { + return "", err + } + if err := send(ctx, conn); err != nil { + return "", err + } + // Every response stream opens with the server's own M message, which + // is ignored. Read past it to the content. + if _, opening, err := conn.Read(ctx); err != nil { + return "", err + } else if len(opening) == 0 || rune(opening[0]) != markerMetadata { + return "", fmt.Errorf("server opened with %q, want an M message", opening) + } + _, data, err := conn.Read(ctx) + if err != nil { + return "", err + } + if len(data) == 0 { + return "", nil + } + // S marks the end-of-stream message, whose payload is the JSON verdict; + // anything else is a normal response message. + if rune(data[0]) == markerServerEndStream { + return string(data[1:]), nil + } + return "a response message", nil +} + +// writeMessage frames one message with an arbitrary marker and frame type, +// which is how this client produces mistakes the transport would not. +func writeMessage( + ctx context.Context, + conn *websocket.Conn, + text bool, + marker rune, + payload []byte, +) error { + frame := append([]byte(string(marker)), payload...) + messageType := websocket.MessageBinary + if text { + messageType = websocket.MessageText + } + return conn.Write(ctx, messageType, frame) +} diff --git a/internal/example/websocket/protocol_errors/client/main_test.go b/internal/example/websocket/protocol_errors/client/main_test.go new file mode 100644 index 00000000..4157f12c --- /dev/null +++ b/internal/example/websocket/protocol_errors/client/main_test.go @@ -0,0 +1,77 @@ +// Copyright 2021-2026 The Connect Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package main + +import ( + "net/http" + "net/http/httptest" + "testing" + + "connectrpc.com/connect/v2" + "connectrpc.com/connect/v2/connecthttp" + "connectrpc.com/connect/v2/internal/example/websocket/protocol_errors/misframe" + v1 "connectrpc.com/connect/v2/internal/gen/connect/ping/v1" + pingv1connect "connectrpc.com/connect/v2/internal/gen/connect/ping/v1/pingv1connect" +) + +// The mirror: a server that misframes its responses is reported to the +// client's handler, which is the only way a client can tell a framing fault +// from any other Internal error. +func TestClientHandlerSeesAMisframingServer(t *testing.T) { + mux := http.NewServeMux() + mux.Handle(pingv1connect.PingServiceCumSumProcedure, http.HandlerFunc(misframe.Handler)) + httpServer := httptest.NewServer(mux) + t.Cleanup(httpServer.Close) + + var ( + gotFault connecthttp.ProtocolFault + gotProcedure string + calls int + ) + transport := connecthttp.NewTransport( + httpServer.Client(), + httpServer.URL, + connecthttp.WithWebSocket(connecthttp.SelectStreaming), + connecthttp.WithWebSocketClientProtocolErrorHandler( + func(spec connect.Spec, fault connecthttp.ProtocolFault, _ *connect.Error) { + calls++ + gotFault = fault + gotProcedure = spec.Procedure + }, + ), + ) + client := pingv1connect.NewPingServiceClient(connect.NewClient(transport)) + stream, err := client.CumSum(t.Context()) + if err != nil { + t.Fatalf("CumSum: %v", err) + } + t.Cleanup(func() { _ = stream.Close() }) + if err := stream.Send(&v1.CumSumRequest{Number: 7}); err != nil { + t.Fatalf("Send: %v", err) + } + if _, err := stream.Receive(); err == nil { + t.Fatal("Receive succeeded against a misframing server; want a framing error") + } + + if calls != 1 { + t.Errorf("handler called %d times; want 1", calls) + } + if gotFault != connecthttp.FaultMarker { + t.Errorf("got fault %s; want %s", gotFault, connecthttp.FaultMarker) + } + if gotProcedure != pingv1connect.PingServiceCumSumProcedure { + t.Errorf("got procedure %q; want %q", gotProcedure, pingv1connect.PingServiceCumSumProcedure) + } +} diff --git a/internal/example/websocket/protocol_errors/misframe/misframe.go b/internal/example/websocket/protocol_errors/misframe/misframe.go new file mode 100644 index 00000000..de251ddb --- /dev/null +++ b/internal/example/websocket/protocol_errors/misframe/misframe.go @@ -0,0 +1,66 @@ +// Copyright 2021-2026 The Connect Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// Package misframe holds a server that answers with deliberately malformed +// frames, so the protocol_errors example can demonstrate the client-side +// protocol error handler. +// +// It is its own package because both halves of the example need it: the server +// binary serves it under -misframe, and the client's test points at it. Two +// package mains cannot share code, and a second copy could drift from the one +// the example actually runs. +package misframe + +import ( + "net/http" + + v1 "connectrpc.com/connect/v2/internal/gen/connect/ping/v1" + "github.com/coder/websocket" + "google.golang.org/protobuf/proto" +) + +// Handler answers an upgrade with a response carrying a marker nobody has +// defined — the mistake a client reports as connecthttp.FaultMarker. +// +// It speaks the wire format by hand rather than going through connecthttp's +// WebSocket transport, because that transport frames correctly and no option +// makes it stop. +func Handler(responseWriter http.ResponseWriter, request *http.Request) { + conn, err := websocket.Accept(responseWriter, request, &websocket.AcceptOptions{ + Subprotocols: []string{"connectrpc.1+proto"}, + InsecureSkipVerify: true, + }) + if err != nil { + return + } + defer func() { _ = conn.CloseNow() }() + + ctx := request.Context() + if _, _, err := conn.Read(ctx); err != nil { // the client's request + return + } + payload, err := proto.Marshal(&v1.CumSumResponse{Sum: 7}) + if err != nil { + return + } + // Every response stream opens with an M message. This one is well formed, + // so the client accepts the stream and then meets the lie below — without + // it the client would refuse the opening itself, and the fault reported + // would be about metadata rather than the marker. + if err := conn.Write(ctx, websocket.MessageText, []byte("M[]")); err != nil { + return + } + frame := append([]byte("Z"), payload...) // the lie + _ = conn.Write(ctx, websocket.MessageBinary, frame) +} diff --git a/internal/example/websocket/protocol_errors/server/main.go b/internal/example/websocket/protocol_errors/server/main.go new file mode 100644 index 00000000..f53dfef5 --- /dev/null +++ b/internal/example/websocket/protocol_errors/server/main.go @@ -0,0 +1,145 @@ +// Copyright 2021-2026 The Connect Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// Command server monitors clients that send malformed frames. +// +// A framing fault is reported to the offending client in the end-of-stream +// message, which means it is a *successful* outcome from the server's point of +// view: it never reaches the logger, and a Session wrapper sees a nil error. An +// interceptor does see it, but only as Internal — the same code every +// framing fault carries. WithWebSocketServerProtocolErrorHandler is the hook that says +// which kind of mistake it was and who made it. +// +// Run this, then the matching client, which misframes on purpose. +// +// The client watches for the opposite fault — a server that misframes its +// responses — with WithWebSocketClientProtocolErrorHandler. To make that half fire, +// start this server with -misframe, which answers with malformed frames +// instead of mounting the real service. +package main + +import ( + "context" + "errors" + "flag" + "io" + "log" + "net" + "net/http" + "sync" + + "connectrpc.com/connect/v2" + "connectrpc.com/connect/v2/connecthttp" + "connectrpc.com/connect/v2/internal/example/websocket/protocol_errors/misframe" + v1 "connectrpc.com/connect/v2/internal/gen/connect/ping/v1" + pingv1connect "connectrpc.com/connect/v2/internal/gen/connect/ping/v1/pingv1connect" +) + +type pingServer struct { + pingv1connect.UnimplementedPingServiceHandler +} + +func (pingServer) CumSum(_ context.Context, stream pingv1connect.PingServiceCumSumServerStream) error { + var total int64 + for { + req, err := stream.Receive() + if errors.Is(err, io.EOF) { + return nil + } + if err != nil { + return err + } + total += req.Number + if err := stream.Send(&v1.CumSumResponse{Sum: total}); err != nil { + return err + } + } +} + +// faultMonitor is the shape a real deployment would give this: a counter per +// peer and per kind of mistake, so a client that consistently sends unknown +// markers stands out from one that trips over a frame type once. +type faultMonitor struct { + mu sync.Mutex + counts map[string]map[connecthttp.ProtocolFault]int +} + +func newFaultMonitor() *faultMonitor { + return &faultMonitor{counts: make(map[string]map[connecthttp.ProtocolFault]int)} +} + +// observe is the ProtocolErrorHandler. It returns nothing: the error reaches +// the offending client either way, so a monitor cannot accidentally swallow a +// fault by mishandling it. +// +// It runs on the connection's read path, so it must not block. Counting under +// a mutex is fine; exporting to a metrics backend should be asynchronous. +func (m *faultMonitor) observe( + peerAddr string, + request *http.Request, + fault connecthttp.ProtocolFault, + err *connect.Error, +) { + // Keyed on the host, not on PeerAddr: that carries the ephemeral port, so + // counting by it would start over on every connection — and one connection + // carries one RPC, so a repeat offender would never register. A deployment + // with authenticated clients should key on the account instead, which the + // upgrade request makes reachable. + client := peerAddr + if host, _, splitErr := net.SplitHostPort(client); splitErr == nil { + client = host + } + + m.mu.Lock() + byFault, ok := m.counts[client] + if !ok { + byFault = make(map[connecthttp.ProtocolFault]int) + m.counts[client] = byFault + } + byFault[fault]++ + total := byFault[fault] + m.mu.Unlock() + + log.Printf("protocol fault from %s on %s: %s (#%d for this client) — %v", + client, request.URL.Path, fault, total, err) +} + +func main() { + addr := flag.String("addr", "localhost:8080", "address to listen on") + misframing := flag.Bool("misframe", false, + "answer with malformed frames, to exercise the client's error handler") + flag.Parse() + + server := connect.NewServer() + pingv1connect.RegisterPingServiceHandler(server, pingServer{}) + monitor := newFaultMonitor() + + mux := http.NewServeMux() + if *misframing { + log.Println("misframing mode: responses are deliberately malformed") + mux.Handle(pingv1connect.PingServiceCumSumProcedure, http.HandlerFunc(misframe.Handler)) + } else { + connecthttp.Mount(mux, server, + connecthttp.WithWebSocketServerProtocolErrorHandler(monitor.observe), + ) + } + + protocols := new(http.Protocols) + protocols.SetHTTP1(true) // an upgrade needs a hijackable connection + httpServer := &http.Server{Addr: *addr, Handler: mux, Protocols: protocols} + log.Println("listening on", httpServer.Addr) + if err := httpServer.ListenAndServe(); err != nil { + log.Fatal(err) + } +} diff --git a/internal/example/websocket/protocol_errors/server/main_test.go b/internal/example/websocket/protocol_errors/server/main_test.go new file mode 100644 index 00000000..0838bcba --- /dev/null +++ b/internal/example/websocket/protocol_errors/server/main_test.go @@ -0,0 +1,149 @@ +// Copyright 2021-2026 The Connect Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// This file covers the server-side monitor. The client's handler — the +// mirror, against the misframing server in ../misframe — is tested beside the +// client binary. + +package main + +import ( + "context" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "connectrpc.com/connect/v2" + "connectrpc.com/connect/v2/connecthttp" + v1 "connectrpc.com/connect/v2/internal/gen/connect/ping/v1" + pingv1connect "connectrpc.com/connect/v2/internal/gen/connect/ping/v1/pingv1connect" + "github.com/coder/websocket" + "google.golang.org/protobuf/proto" +) + +// newMonitoredServer starts the same mux main() serves, on a real HTTP/1.1 +// listener: an upgrade needs a hijackable connection. +func newMonitoredServer(tb testing.TB) (*httptest.Server, *faultMonitor) { + tb.Helper() + server := connect.NewServer() + pingv1connect.RegisterPingServiceHandler(server, pingServer{}) + monitor := newFaultMonitor() + mux := http.NewServeMux() + connecthttp.Mount(mux, server, + connecthttp.WithWebSocketServerProtocolErrorHandler(monitor.observe), + ) + httpServer := httptest.NewServer(mux) + tb.Cleanup(httpServer.Close) + return httpServer, monitor +} + +// sendOneFrame opens a connection, writes one frame, and reads the verdict. +func sendOneFrame(tb testing.TB, serverURL string, text bool, marker rune, payload []byte) { + tb.Helper() + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + url := "ws" + strings.TrimPrefix(serverURL, "http") + pingv1connect.PingServiceCumSumProcedure + conn, response, err := websocket.Dial(ctx, url, &websocket.DialOptions{ + Subprotocols: []string{"connectrpc.1+proto"}, + }) + if response != nil && response.Body != nil { + _ = response.Body.Close() + } + if err != nil { + tb.Fatalf("dial: %v", err) + } + defer func() { _ = conn.CloseNow() }() + + // Every stream opens with one M message; the frame under test follows it. + if err := conn.Write(ctx, websocket.MessageText, []byte("M[]")); err != nil { + tb.Fatalf("write opening metadata: %v", err) + } + + frame := append([]byte(string(marker)), payload...) + messageType := websocket.MessageBinary + if text { + messageType = websocket.MessageText + } + if err := conn.Write(ctx, messageType, frame); err != nil { + tb.Fatalf("write: %v", err) + } + _, _, _ = conn.Read(ctx) +} + +// The monitor counts repeated mistakes from one client, which is the point of +// keying on the host rather than on PeerAddr: one connection carries one RPC, +// so a per-connection counter could never exceed one. +func TestMonitorCountsRepeatOffenders(t *testing.T) { + httpServer, monitor := newMonitoredServer(t) + message, err := proto.Marshal(&v1.CumSumRequest{Number: 7}) + if err != nil { + t.Fatalf("marshal: %v", err) + } + + // Two unknown markers, on two connections. + sendOneFrame(t, httpServer.URL, false, 'Z', message) + sendOneFrame(t, httpServer.URL, false, 'Y', message) + // And one of a different kind, which must count separately. + sendOneFrame(t, httpServer.URL, true, 'B', nil) + + monitor.mu.Lock() + defer monitor.mu.Unlock() + if len(monitor.counts) != 1 { + t.Fatalf("got %d clients; want 1 (all faults came from one host)", len(monitor.counts)) + } + for client, byFault := range monitor.counts { + if got := byFault[connecthttp.FaultMarker]; got != 2 { + t.Errorf("%s: got %d marker faults; want 2", client, got) + } + if got := byFault[connecthttp.FaultFrameType]; got != 1 { + t.Errorf("%s: got %d frame_type faults; want 1", client, got) + } + } +} + +// A well-framed client produces nothing: the handler reports faults, not +// traffic. +func TestMonitorSilentOnCleanTraffic(t *testing.T) { + httpServer, monitor := newMonitoredServer(t) + transport := connecthttp.NewTransport( + httpServer.Client(), + httpServer.URL, + connecthttp.WithWebSocket(connecthttp.SelectStreaming), + ) + client := pingv1connect.NewPingServiceClient(connect.NewClient(transport)) + stream, err := client.CumSum(t.Context()) + if err != nil { + t.Fatalf("CumSum: %v", err) + } + if err := stream.Send(&v1.CumSumRequest{Number: 1}); err != nil { + t.Fatalf("Send: %v", err) + } + if _, err := stream.Receive(); err != nil { + t.Fatalf("Receive: %v", err) + } + if err := stream.CloseSend(); err != nil { + t.Fatalf("CloseSend: %v", err) + } + if err := stream.Close(); err != nil { + t.Fatalf("Close: %v", err) + } + + monitor.mu.Lock() + defer monitor.mu.Unlock() + if len(monitor.counts) != 0 { + t.Errorf("got %d clients reported; want 0", len(monitor.counts)) + } +} diff --git a/internal/example/websocket/send_close/client/main.go b/internal/example/websocket/send_close/client/main.go new file mode 100644 index 00000000..5f2fff0e --- /dev/null +++ b/internal/example/websocket/send_close/client/main.go @@ -0,0 +1,110 @@ +// Copyright 2021-2026 The Connect Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// Command client sums ten numbers over a client-streaming RPC. +// +// Run with -abandon to drop the connection halfway instead of ending the +// stream properly. The two look identical to the client's Send loop and +// different to the server, which is the point: a handler that treats a dead +// client as a finished one commits a total the client never asked for. +package main + +import ( + "context" + "flag" + "fmt" + "log" + "net/http" + + "connectrpc.com/connect/v2" + "connectrpc.com/connect/v2/connecthttp" + v1 "connectrpc.com/connect/v2/internal/gen/connect/ping/v1" + pingv1connect "connectrpc.com/connect/v2/internal/gen/connect/ping/v1/pingv1connect" +) + +const serverURL = "http://localhost:8080" + +// abandon is set from the command line; see the package comment. +var abandon *bool + +// transportInterceptor logs the wire protocol the transport resolved for each +// call, which is how this example shows the routing actually happening. +func transportInterceptor(next connect.ClientFunc) connect.ClientFunc { + return func(ctx context.Context, spec connect.Spec) (connect.ClientStream, error) { + stream, err := next(ctx, spec) + if info, ok := connect.CallInfoForClientContext(ctx); ok { + log.Printf("called %s over %s", spec.Procedure, info.Protocol) + } + return stream, err + } +} + +func main() { + abandon = flag.Bool("abandon", false, + "drop the connection mid-stream instead of sending end-of-stream") + flag.Parse() + + // One transport, two wires: connecthttp carries every RPC, and the selector + // says which ones upgrade. SelectStreaming sends the streaming RPCs over + // WebSocket and leaves unary on HTTP, where a handshake would buy nothing. + // Without WithWebSocket, everything stays on HTTP. + transport := connecthttp.NewTransport( + http.DefaultClient, + serverURL, + connecthttp.WithWebSocket(connecthttp.SelectStreaming), + ) + pingClient := pingv1connect.NewPingServiceClient( + connect.NewClient(transport, transportInterceptor), + ) + + // NewClientContext attaches the CallInfo the transport publishes response + // metadata onto; without it there is nowhere for the server's M message to + // land. + ctx, info := connect.NewClientContext(context.Background()) + ctx, cancel := context.WithCancel(ctx) + defer cancel() + stream, err := pingClient.Sum(ctx) + if err != nil { + log.Fatalf("Sum: %v", err) + } + for i := range 10 { + if err := stream.Send(&v1.SumRequest{Number: int64(i)}); err != nil { + log.Fatalf("Sum.Send: %v", err) + } + if *abandon && i == 4 { + // Walk away mid-stream, the way a crashed or disconnected client + // does: cancel and return without closing the stream. Nothing + // sends a C message, so the server learns the stream ended + // without learning that the client was finished. + // + // Deliberately not CloseAndReceive here. That sends a C, and + // whether the cancelled context stops it in time is a race — so + // the server would see a finished client on some runs and an + // abandoned one on others. + log.Println("abandoning the stream after 5 of 10 values") + cancel() + log.Println("check the server's log: it discarded the partial sum rather than answering") + return + } + } + response, err := stream.CloseAndReceive() + if err != nil { + log.Fatalf("Sum.CloseAndReceive: %v", err) + } + // Response metadata the handler set, carried in the M message that opens + // every response stream. Over plain HTTP the same value would arrive in + // the response header block. + log.Printf("server counted %s values", info.ResponseHeader().Get("Acme-Values-Counted")) + fmt.Println(response.Sum) +} diff --git a/internal/example/websocket/send_close/server/main.go b/internal/example/websocket/send_close/server/main.go new file mode 100644 index 00000000..ae631f0d --- /dev/null +++ b/internal/example/websocket/send_close/server/main.go @@ -0,0 +1,121 @@ +// Copyright 2021-2026 The Connect Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// Command server serves the ping service over two transports at once: unary +// RPCs on plain HTTP, and streaming RPCs over WebSocket, sharing one set of +// procedure paths. +package main + +import ( + "context" + "errors" + "io" + "log" + "net/http" + "strconv" + + "connectrpc.com/connect/v2" + "connectrpc.com/connect/v2/connecthttp" + v1 "connectrpc.com/connect/v2/internal/gen/connect/ping/v1" + pingv1connect "connectrpc.com/connect/v2/internal/gen/connect/ping/v1/pingv1connect" +) + +// pingServer implements the two methods this example exercises: Ping, a unary +// request/response, and CumSum, a bidirectional stream. +type pingServer struct { + pingv1connect.UnimplementedPingServiceHandler +} + +func (pingServer) Sum(ctx context.Context, stream pingv1connect.PingServiceSumServerStream) (*v1.SumResponse, error) { + var total int64 + var count int + for { + request, err := stream.Receive() + switch { + case err == nil: + total += request.Number + count++ + continue + + case errors.Is(err, io.EOF): + // The client sent C: it is done and waiting for this answer. The + // total is complete, so committing it is safe. + log.Printf("client finished after %d values; answering with %d", count, total) + // Response metadata, which reaches the client as the M message + // that opens every response stream. Setting it here — after the + // last Receive, on the way out — works because this RPC's single + // response is sent once the handler returns, so nothing has gone + // out yet. A server-streaming handler would have to set it before + // its first Send, or lose it. + if info, ok := connect.CallInfoForServerContext(ctx); ok { + info.ResponseHeader().Set("Acme-Values-Counted", strconv.Itoa(count)) + } + return &v1.SumResponse{Sum: total}, nil + + case connect.CodeOf(err) == connect.CodeCanceled: + // The connection ended without C. The client may have crashed + // mid-send, so these %d values are a prefix of an unknown whole — + // answering would invent a total nobody asked for, and committing + // one to a database would be worse. + log.Printf("client abandoned the stream after %d values; discarding %d", count, total) + return nil, err + + default: + return nil, err + } + } +} + +// transportInterceptor logs which wire protocol carried each RPC, which is how +// this example shows the routing actually happening. +func transportInterceptor(next connect.ServerFunc) connect.ServerFunc { + return func(ctx context.Context, spec connect.Spec, stream connect.ServerStream) error { + protocol := "unknown" + if info, ok := connect.CallInfoForServerContext(ctx); ok { + protocol = info.Protocol + } + log.Printf("serving %s over %s", spec.Procedure, protocol) + return next(ctx, spec, stream) + } +} + +func main() { + server := connect.NewServer(transportInterceptor) + pingv1connect.RegisterPingServiceHandler(server, pingServer{}) + + mux := http.NewServeMux() + // One call registers every procedure over both transports at the same + // paths: a WebSocket upgrade is served by the WebSocket transport, and every + // other request by the connecthttp handler underneath. The client picks + // which transport carries each RPC; the server accepts either. + // + // WebSocket is on by default, and connecthttp.WithoutWebSocket() turns it + // off. To give WebSocket its own paths, mount a second mux under them and + // give WebSocket clients that base URL. + connecthttp.Mount(mux, server) + + protocols := new(http.Protocols) + // HTTP/1.1 only: a WebSocket upgrade needs a hijackable connection, which + // HTTP/2 does not provide. + protocols.SetHTTP1(true) + httpServer := &http.Server{ + Addr: "localhost:8080", + Handler: mux, + Protocols: protocols, + } + log.Println("listening on", httpServer.Addr) + if err := httpServer.ListenAndServe(); err != nil { + log.Fatal(err) + } +} diff --git a/internal/example/websocket/simple/client/main.go b/internal/example/websocket/simple/client/main.go new file mode 100644 index 00000000..b656f8f1 --- /dev/null +++ b/internal/example/websocket/simple/client/main.go @@ -0,0 +1,101 @@ +// Copyright 2021-2026 The Connect Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// Command client calls the ping service through a hybrid transport: streaming +// RPCs travel over WebSocket, unary RPCs fall through to plain HTTP. +package main + +import ( + "context" + "errors" + "io" + "log" + "net/http" + "time" + + "connectrpc.com/connect/v2" + "connectrpc.com/connect/v2/connecthttp" + v1 "connectrpc.com/connect/v2/internal/gen/connect/ping/v1" + pingv1connect "connectrpc.com/connect/v2/internal/gen/connect/ping/v1/pingv1connect" +) + +const serverURL = "http://localhost:8080" + +// transportInterceptor logs the wire protocol the transport resolved for each +// call, which is how this example shows the routing actually happening. +func transportInterceptor(next connect.ClientFunc) connect.ClientFunc { + return func(ctx context.Context, spec connect.Spec) (connect.ClientStream, error) { + stream, err := next(ctx, spec) + if info, ok := connect.CallInfoForClientContext(ctx); ok { + log.Printf("called %s over %s", spec.Procedure, info.Protocol) + } + return stream, err + } +} + +func main() { + // A deadline bounds the whole session. Over WebSocket it reaches the server + // as the connect-timeout-ms query parameter on the handshake URI — a + // browser cannot set a request header there, so the query string is the + // deadline's only channel. The server takes the shorter of this and its own + // maximum. + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + + // One transport, two wires: connecthttp carries every RPC, and the selector + // says which ones upgrade. SelectStreaming sends the streaming RPCs over + // WebSocket and leaves unary on HTTP, where a handshake would buy nothing. + // Without WithWebSocket, everything stays on HTTP. + transport := connecthttp.NewTransport( + http.DefaultClient, + serverURL, + connecthttp.WithWebSocket(connecthttp.SelectStreaming), + ) + pingClient := pingv1connect.NewPingServiceClient( + connect.NewClient(transport, transportInterceptor), + ) + + // Unary: falls through to HTTP. + res, err := pingClient.Ping(ctx, &v1.PingRequest{Number: 42, Text: "hello"}) + if err != nil { + log.Fatalf("Ping: %v", err) + } + log.Printf("Ping: number=%d text=%q", res.Number, res.Text) + + // Bidirectional stream: travels over WebSocket. Sends and receives + // interleave, which is the shape HTTP/1.1 cannot carry. + stream, err := pingClient.CumSum(ctx) + if err != nil { + log.Fatalf("CumSum: %v", err) + } + for _, number := range []int64{1, 2, 3, 4} { + if err := stream.Send(&v1.CumSumRequest{Number: number}); err != nil { + log.Fatalf("CumSum.Send: %v", err) + } + msg, err := stream.Receive() + if err != nil { + log.Fatalf("CumSum.Receive: %v", err) + } + log.Printf("CumSum: sent=%d running total=%d", number, msg.Sum) + } + if err := stream.CloseSend(); err != nil { + log.Fatalf("CumSum.CloseSend: %v", err) + } + if _, err := stream.Receive(); !errors.Is(err, io.EOF) { + log.Fatalf("CumSum: expected io.EOF, got %v", err) + } + if err := stream.Close(); err != nil { + log.Fatalf("CumSum.Close: %v", err) + } +} diff --git a/internal/example/websocket/simple/server/main.go b/internal/example/websocket/simple/server/main.go new file mode 100644 index 00000000..453191c9 --- /dev/null +++ b/internal/example/websocket/simple/server/main.go @@ -0,0 +1,112 @@ +// Copyright 2021-2026 The Connect Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// Command server serves the ping service over two transports at once: unary +// RPCs on plain HTTP, and streaming RPCs over WebSocket, sharing one set of +// procedure paths. +package main + +import ( + "context" + "errors" + "io" + "log" + "net/http" + "time" + + "connectrpc.com/connect/v2" + "connectrpc.com/connect/v2/connecthttp" + v1 "connectrpc.com/connect/v2/internal/gen/connect/ping/v1" + pingv1connect "connectrpc.com/connect/v2/internal/gen/connect/ping/v1/pingv1connect" +) + +// pingServer implements the two methods this example exercises: Ping, a unary +// request/response, and CumSum, a bidirectional stream. +type pingServer struct { + pingv1connect.UnimplementedPingServiceHandler +} + +func (pingServer) Ping(_ context.Context, req *v1.PingRequest) (*v1.PingResponse, error) { + return &v1.PingResponse{Number: req.Number, Text: req.Text}, nil +} + +// CumSum echoes a running total, one response per request, until the client +// half-closes. Over HTTP/1.1 this shape needs full-duplex streaming that the +// protocol cannot provide; over WebSocket it works on either HTTP version. +func (pingServer) CumSum(_ context.Context, stream pingv1connect.PingServiceCumSumServerStream) error { + var total int64 + for { + req, err := stream.Receive() + if errors.Is(err, io.EOF) { + return nil + } + if err != nil { + return err + } + total += req.Number + if err := stream.Send(&v1.CumSumResponse{Sum: total}); err != nil { + return err + } + } +} + +// transportInterceptor logs which wire protocol carried each RPC, which is how +// this example shows the routing actually happening. +func transportInterceptor(next connect.ServerFunc) connect.ServerFunc { + return func(ctx context.Context, spec connect.Spec, stream connect.ServerStream) error { + protocol := "unknown" + if info, ok := connect.CallInfoForServerContext(ctx); ok { + protocol = info.Protocol + } + // The client's deadline reaches a WebSocket RPC as a query parameter on + // the handshake, and a plain HTTP one as a header. Logged so the two + // routes can be seen arriving at the same place. + remaining := "none" + if deadline, ok := ctx.Deadline(); ok { + remaining = time.Until(deadline).Round(time.Second).String() + } + log.Printf("serving %s over %s (deadline in %s)", spec.Procedure, protocol, remaining) + return next(ctx, spec, stream) + } +} + +func main() { + server := connect.NewServer(transportInterceptor) + pingv1connect.RegisterPingServiceHandler(server, pingServer{}) + + mux := http.NewServeMux() + // One call registers every procedure over both transports at the same + // paths: a WebSocket upgrade is served by the WebSocket transport, and every + // other request by the connecthttp handler underneath. The client picks + // which transport carries each RPC; the server accepts either. + // + // WebSocket is on by default, and connecthttp.WithoutWebSocket() turns it + // off. To give WebSocket its own paths, mount a second mux under them and + // give WebSocket clients that base URL. + connecthttp.Mount(mux, server) + + protocols := new(http.Protocols) + // HTTP/1.1 only: a WebSocket upgrade needs a hijackable connection, which + // HTTP/2 does not provide. + protocols.SetHTTP1(true) + httpServer := &http.Server{ + Addr: "localhost:8080", + Handler: mux, + Protocols: protocols, + } + log.Println("listening on", httpServer.Addr) + if err := httpServer.ListenAndServe(); err != nil { + log.Fatal(err) + } +} diff --git a/internal/example/websocket/simple/server/main_test.go b/internal/example/websocket/simple/server/main_test.go new file mode 100644 index 00000000..2fb01de9 --- /dev/null +++ b/internal/example/websocket/simple/server/main_test.go @@ -0,0 +1,107 @@ +// Copyright 2021-2026 The Connect Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package main + +import ( + "context" + "errors" + "io" + "net/http" + "net/http/httptest" + "testing" + + "connectrpc.com/connect/v2" + "connectrpc.com/connect/v2/connecthttp" + v1 "connectrpc.com/connect/v2/internal/gen/connect/ping/v1" + pingv1connect "connectrpc.com/connect/v2/internal/gen/connect/ping/v1/pingv1connect" +) + +// newTestClient starts the same hybrid mux main() serves, on a real HTTP/1.1 +// listener. httptest is used rather than an in-memory server because a +// WebSocket upgrade needs a hijackable connection. +func newTestClient(tb testing.TB, protocol *string) pingv1connect.PingServiceClient { + tb.Helper() + server := connect.NewServer() + pingv1connect.RegisterPingServiceHandler(server, pingServer{}) + mux := http.NewServeMux() + connecthttp.Mount(mux, server) + httpServer := httptest.NewServer(mux) + tb.Cleanup(httpServer.Close) + + transport := connecthttp.NewTransport( + httpServer.Client(), + httpServer.URL, + connecthttp.WithWebSocket(connecthttp.SelectStreaming), + ) + record := func(next connect.ClientFunc) connect.ClientFunc { + return func(ctx context.Context, spec connect.Spec) (connect.ClientStream, error) { + stream, err := next(ctx, spec) + if info, ok := connect.CallInfoForClientContext(ctx); ok { + *protocol = info.Protocol + } + return stream, err + } + } + return pingv1connect.NewPingServiceClient(connect.NewClient(transport, record)) +} + +func TestPingFallsThroughToHTTP(t *testing.T) { + var protocol string + client := newTestClient(t, &protocol) + res, err := client.Ping(t.Context(), &v1.PingRequest{Number: 42, Text: "hello"}) + if err != nil { + t.Fatalf("Ping: %v", err) + } + if res.Number != 42 || res.Text != "hello" { + t.Errorf("got Number=%d Text=%q; want 42 %q", res.Number, res.Text, "hello") + } + if protocol != connect.ProtocolNameConnect { + t.Errorf("Ping used %q; want it to fall through to %q", protocol, connect.ProtocolNameConnect) + } +} + +func TestCumSumOverWebSocket(t *testing.T) { + var protocol string + client := newTestClient(t, &protocol) + stream, err := client.CumSum(t.Context()) + if err != nil { + t.Fatalf("CumSum: %v", err) + } + want := []int64{1, 3, 6, 10} + for i, number := range []int64{1, 2, 3, 4} { + if err := stream.Send(&v1.CumSumRequest{Number: number}); err != nil { + t.Fatalf("CumSum.Send: %v", err) + } + msg, err := stream.Receive() + if err != nil { + t.Fatalf("CumSum.Receive: %v", err) + } + if msg.Sum != want[i] { + t.Errorf("after %d messages got Sum=%d; want %d", i+1, msg.Sum, want[i]) + } + } + if err := stream.CloseSend(); err != nil { + t.Fatalf("CumSum.CloseSend: %v", err) + } + if _, err := stream.Receive(); !errors.Is(err, io.EOF) { + t.Errorf("after CloseSend got %v; want io.EOF", err) + } + if err := stream.Close(); err != nil { + t.Fatalf("CumSum.Close: %v", err) + } + if protocol != connecthttp.ProtocolNameConnectWebSocket { + t.Errorf("CumSum used %q; want %q", protocol, connecthttp.ProtocolNameConnectWebSocket) + } +} diff --git a/internal/example/websocket/transport_choice/client/main.go b/internal/example/websocket/transport_choice/client/main.go new file mode 100644 index 00000000..078f6d37 --- /dev/null +++ b/internal/example/websocket/transport_choice/client/main.go @@ -0,0 +1,139 @@ +// Copyright 2021-2026 The Connect Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// Command client runs the same server stream four times against one server, +// choosing a different transport each time. Nothing about the server changes +// between runs: the Selector passed to connecthttp.WithWebSocket is a +// client-side decision, and the server accepts whichever wire the client +// picked. +// +// Run the transport_choice server first, then: +// +// go run ./websocket/transport_choice/client +package main + +import ( + "context" + "errors" + "flag" + "io" + "log" + "net/http" + + "connectrpc.com/connect/v2" + "connectrpc.com/connect/v2/connecthttp" + v1 "connectrpc.com/connect/v2/internal/gen/connect/ping/v1" + pingv1connect "connectrpc.com/connect/v2/internal/gen/connect/ping/v1/pingv1connect" +) + +// choices are the routing rules this example demonstrates, in the order it +// runs them. +var choices = []struct { + name string + selector connecthttp.Selector + explain string +}{ + { + name: "default", + explain: "streaming over WebSocket, unary over HTTP", + // Leaving the selector nil keeps SelectStreaming, the default. + }, + { + name: "all", + selector: connecthttp.SelectAll, + explain: "everything over WebSocket, including unary", + }, + { + name: "bidi only", + selector: connecthttp.SelectBidi, + explain: "only full-duplex RPCs upgrade; a server stream is plain HTTP", + }, + { + name: "never", + selector: func(connect.Spec) bool { return false }, + explain: "no upgrade at all; the fallback transport carries everything", + }, +} + +func main() { + serverURL := flag.String("url", "http://localhost:8080", "base URL of the server") + count := flag.Int64("count", 3, "how many numbers to ask CountUp for") + flag.Parse() + + for _, choice := range choices { + selector := choice.selector + if selector == nil { + selector = connecthttp.SelectStreaming + } + transport := connecthttp.NewTransport( + http.DefaultClient, + *serverURL, + connecthttp.WithWebSocket(selector), + ) + + var protocol string + client := pingv1connect.NewPingServiceClient( + connect.NewClient(transport, recordProtocol(&protocol)), + ) + numbers, err := countUp(context.Background(), client, *count) + if err != nil { + log.Fatalf("%s: CountUp: %v", choice.name, err) + } + log.Printf("selector %-9s -> CountUp over %-18s got %v (%s)", + choice.name, protocol, numbers, choice.explain) + } +} + +// countUp drains the server stream and returns what it produced. +func countUp( + ctx context.Context, + client pingv1connect.PingServiceClient, + count int64, +) ([]int64, error) { + stream, err := client.CountUp(ctx, &v1.CountUpRequest{Number: count}) + if err != nil { + return nil, err + } + defer func() { + if err := stream.Close(); err != nil { + log.Printf("CountUp.Close: %v", err) + } + }() + var numbers []int64 + for { + message, err := stream.Receive() + if errors.Is(err, io.EOF) { + // The end of the stream, not a failure. + return numbers, nil + } + if err != nil { + return nil, err + } + numbers = append(numbers, message.Number) + } +} + +// recordProtocol captures the wire the transport resolved for each RPC, which +// is the only way to observe the selector's decision from the client side. +func recordProtocol(into *string) connect.ClientInterceptor { + return func(next connect.ClientFunc) connect.ClientFunc { + return func(ctx context.Context, spec connect.Spec) (connect.ClientStream, error) { + stream, err := next(ctx, spec) + if info, ok := connect.CallInfoForClientContext(ctx); ok { + *into = info.Protocol + } + return stream, err + } + } +} diff --git a/internal/example/websocket/transport_choice/server/main.go b/internal/example/websocket/transport_choice/server/main.go new file mode 100644 index 00000000..4662d8e1 --- /dev/null +++ b/internal/example/websocket/transport_choice/server/main.go @@ -0,0 +1,98 @@ +// Copyright 2021-2026 The Connect Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// Command server serves one streaming procedure over both transports, so that +// the client alone decides which wire carries it. The server makes no such +// choice: it answers a WebSocket upgrade and a plain HTTP request on the same +// path, and logs which one arrived. +package main + +import ( + "context" + "flag" + "log" + "net/http" + + "connectrpc.com/connect/v2" + "connectrpc.com/connect/v2/connecthttp" + v1 "connectrpc.com/connect/v2/internal/gen/connect/ping/v1" + pingv1connect "connectrpc.com/connect/v2/internal/gen/connect/ping/v1/pingv1connect" +) + +// pingServer implements a unary procedure and a server stream. A server stream +// is the interesting shape here: unlike a bidirectional one it works over +// either transport, so the client's choice is a real choice rather than a +// requirement. +type pingServer struct { + pingv1connect.UnimplementedPingServiceHandler +} + +func (pingServer) Ping(_ context.Context, req *v1.PingRequest) (*v1.PingResponse, error) { + return &v1.PingResponse{Number: req.Number, Text: req.Text}, nil +} + +func (pingServer) CountUp( + _ context.Context, + req *v1.CountUpRequest, + stream pingv1connect.PingServiceCountUpServerStream, +) error { + for i := int64(1); i <= req.Number; i++ { + if err := stream.Send(&v1.CountUpResponse{Number: i}); err != nil { + return err + } + } + return nil +} + +// transportInterceptor logs the wire each RPC arrived on, which is how this +// example shows the client's choice taking effect. +func transportInterceptor(next connect.ServerFunc) connect.ServerFunc { + return func(ctx context.Context, spec connect.Spec, stream connect.ServerStream) error { + protocol := "unknown" + if info, ok := connect.CallInfoForServerContext(ctx); ok { + protocol = info.Protocol + } + log.Printf("serving %s over %s", spec.Procedure, protocol) + return next(ctx, spec, stream) + } +} + +func main() { + addr := flag.String("addr", "localhost:8080", "address to listen on") + flag.Parse() + + server := connect.NewServer(transportInterceptor) + pingv1connect.RegisterPingServiceHandler(server, pingServer{}) + + mux := http.NewServeMux() + // Every procedure is registered over both transports. There is deliberately + // no server-side selector: which transport carries an RPC is the client's + // decision, and a server that served only one would reject a client that + // chose the other. + connecthttp.Mount(mux, server) + + protocols := new(http.Protocols) + // HTTP/1.1 only: a WebSocket upgrade needs a hijackable connection, which + // HTTP/2 does not provide. + protocols.SetHTTP1(true) + httpServer := &http.Server{ + Addr: *addr, + Handler: mux, + Protocols: protocols, + } + log.Println("listening on", httpServer.Addr) + if err := httpServer.ListenAndServe(); err != nil { + log.Fatal(err) + } +} diff --git a/internal/example/websocket/transport_choice/server/main_test.go b/internal/example/websocket/transport_choice/server/main_test.go new file mode 100644 index 00000000..8840a2f9 --- /dev/null +++ b/internal/example/websocket/transport_choice/server/main_test.go @@ -0,0 +1,149 @@ +// Copyright 2021-2026 The Connect Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package main + +import ( + "context" + "net/http" + "net/http/httptest" + "testing" + + "connectrpc.com/connect/v2" + "connectrpc.com/connect/v2/connecthttp" + v1 "connectrpc.com/connect/v2/internal/gen/connect/ping/v1" + pingv1connect "connectrpc.com/connect/v2/internal/gen/connect/ping/v1/pingv1connect" +) + +// newServer starts the same mux main() serves, on a real HTTP/1.1 listener: a +// WebSocket upgrade needs a hijackable connection, which an in-memory server +// does not give. +func newServer(tb testing.TB) *httptest.Server { + tb.Helper() + server := connect.NewServer() + pingv1connect.RegisterPingServiceHandler(server, pingServer{}) + mux := http.NewServeMux() + connecthttp.Mount(mux, server) + httpServer := httptest.NewServer(mux) + tb.Cleanup(httpServer.Close) + return httpServer +} + +func recordProtocol(into *string) connect.ClientInterceptor { + return func(next connect.ClientFunc) connect.ClientFunc { + return func(ctx context.Context, spec connect.Spec) (connect.ClientStream, error) { + stream, err := next(ctx, spec) + if info, ok := connect.CallInfoForClientContext(ctx); ok { + *into = info.Protocol + } + return stream, err + } + } +} + +// One server, four client routing rules, one procedure: the same server stream +// comes back correctly every time, over whichever wire the client chose. +func TestClientChoosesTheTransport(t *testing.T) { + httpServer := newServer(t) + + for _, test := range []struct { + name string + selector connecthttp.Selector + want string + }{ + {"default", nil, connecthttp.ProtocolNameConnectWebSocket}, + {"all", connecthttp.SelectAll, connecthttp.ProtocolNameConnectWebSocket}, + {"bidi only", connecthttp.SelectBidi, connect.ProtocolNameConnect}, + {"never", func(connect.Spec) bool { return false }, connect.ProtocolNameConnect}, + } { + t.Run(test.name, func(t *testing.T) { + selector := test.selector + if selector == nil { + selector = connecthttp.SelectStreaming + } + transport := connecthttp.NewTransport( + httpServer.Client(), + httpServer.URL, + connecthttp.WithWebSocket(selector), + ) + var protocol string + client := pingv1connect.NewPingServiceClient( + connect.NewClient(transport, recordProtocol(&protocol)), + ) + + stream, err := client.CountUp(t.Context(), &v1.CountUpRequest{Number: 3}) + if err != nil { + t.Fatalf("CountUp: %v", err) + } + var got []int64 + for { + message, err := stream.Receive() + if err != nil { + break + } + got = append(got, message.Number) + } + if err := stream.Close(); err != nil { + t.Fatalf("CountUp.Close: %v", err) + } + if len(got) != 3 || got[0] != 1 || got[2] != 3 { + t.Errorf("got %v; want [1 2 3]", got) + } + if protocol != test.want { + t.Errorf("CountUp used %q; want %q", protocol, test.want) + } + }) + } +} + +// Unary is the other half of the default rule: it stays on HTTP unless the +// client asks for everything to be upgraded. +func TestUnaryFollowsTheSameRule(t *testing.T) { + httpServer := newServer(t) + + for _, test := range []struct { + name string + selector connecthttp.Selector + want string + }{ + {"default leaves unary on HTTP", nil, connect.ProtocolNameConnect}, + {"SelectAll upgrades unary too", connecthttp.SelectAll, connecthttp.ProtocolNameConnectWebSocket}, + } { + t.Run(test.name, func(t *testing.T) { + selector := test.selector + if selector == nil { + selector = connecthttp.SelectStreaming + } + transport := connecthttp.NewTransport( + httpServer.Client(), + httpServer.URL, + connecthttp.WithWebSocket(selector), + ) + var protocol string + client := pingv1connect.NewPingServiceClient( + connect.NewClient(transport, recordProtocol(&protocol)), + ) + response, err := client.Ping(t.Context(), &v1.PingRequest{Number: 42}) + if err != nil { + t.Fatalf("Ping: %v", err) + } + if response.Number != 42 { + t.Errorf("got Number=%d; want 42", response.Number) + } + if protocol != test.want { + t.Errorf("Ping used %q; want %q", protocol, test.want) + } + }) + } +} diff --git a/internal/wstransport/afterendofstream_test.go b/internal/wstransport/afterendofstream_test.go new file mode 100644 index 00000000..2c55fea1 --- /dev/null +++ b/internal/wstransport/afterendofstream_test.go @@ -0,0 +1,118 @@ +// Copyright 2021-2026 The Connect Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package wstransport + +import ( + "context" + "strings" + "sync" + "testing" + + "connectrpc.com/connect/v2/internal/assert" + "github.com/coder/websocket" +) + +// recordingSender keeps every message written through it. +type recordingSender struct { + mu sync.Mutex + messages [][]byte +} + +func (s *recordingSender) send(_ context.Context, _ bool, data []byte) (int64, error) { + s.mu.Lock() + defer s.mu.Unlock() + s.messages = append(s.messages, append([]byte(nil), data...)) + return int64(len(data)), nil +} + +func (s *recordingSender) last() string { + s.mu.Lock() + defer s.mu.Unlock() + if len(s.messages) == 0 { + return "" + } + return string(s.messages[len(s.messages)-1]) +} + +// §8: a message the server has already read after C is a protocol error, even +// when the handler returned at io.EOF before the post-C drain looked at it. +// Close is the last place it can be noticed, and must not report success. +func TestCloseReportsAMessageReadAfterEndOfClientStream(t *testing.T) { + t.Parallel() + for _, test := range []struct { + name string + read frameResult + wantCode websocket.StatusCode + wantInEnd string + }{ + { + name: "message", + read: frameResult{messageType: websocket.MessageBinary, frame: []byte{markerBody}}, + wantCode: websocket.StatusProtocolError, + wantInEnd: "after its C message", + }, + { + name: "oversized message", + read: frameResult{err: errMessageTooBig}, + wantCode: websocket.StatusMessageTooBig, + wantInEnd: "resource_exhausted", + }, + } { + t.Run(test.name, func(t *testing.T) { + t.Parallel() + ctx, cancel := context.WithCancel(t.Context()) + t.Cleanup(cancel) + delivered := false + reader := newFrameReader(ctx, func(readCtx context.Context) (websocket.MessageType, []byte, error) { + if !delivered { + delivered = true + return test.read.messageType, test.read.frame, test.read.err + } + <-readCtx.Done() + return 0, nil, readCtx.Err() + }, nil) + t.Cleanup(func() { + cancel() + reader.close() + }) + assert.True(t, reader.await(ctx)) + + serverConn, clientConn := connPair(t) + sender := &recordingSender{} + conn := &websocketHandlerConn{ + wsConn: serverConn, + marshaler: messageWriter{ + sender: sender, + }, + frameDecoder: frameDecoder{readMaxBytes: 1024}, + reader: reader, + eof: true, + sawEndOfClientStream: true, + leadingSent: true, + } + closed := make(chan error, 1) + go func() { closed <- conn.Close(t.Context(), nil) }() + + readCtx, cancelRead := context.WithTimeout(t.Context(), wsTestReadTimeout) + defer cancelRead() + _, _, readErr := clientConn.Read(readCtx) + assert.Equal(t, websocket.CloseStatus(readErr), test.wantCode) + <-closed + end := sender.last() + assert.True(t, strings.HasPrefix(end, "S"), assert.Sprintf("%q", end)) + assert.True(t, strings.Contains(end, test.wantInEnd), assert.Sprintf("%q", end)) + }) + } +} diff --git a/internal/wstransport/baseurlpath_ext_test.go b/internal/wstransport/baseurlpath_ext_test.go new file mode 100644 index 00000000..0213f78a --- /dev/null +++ b/internal/wstransport/baseurlpath_ext_test.go @@ -0,0 +1,180 @@ +// Copyright 2021-2026 The Connect Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package wstransport_test + +import ( + "errors" + "io" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" + + "connectrpc.com/connect/v2" + "connectrpc.com/connect/v2/connecthttp" + "connectrpc.com/connect/v2/internal/assert" + pingv1 "connectrpc.com/connect/v2/internal/gen/connect/ping/v1" + "connectrpc.com/connect/v2/internal/gen/connect/ping/v1/pingv1connect" + "connectrpc.com/connect/v2/internal/wstransport" +) + +// pathRecorder records the path of every request that reaches it, keyed by +// whether it was a WebSocket upgrade. The two transports have to agree, and +// the only way to know is to watch both arrive. +type pathRecorder struct { + mu sync.Mutex + websocket []string + http []string +} + +func (r *pathRecorder) wrap(next http.Handler) http.Handler { + return http.HandlerFunc(func(responseWriter http.ResponseWriter, request *http.Request) { + r.mu.Lock() + if wstransport.IsUpgrade(request) { + r.websocket = append(r.websocket, request.URL.Path) + } else { + r.http = append(r.http, request.URL.Path) + } + r.mu.Unlock() + next.ServeHTTP(responseWriter, request) + }) +} + +func (r *pathRecorder) paths() (websocket, http []string) { + r.mu.Lock() + defer r.mu.Unlock() + return append([]string(nil), r.websocket...), append([]string(nil), r.http...) +} + +// newPrefixedServer mounts both transports under prefix, the way a service +// sharing a host with other routes would. +func newPrefixedServer(tb testing.TB, prefix string) (*httptest.Server, *pathRecorder) { + tb.Helper() + server := connect.NewServer() + pingv1connect.RegisterPingServiceHandler(server, pingServer{}) + inner := http.NewServeMux() + connecthttp.Mount(inner, server) + recorder := &pathRecorder{} + outer := http.NewServeMux() + outer.Handle(prefix+"/", http.StripPrefix(prefix, recorder.wrap(inner))) + httpServer := httptest.NewServer(outer) + tb.Cleanup(httpServer.Close) + return httpServer, recorder +} + +// A base URL with a path prefix has to reach the same procedures a bare one +// does, over both halves of the transport. +func TestBaseURLWithPathPrefixRoutesBothTransports(t *testing.T) { + t.Parallel() + httpServer, recorder := newPrefixedServer(t, "/api") + transport := connecthttp.NewTransport( + httpServer.Client(), + httpServer.URL+"/api", + connecthttp.WithWebSocket(connecthttp.SelectStreaming), + ) + client := pingv1connect.NewPingServiceClient(connect.NewClient(transport)) + + // Unary travels over HTTP, bidi over WebSocket. + res, err := client.Ping(t.Context(), &pingv1.PingRequest{Number: 7, Text: "prefixed"}) + assert.Nil(t, err) + assert.Equal(t, res.Number, int64(7)) + assert.Equal(t, res.Text, "prefixed") + + stream, err := client.CumSum(t.Context()) + assert.Nil(t, err) + assert.Nil(t, stream.Send(&pingv1.CumSumRequest{Number: 3})) + sum, err := stream.Receive() + assert.Nil(t, err) + assert.Equal(t, sum.Sum, int64(3)) + assert.Nil(t, stream.CloseSend()) + assert.Nil(t, stream.Close()) + + // StripPrefix has already run, so the recorded paths are the bare + // procedures: what matters is that the prefix was there to strip. + websocketPaths, httpPaths := recorder.paths() + assert.Equal(t, websocketPaths, []string{pingv1connect.PingServiceCumSumProcedure}) + assert.Equal(t, httpPaths, []string{pingv1connect.PingServicePingProcedure}) +} + +// Whatever the shape of the base URL's path, both halves must derive the same +// request path from it. connecthttp joins with its own helper and this package +// with another; a divergence would quietly route the two halves apart. +func TestBothTransportsAgreeOnTheRequestPath(t *testing.T) { + t.Parallel() + for _, suffix := range []string{"", "/", "/api", "/api/", "/api//", "/a/b"} { + t.Run("base"+suffix, func(t *testing.T) { + t.Parallel() + recorder := &pathRecorder{} + // Nothing is mounted: every request 404s. The paths are recorded on + // the way in, which is all this test reads. + httpServer := httptest.NewServer(recorder.wrap(http.NotFoundHandler())) + t.Cleanup(httpServer.Close) + + transport := connecthttp.NewTransport( + httpServer.Client(), + httpServer.URL+suffix, + connecthttp.WithWebSocket(connecthttp.SelectStreaming), + ) + client := pingv1connect.NewPingServiceClient(connect.NewClient(transport)) + + _, err := client.Ping(t.Context(), &pingv1.PingRequest{}) + assert.NotNil(t, err) + stream, err := client.CumSum(t.Context()) + assert.Nil(t, err) + assert.NotNil(t, stream.Send(&pingv1.CumSumRequest{})) + _ = stream.Close() + + websocketPaths, httpPaths := recorder.paths() + assert.Equal(t, len(websocketPaths), 1) + assert.Equal(t, len(httpPaths), 1) + assert.Equal(t, + strings.TrimSuffix(websocketPaths[0], pingv1connect.PingServiceCumSumProcedure), + strings.TrimSuffix(httpPaths[0], pingv1connect.PingServicePingProcedure), + ) + // And the shared prefix is the base URL's own path, normalized. + assert.Equal(t, websocketPaths[0], strings.TrimSuffix(suffix, "/")+pingv1connect.PingServiceCumSumProcedure) + }) + } +} + +// A path prefix that the client adds and the server does not strip shows up as +// a procedure the registry has never heard of. The session has to answer that, +// because the handshake has already succeeded and a caller waiting on Receive +// has nothing else to wait for. +func TestUnregisteredProcedureIsUnimplemented(t *testing.T) { + t.Parallel() + httpServer := newHybridServer(t, pingServer{}) + transport := connecthttp.NewTransport( + httpServer.Client(), + httpServer.URL, + connecthttp.WithWebSocket(connecthttp.SelectAll), + ) + + stream, err := transport.NewClientStream(t.Context(), connect.Spec{ + Procedure: "/connect.ping.v1.PingService/NoSuchMethod", + StreamType: connect.StreamTypeBidi, + }) + assert.Nil(t, err) + t.Cleanup(func() { _ = stream.Close() }) + // The server answers once it reads M, so the verdict can beat the first body + // to the wire; Send then reports io.EOF, as over HTTP. + if err := stream.Send(&pingv1.CumSumRequest{Number: 1}); err != nil { + assert.True(t, errors.Is(err, io.EOF), assert.Sprintf("%v", err)) + } + err = stream.Receive(&pingv1.CumSumResponse{}) + assert.NotNil(t, err) + assert.Equal(t, connect.CodeOf(err), connect.CodeUnimplemented) +} diff --git a/internal/wstransport/browser_ext_test.go b/internal/wstransport/browser_ext_test.go new file mode 100644 index 00000000..fd73cd41 --- /dev/null +++ b/internal/wstransport/browser_ext_test.go @@ -0,0 +1,249 @@ +// Copyright 2021-2026 The Connect Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package wstransport_test + +import ( + "context" + "encoding/json" + "maps" + "net/http" + "net/http/httptest" + "testing" + "time" + + "connectrpc.com/connect/v2" + "connectrpc.com/connect/v2/connecthttp" + "connectrpc.com/connect/v2/internal/assert" + pingv1 "connectrpc.com/connect/v2/internal/gen/connect/ping/v1" + "connectrpc.com/connect/v2/internal/gen/connect/ping/v1/pingv1connect" + "github.com/coder/websocket" + "google.golang.org/protobuf/proto" +) + +// Message markers, restated here so the tests assert against the wire format +// rather than against the implementation's constants. +const ( + wireBody byte = 'B' // either direction + wireMetadata byte = 'M' // either direction + wireServerEndStream byte = 'S' // server -> client + wireClientEndStream byte = 'C' // client -> server +) + +// browserClient is the hand-rolled stand-in for a browser: it speaks the wire +// format directly, including the two client-only flag bits the Go client never +// sends. Without it the browser paths have no coverage at all. +type browserClient struct { + conn *websocket.Conn +} + +func dialBrowserClient(tb testing.TB, server *httptest.Server, procedure string) *browserClient { + tb.Helper() + return dialBrowserClientWithToken(tb, server, procedure, "connectrpc.1+proto") +} + +// dialBrowserClientWithToken offers one specific subprotocol, for tests that +// care which codec the token selects rather than taking the default. +func dialBrowserClientWithToken( + tb testing.TB, + server *httptest.Server, + procedure string, + token string, +) *browserClient { + tb.Helper() + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + tb.Cleanup(cancel) + conn, res, err := websocket.Dial(ctx, "ws"+server.URL[4:]+procedure, &websocket.DialOptions{ + HTTPClient: server.Client(), + Subprotocols: []string{token}, + }) + if res != nil && res.Body != nil { + _ = res.Body.Close() + } + if err != nil { + tb.Fatalf("dial: %v", err) + } + tb.Cleanup(func() { _ = conn.CloseNow() }) + client := &browserClient{conn: conn} + // Every stream opens with exactly one M message, empty when + // there is none. Tests with metadata of their own use dialBrowserClientOpening. + client.writeJSON(tb, wireMetadata, []byte("[]")) + return client +} + +// dialBrowserClientOpening opens the stream with the given metadata payload +// rather than an empty one — a stream carries exactly one such message, so a +// test cannot send its metadata as a second. +func dialBrowserClientOpening( + tb testing.TB, + server *httptest.Server, + procedure string, + metadata []byte, +) *browserClient { + tb.Helper() + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + tb.Cleanup(cancel) + conn, res, err := websocket.Dial(ctx, "ws"+server.URL[4:]+procedure, &websocket.DialOptions{ + HTTPClient: server.Client(), + Subprotocols: []string{"connectrpc.1+proto"}, + }) + if res != nil && res.Body != nil { + _ = res.Body.Close() + } + if err != nil { + tb.Fatalf("dial: %v", err) + } + tb.Cleanup(func() { _ = conn.CloseNow() }) + client := &browserClient{conn: conn} + client.writeJSON(tb, wireMetadata, metadata) + return client +} + +// writeMessage frames one marker and payload into one WebSocket message. text +// picks the frame type, which is what tells the peer how to read the payload. +func (c *browserClient) writeMessage(tb testing.TB, marker byte, text bool, payload []byte) { + tb.Helper() + frame := append([]byte{marker}, payload...) + messageType := websocket.MessageBinary + if text { + messageType = websocket.MessageText + } + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + if err := c.conn.Write(ctx, messageType, frame); err != nil { + tb.Fatalf("write message: %v", err) + } +} + +// writeJSON sends a control message, which is always JSON in a text frame. +func (c *browserClient) writeJSON(tb testing.TB, marker byte, payload []byte) { + tb.Helper() + c.writeMessage(tb, marker, true, payload) +} + +// writeProto sends a body encoded as Protobuf, hence a binary frame. +func (c *browserClient) writeProto(tb testing.TB, payload []byte) { + tb.Helper() + c.writeMessage(tb, wireBody, false, payload) +} + +// readMessage reads one message and splits off its marker, reporting whether +// it arrived in a text frame. +func (c *browserClient) readMessage(tb testing.TB) (byte, []byte, bool) { + tb.Helper() + ctx, cancel := readContext(tb) + defer cancel() + messageType, data, err := c.conn.Read(ctx) + if err != nil { + tb.Fatalf("read message: %v", err) + } + if len(data) == 0 { + tb.Fatal("empty message carries no marker") + } + return data[0], data[1:], messageType == websocket.MessageText +} + +// metadataServer records the request metadata the handler observed. +type metadataServer struct { + pingv1connect.UnimplementedPingServiceHandler + + seen chan http.Header +} + +func (m metadataServer) CumSum(ctx context.Context, stream pingv1connect.PingServiceCumSumServerStream) error { + // Receive first: M messages arrive before the first body + // message, so the metadata is only complete after a read. + req, err := stream.Receive() + if err != nil { + return err + } + header := http.Header{} + if info, ok := connect.CallInfoForServerContext(ctx); ok { + maps.Insert(header, info.RequestHeader().All()) + } + m.seen <- header + return stream.Send(&pingv1.CumSumResponse{Sum: req.Number}) +} + +func newMetadataServer(tb testing.TB, seen chan http.Header) *httptest.Server { + tb.Helper() + server := connect.NewServer() + pingv1connect.RegisterPingServiceHandler(server, metadataServer{seen: seen}) + mux := http.NewServeMux() + connecthttp.Mount(mux, server) + httpServer := httptest.NewServer(mux) + tb.Cleanup(httpServer.Close) + return httpServer +} + +// TestBrowserLeadingMetadataMessage drives the M path: a client that cannot +// set headers on the upgrade sends them as a message instead. +func TestBrowserLeadingMetadataMessage(t *testing.T) { + t.Parallel() + seen := make(chan http.Header, 1) + metadata, err := json.Marshal([][]string{{"acme-tenant", "tenant-42"}}) + assert.Nil(t, err) + client := dialBrowserClientOpening(t, newMetadataServer(t, seen), pingProcedure, metadata) + + request, err := proto.Marshal(&pingv1.CumSumRequest{Number: 3}) + assert.Nil(t, err) + client.writeProto(t, request) + + // Every response stream opens with the server's own M, even empty. + opening, _, openingText := client.readMessage(t) + assert.Equal(t, opening, wireMetadata) + assert.True(t, openingText) // metadata is JSON, so a text frame + + marker, payload, text := client.readMessage(t) + assert.Equal(t, marker, wireBody) + assert.False(t, text) // a Protobuf body is a binary frame + var response pingv1.CumSumResponse + assert.Nil(t, proto.Unmarshal(payload, &response)) + assert.Equal(t, response.Sum, int64(3)) + + header := <-seen + assert.Equal(t, header.Get("Acme-Tenant"), "tenant-42") +} + +// TestBrowserEndOfClientStreamMessage drives the C path, which stands in for +// the request-body EOF a WebSocket cannot send. +func TestBrowserEndOfClientStreamMessage(t *testing.T) { + t.Parallel() + seen := make(chan http.Header, 1) + client := dialBrowserClient(t, newMetadataServer(t, seen), pingProcedure) + + request, err := proto.Marshal(&pingv1.CumSumRequest{Number: 5}) + assert.Nil(t, err) + client.writeProto(t, request) + opening, _, _ := client.readMessage(t) + assert.Equal(t, opening, wireMetadata) + marker, payload, _ := client.readMessage(t) + assert.Equal(t, marker, wireBody) + var response pingv1.CumSumResponse + assert.Nil(t, proto.Unmarshal(payload, &response)) + assert.Equal(t, response.Sum, int64(5)) + <-seen + + // A bare C: the handler should see io.EOF and return, which makes the + // server send its S message. + client.writeJSON(t, wireClientEndStream, nil) + endMarker, endPayload, endText := client.readMessage(t) + assert.Equal(t, endMarker, wireServerEndStream) + assert.True(t, endText) // EndStreamMessage is JSON, so a text frame + var end map[string]any + assert.Nil(t, json.Unmarshal(endPayload, &end)) + // A clean finish carries no error member. + _, hasError := end["error"] + assert.False(t, hasError) +} diff --git a/internal/wstransport/client.go b/internal/wstransport/client.go new file mode 100644 index 00000000..37b480a5 --- /dev/null +++ b/internal/wstransport/client.go @@ -0,0 +1,214 @@ +// Copyright 2021-2026 The Connect Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package wstransport + +import ( + "context" + "net/http" + "net/url" + "slices" + "strconv" + "strings" + "time" + + "connectrpc.com/connect/v2" + "github.com/coder/websocket" +) + +// NewTransport returns a [connect.Transport] that carries every RPC over +// WebSocket, with no HTTP fallback. An http or https scheme in baseURL is +// rewritten to ws or wss. +// +// Do not call this directly. It exists for +// [connectrpc.com/connect/v2/connecthttp], which builds one of these and wraps +// it with an HTTP transport to route each RPC by a selector. Use +// connecthttp.NewTransport with connecthttp.WithWebSocket instead; a transport +// from here upgrades everything and fails against a peer that does not. +func NewTransport(baseURL string, options ...ClientOption) (connect.Transport, error) { + opts := defaultOptions() + for _, opt := range options { + opt.applyToClient(&opts) + } + parsed, err := url.Parse(baseURL) + if err != nil { + return nil, connect.Errorf(connect.CodeUnavailable, "invalid base URL: %s", err).WithCause(err) + } + switch strings.ToLower(parsed.Scheme) { + case "http", "ws", "": + parsed.Scheme = "ws" + case "https", "wss": + parsed.Scheme = "wss" + default: + return nil, connect.Errorf(connect.CodeUnavailable, "unsupported URL scheme %q", parsed.Scheme) + } + codecs := newCodecRegistry(opts.codecs) + sendCodec, ok := codecs.get(opts.sendCodec) + if !ok { + return nil, connect.Errorf(connect.CodeUnknown, "unknown codec %q", opts.sendCodec) + } + if !validCodecName(opts.sendCodec) { + return nil, connect.Errorf( + connect.CodeUnknown, + "send codec %q has no WebSocket subprotocol; §4.3 requires a lower-case HTTP token", + opts.sendCodec, + ) + } + offered := []string{subprotocolForCodec(opts.sendCodec)} + for _, codec := range carriedCodecs(opts.codecs) { + if codec.Name() != opts.sendCodec { + offered = append(offered, subprotocolForCodec(codec.Name())) + } + } + return &clientTransport{ + baseURL: parsed, + httpClient: opts.httpClient, + sendCodec: sendCodec, + dial: &dialConfig{ + offered: offered, + codecs: codecs, + handshakeTimeout: opts.handshakeTimeout, + readLimit: messageReadLimit(opts.readMaxBytes), + keepAliveInterval: opts.keepAliveInterval, + keepAliveTimeout: opts.keepAliveTimeout, + }, + opts: &opts, + }, nil +} + +type clientTransport struct { + baseURL *url.URL + httpClient *http.Client + sendCodec connect.Codec + dial *dialConfig + opts *options +} + +// offeredSubprotocols returns a copy of the tokens to offer, for a call's dial +// options to keep without sharing the transport's slice. +func (t *clientTransport) offeredSubprotocols() []string { + return slices.Clone(t.dial.offered) +} + +// encodeTimeout renders the context's deadline for the connect-timeout-ms +// query parameter. The query string is the deadline's only channel: a browser +// cannot set a header on a handshake, so a header would serve no client this +// transport has to interoperate with. +func encodeTimeout(ctx context.Context) (string, bool) { + deadline, ok := ctx.Deadline() + if !ok { + return "", false + } + // Rounded up, never down. Truncating can advertise a deadline shorter than + // the caller's own, and a server that gives up first is killed mid-read by + // the WebSocket library — which closes the connection, so the deadline + // error never reaches the client and it reports the close as Unavailable + // instead. + millis := int64((time.Until(deadline) + time.Millisecond - 1) / time.Millisecond) + // A non-positive or absurdly distant deadline is not expressible; let the + // context alone enforce it rather than sending nonsense. + encoded := strconv.FormatInt(millis, 10) + if millis <= 0 || len(encoded) > 10 { + return "", false + } + return encoded, true +} + +func (t *clientTransport) NewClientStream(ctx context.Context, spec connect.Spec) (connect.ClientStream, error) { + info, _ := connect.CallInfoForClientContext(ctx) + dialURL := t.dialURL(ctx, spec) + call := t.newCall(dialURL) + conn := &websocketClientConn{ + ctx: ctx, + frameDecoder: frameDecoder{ + fromServer: true, + readMaxBytes: t.opts.readMaxBytes, + }, + call: call, + marshaler: messageWriter{ + // No compression here: permessage-deflate compresses whole messages + // below this layer. + sender: call, + sendMaxBytes: t.opts.sendMaxBytes, + }, + spec: spec, + onProtocolError: t.opts.onClientProtocolError, + callInfo: info, + responseHeader: make(http.Header), + responseTrailer: make(http.Header), + } + if info != nil { + info.Spec = spec + conn.marshaler.stats = &info.SendStats + conn.receiveStats = &info.ReceiveStats + info.PeerAddr = dialURL.Host + info.Protocol = ProtocolConnectWebSocket + info.Codec = t.opts.sendCodec + info.RequestEncoding = connect.CompressionNameIdentity + } + if t.opts.eagerDial { + // Dial now rather than on first use. A caller who asked for this has + // somewhere else to send the RPC and needs the answer here, while that + // choice is still open: once this returns a stream, the upgrade error + // would surface from Send and the choice would be gone. + if err := call.ensureDialed(ctx); err != nil { + return nil, err + } + } + return &clientStream{ + conn: conn, + // Unary and client-streaming both have exactly one response message, + // and it is the second read that reaches the trailers. + singleResponse: spec.StreamType&connect.StreamTypeServer == 0, + }, nil +} + +// dialURL is where spec's procedure is served, carrying ctx's deadline. +func (t *clientTransport) dialURL(ctx context.Context, spec connect.Spec) *url.URL { + dialURL := *t.baseURL + dialURL.Path = strings.TrimSuffix(dialURL.Path, "/") + spec.Procedure + if encoded, ok := encodeTimeout(ctx); ok { + query := dialURL.Query() + query.Set(wsQueryTimeoutMs, encoded) + dialURL.RawQuery = query.Encode() + } + return &dialURL +} + +// newCall prepares, but does not dial, the connection for one RPC. +func (t *clientTransport) newCall(dialURL *url.URL) *wsClientCall { + drain := newDrainLimiter(t.dial.readLimit) + beat := &heartbeat{} + return &wsClientCall{ + heartbeat: beat, + config: t.dial, + drain: drain, + dialOptions: &websocket.DialOptions{ + HTTPClient: withDrainLimiter(t.httpClient, drain), + // §4.6: a server's own PINGs and PONGs are frames from it too. + OnPingReceived: beat.onPing, + OnPongReceived: beat.onPong, + // §4.3: the preferred codec first, then any other this client can + // encode. The server picks one and the client follows its choice. + Subprotocols: t.offeredSubprotocols(), + // Offer permessage-deflate with a per-message context. A server + // that declines leaves messages uncompressed; one that requires + // no-context-takeover is already satisfied by this offer. + CompressionMode: t.opts.compressionMode(), + CompressionThreshold: t.opts.compressionThreshold(), + }, + url: dialURL, + codec: t.sendCodec, + } +} diff --git a/internal/wstransport/client_call.go b/internal/wstransport/client_call.go new file mode 100644 index 00000000..2211ace2 --- /dev/null +++ b/internal/wstransport/client_call.go @@ -0,0 +1,214 @@ +// Copyright 2021-2026 The Connect Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package wstransport + +import ( + "context" + "fmt" + "io" + "net/http" + "net/url" + "strings" + "sync" + "time" + + "connectrpc.com/connect/v2" + "github.com/coder/websocket" +) + +// wsStatusClientProtocolError is the code §13 has a client send for most faults. +// A browser script may only pass 1000 or 3000-4999 to close(), so the reason, +// not the code, says what went wrong. +const wsStatusClientProtocolError = websocket.StatusCode(3102) + +// wsClientCall owns the lazy dial and is the [messageSender] the +// writer sends through. Dialing on first use rather than at construction is +// what lets a stream be created without a round trip. +type wsClientCall struct { + config *dialConfig + dialOptions *websocket.DialOptions + url *url.URL + // codec starts as the send codec and becomes the server's choice once the + // handshake completes. + codec connect.Codec + // drain caps what the closing handshake reads; see drainLimiter. + drain *drainLimiter + + // heartbeat carries the server's PINGs and PONGs to reader; the dial + // options' callbacks hold it. + heartbeat *heartbeat + + // stopCloseOnDone cancels the Close frame sent when ctx ends, once the + // connection is being closed anyway. + stopCloseOnDone func() bool + + // dialOnce also makes concurrent callers wait for the dial in progress. + dialOnce sync.Once + wsConn *websocket.Conn + reader *frameReader + keeper *keepAlive + response *http.Response + dialErr *connect.Error +} + +// ensureDialed dials under ctx, the RPC's context, on first use. Later callers +// share the first one's result, so every caller must pass that same context. +func (c *wsClientCall) ensureDialed(ctx context.Context) *connect.Error { + c.dialOnce.Do(func() { + conn, err := c.handshake(ctx) + if err != nil { + c.dialErr = err + return + } + c.start(ctx, conn) + }) + return c.dialErr +} + +// start begins reading and keeping alive an accepted connection. +func (c *wsClientCall) start(ctx context.Context, conn *websocket.Conn) { + // The limit is enforced in readBoundedMessage, as on the server, so an + // oversized message is classified and closed like any other fault. + conn.SetReadLimit(-1) + c.wsConn = conn + // The library tears a connection down without a Close frame when a + // read's or write's context ends, so the connection runs detached from + // the call. §11.1 and §13 have a client whose call ends before S close + // with 1000, which the server takes as the cancellation (§8). + readLimit := c.config.readLimit + connCtx := context.WithoutCancel(ctx) + c.stopCloseOnDone = context.AfterFunc(ctx, func() { + _ = closeWithDrain(conn, c.drain, websocket.StatusNormalClosure, "") + }) + c.reader = newFrameReader( + connCtx, + func(readCtx context.Context) (websocket.MessageType, []byte, error) { + return readBoundedMessage(readCtx, conn, readLimit, c.drain) + }, + nil, + ) + c.heartbeat.attach(c.reader) + c.keeper = startKeepAlive( + connCtx, conn, c.reader, c.config.keepAliveInterval, c.config.keepAliveTimeout, + wsStatusClientProtocolError, + ) +} + +// preventDial makes sure this call never dials, and reports whether it already +// had. A dial in progress is waited for. +func (c *wsClientCall) preventDial() bool { + c.dialOnce.Do(func() { + c.dialErr = errorf(connect.CodeCanceled, "stream closed before it was used") + }) + return c.wsConn != nil +} + +// connected reports whether the call dialed successfully. It is meaningful +// only after ensureDialed or preventDial has returned. +func (c *wsClientCall) connected() bool { + return c.wsConn != nil +} + +// negotiatedCodec is the codec the server chose, or the send codec until the +// handshake completes. +func (c *wsClientCall) negotiatedCodec() connect.Codec { + return c.codec +} + +// handshakeHeader returns the upgrade response's headers, or nil when there +// was no response. +func (c *wsClientCall) handshakeHeader() http.Header { + if c.response == nil { + return nil + } + return c.response.Header +} + +// nextFrame reads the next frame from a dialed connection. +func (c *wsClientCall) nextFrame(ctx context.Context) (websocket.MessageType, []byte, error) { + return c.reader.next(ctx) +} + +// keepAliveExpired reports whether the server went silent for longer than the +// keep-alive timeout, and what that timeout is. +func (c *wsClientCall) keepAliveExpired() (time.Duration, bool) { + // timedOut tolerates the nil keeper that disabled keep-alives leave; timeout + // does not. + if !c.keeper.timedOut() { + return 0, false + } + return c.keeper.timeout(), true +} + +// closeWith stops the call's background work and closes the connection with +// code and reason. A call that never dialed has nothing to close. +func (c *wsClientCall) closeWith(code websocket.StatusCode, reason string) error { + if c.wsConn == nil { + return nil + } + if c.stopCloseOnDone != nil { + c.stopCloseOnDone() + } + c.keeper.stop() + // Deferred so it runs once the close below has ended the read in flight. + defer c.reader.close() + return closeWithDrain(c.wsConn, c.drain, code, reason) +} + +// send implements [messageSender], writing one message as a single WebSocket +// frame. +func (c *wsClientCall) send(ctx context.Context, text bool, data []byte) (int64, error) { + if err := c.ensureDialed(ctx); err != nil { + return 0, err + } + // Checked here and the write detached: a write under a context that ends + // would drop the connection without the Close frame §13 asks for. + if err := ctx.Err(); err != nil { + return 0, err + } + written, err := writeFrame(context.WithoutCancel(ctx), c.wsConn, text, data) + if err != nil && ctx.Err() == nil { + // A server may end the RPC before reading every request, so a failed + // write is how this end learns the stream is over. As over HTTP, it + // reads as io.EOF and the caller calls Receive for the server's verdict. + return written, fmt.Errorf("%w: %w", io.EOF, err) + } + return written, err +} + +// dialConfig holds what every call from one transport dials with. It is built +// once and never written after, so calls share it without locking. +type dialConfig struct { + // offered lists the tokens to offer, most preferred first: the send + // codec's, then every other registered codec's in registration order. + offered []string + codecs registry[connect.Codec] + handshakeTimeout time.Duration + readLimit int64 + keepAliveInterval time.Duration + keepAliveTimeout time.Duration +} + +// selectedSubprotocol maps the echoed token back to the one this client +// offered, or "" when the server echoed none. Token matching is +// case-insensitive, as the library's own check is. +func (d *dialConfig) selectedSubprotocol(echoed string) string { + for _, token := range d.offered { + if echoed != "" && strings.EqualFold(token, echoed) { + return token + } + } + return "" +} diff --git a/internal/wstransport/client_conn.go b/internal/wstransport/client_conn.go new file mode 100644 index 00000000..f88adb8c --- /dev/null +++ b/internal/wstransport/client_conn.go @@ -0,0 +1,539 @@ +// Copyright 2021-2026 The Connect Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package wstransport + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "io" + "net" + "net/http" + "sync" + "sync/atomic" + "time" + + "connectrpc.com/connect/v2" + "connectrpc.com/connect/v2/internal/connectwire" + "github.com/coder/websocket" +) + +// websocketClientConn is the client's view of one RPC. [clientStream] adapts +// it to [connect.ClientStream]. It mirrors the server: one message per frame, +// with [messageWriter] marshaling outbound and the conn reading inbound. +type websocketClientConn struct { + frameDecoder + + // ctx is the RPC's context. It lives here because Send, Receive, and the + // other stream methods take none. + ctx context.Context //nolint:containedctx + + call *wsClientCall + // localFault records the first failure this end produced rather than read + // off the wire; its message is the close reason. + localFault atomic.Pointer[connect.Error] + + marshaler messageWriter + // openOnce writes the M message that must precede every other message on + // the stream. + openOnce sync.Once + openErr *connect.Error + // callInfo supplies the request headers when M is written, and learns the + // negotiated codec once the handshake completes. Nil when the caller + // supplied none. + callInfo *connect.CallInfo + + // The read side takes one message per WebSocket frame and recognizes the + // server's M and S messages. + + // spec and onProtocolError identify and report a server that frames its + // responses wrongly; see WithClientProtocolErrorHandler. + spec connect.Spec + onProtocolError ClientProtocolErrorHandler + // receiveStats receives each decoded message's size. Nil when the caller + // supplied no CallInfo. + receiveStats *connect.MessageStats + + // endStreamSeen is atomic because Send and CloseSend, which may run + // concurrently with Receive, read it. + endStreamSeen atomic.Bool + // endStreamReceived is set only by a valid S, unlike endStreamSeen, which a + // failed read also sets. CloseResponse may run concurrently with Receive. + endStreamReceived atomic.Bool + // serverFault is set by Receive and read by Close, which the contract + // allows to run concurrently. + serverFault atomic.Pointer[serverFault] + endStreamError *connect.Error + trailer http.Header + // header is written by Receive and read by Close, which the contract + // allows to run concurrently, so metadataMu guards it. + metadataMu sync.Mutex + header http.Header + // sawData gates the ordering rule on the response side: server metadata is + // "leading" only while no body has arrived. + sawData bool + // sawLeadingMetadata records the server's opening M, which must arrive + // exactly once and before anything else. + sawLeadingMetadata bool + + // responseHeader and responseTrailer are guarded by metadataMu, since + // Close may read them while Receive writes them. + responseHeader http.Header + responseTrailer http.Header + + responseHeaderOnce sync.Once + // Close may run concurrently with Receive by contract, and both publish. + // A sync.Once rather than a flag: the ordering that makes a plain bool + // safe today is incidental — Close publishes before touching the conn and + // Receive after — and moving either call would break it silently. + publishOnce sync.Once + publishHeadersOnce sync.Once + // closeResponseOnce makes CloseResponse safe to call from Close and from + // the release that follows S. + closeResponseOnce sync.Once + closeResponseErr error + releaseOnce sync.Once + sendCloseOnce sync.Once + sendCloseErr *connect.Error + // Read by Send, which the contract allows to run concurrently with the + // CloseSend that sets it. + sendClosed atomic.Bool +} + +// open writes the M message that starts the stream. Every message the client +// sends must follow it, so it runs before the first Send and before +// CloseRequest. It is written even when there is no metadata: the server reads +// it to know the stream has begun, and waits for nothing else. +func (c *websocketClientConn) open() *connect.Error { + c.openOnce.Do(func() { + // §6.2: once the server's S has arrived, the client sends nothing more, + // not even the M it had not yet sent. + if c.endStreamSeen.Load() { + return + } + // Checked before anything is written, so a header this client may not + // send fails the call here rather than as the server's protocol error. + requestMeta := c.requestMetadata() + if metadataErr := checkRequestMetadata(requestMeta); metadataErr != nil { + c.openErr = metadataErr + return + } + entries, encodeErr := encodeMetadata(requestMeta) + if encodeErr != nil { + c.openErr = encodeErr + return + } + c.openErr = c.marshaler.writeJSON(c.ctx, markerMetadata, entries) + // Writing M is what dials, so the server's codec choice is known now. + // A failed dial leaves nothing to report. + if !c.call.connected() { + return + } + if c.callInfo != nil { + c.callInfo.Codec = c.call.negotiatedCodec().Name() + } + }) + return c.openErr +} + +// SendHeaders dials and writes the M message that opens the stream, which is +// what actually transmits the request metadata. +func (c *websocketClientConn) SendHeaders() error { + if err := c.call.ensureDialed(c.ctx); err != nil { + return err + } + if err := c.open(); err != nil { + return err + } + return nil // literal nil; a nil *connect.Error is a non-nil error +} + +func (c *websocketClientConn) Send(msg any) error { + // The peer stops reading bodies once it has seen end-of-client-stream, so + // this message would be discarded. connecthttp reports the same + // mistake rather than letting the caller believe it was delivered. + if c.sendClosed.Load() { + return errorf(connect.CodeUnknown, "send after CloseSend: %w", io.EOF) + } + // Writing now would race this end's reply to the server's Close frame, + // and the server discards anything sent after its S. + if c.endStreamSeen.Load() { + return errorf(connect.CodeUnknown, "send after the server ended the stream: %w", io.EOF) + } + if err := c.open(); err != nil { + return err + } + if err := c.marshaler.writeBody(c.ctx, c.call.negotiatedCodec(), msg); err != nil { + c.noteLocalFault(err) + return err + } + return nil // literal nil; a nil *Error is a non-nil error +} + +func (c *websocketClientConn) CloseRequest() error { + // §8: no C once the response stream has ended. Writing one would race + // this end's reply to the server's Close frame. + if c.endStreamSeen.Load() { + c.sendClosed.Store(true) + return nil + } + // A stream that sent no message still has to open before it can end. + if err := c.open(); err != nil { + if c.requestSideEnded(err) { + c.sendClosed.Store(true) + return nil + } + return err + } + c.sendCloseOnce.Do(func() { + defer c.sendClosed.Store(true) + // §6.1: C is a bare control message and always text, whatever the + // codec, so an empty final message is never mistaken for it. + c.sendCloseErr = c.marshaler.send(c.ctx, markerClientEndStream, true, nil) + }) + if c.sendCloseErr != nil && !c.requestSideEnded(c.sendCloseErr) { + return c.sendCloseErr + } + return nil +} + +// requestSideEnded reports a failed write that leaves nothing for CloseRequest +// to close: the server ended the stream, or the call's context did. Receive +// reports why, as it does when connecthttp's CloseSend succeeds in either case. +func (c *websocketClientConn) requestSideEnded(err error) bool { + return errors.Is(err, io.EOF) || c.ctx.Err() != nil +} + +func (c *websocketClientConn) Receive(msg any) error { + // A stream that only receives still has to open: the server will not + // dispatch the handler until the opening metadata arrives. If the server + // has already ended the stream, its verdict is still there to read. + if err := c.open(); err != nil && !errors.Is(err, io.EOF) { + return err + } + err := c.receive(msg) + if err == nil { + return nil + } + // The trailers go on the conn, which the transport publishes to CallInfo, + // rather than on the error. + if c.endStreamSeen.Load() { + c.metadataMu.Lock() + mergeHeaders(c.responseTrailer, c.trailer) + c.metadataMu.Unlock() + if c.endStreamReceived.Load() { + c.releaseAfterEndOfStream() + } + if serverErr := c.endStreamError; serverErr != nil { + return serverErr + } + } + return err +} + +// releaseAfterEndOfStream closes the connection once S has arrived. A caller +// that reads to io.EOF need not call Close, so nothing else would release it +// from a server that does not close first (§9.1 is only a SHOULD). +func (c *websocketClientConn) releaseAfterEndOfStream() { + c.releaseOnce.Do(func() { + go func() { _ = c.CloseResponse() }() + }) +} + +// preventDial makes sure this stream never dials, and reports whether it +// already had. +func (c *websocketClientConn) preventDial() bool { + return c.call.preventDial() +} + +// noteLocalFault records an error this end produced while encoding, as opposed +// to one the wire reported. A failed write is not one: it says the connection +// or the peer went, which §13 has its own codes for. +func (c *websocketClientConn) noteLocalFault(err *connect.Error) { + if err == nil { + return + } + // Internal is a codec that is missing or refused the message; the send + // path's ResourceExhausted is sendMaxBytes, which only this end imposes and + // only on its own writes. A failed write reports neither. + if err.Code() == connect.CodeInternal || err.Code() == connect.CodeResourceExhausted { + c.localFault.CompareAndSwap(nil, err) + } +} + +func (c *websocketClientConn) CloseResponse() error { + c.closeResponseOnce.Do(func() { c.closeResponseErr = c.closeResponse() }) + return c.closeResponseErr +} + +func (c *websocketClientConn) closeResponse() error { + closeErr := c.call.closeWith(c.closeStatus()) + // The background reader answers the server's close frame and closes the + // connection itself, so an already-closed connection is a completed + // handshake rather than a failure. + if errors.Is(closeErr, net.ErrClosed) { + return nil + } + // §13: S completed the RPC, so a server that then drops the connection + // without a closing handshake has not failed it. + if c.endStreamReceived.Load() { + return nil + } + if closeErr == nil { + return nil + } + // §13.1: the connection ended without S, so the RPC failed. It is + // Unavailable unless this end canceled it or its deadline passed. + if ctxErr := c.ctx.Err(); ctxErr != nil { + return wsContextError(ctxErr) + } + return errorf(connect.CodeUnavailable, "close WebSocket without EndStreamMessage: %v", closeErr) +} + +// closeStatus picks the code and reason this end closes the connection with. +func (c *websocketClientConn) closeStatus() (websocket.StatusCode, string) { + // A peer fault wins over a local one: it is what the server can act on. + if fault := c.serverFault.Load(); fault != nil { + return fault.code, closeReason(fault.err.Message()) + } + if localErr := c.localFault.Load(); localErr != nil { + // §13.1: the RPC ended on an unexpected condition at this end, not on + // anything the server did. Sent unconditionally — the peer behaved, so + // the closing handshake has nothing queued to drain, and the ordinary + // 1000 below costs the same handshake anyway. §13 requires the reason. + return wsStatusClientProtocolError, closeReason(localErr.Message()) + } + // Best-effort clean close. Sending 1000 Normal Closure is correct even if + // Receive has not yet observed the EndStream: the server's completion path + // has already sent its own close, and Close is a no-op once the handshake + // has happened. + return websocket.StatusNormalClosure, "" +} + +// Unmarshal records whether a failure was the peer's doing, which decides how +// the connection is torn down. +func (c *websocketClientConn) receive(message any) *connect.Error { + for { + c.fault = faultNone + wasMetadata, err := c.unmarshal(message) + // A classified fault is a protocol error whatever its code: §5 has the + // client close with 3102 for it, not end the RPC with 1000. + if err != nil && (c.fault != faultNone || peerFault(err)) { + c.serverFault.CompareAndSwap(nil, &serverFault{err: err, code: clientCloseCode(c.fault)}) + } + // Gated on the classification rather than peerFault; see the server + // side. Observation only — err is returned unchanged. + if c.fault != faultNone && c.onProtocolError != nil { + c.onProtocolError(c.spec, c.fault, err) + } + // An M carries no message for the caller, so read again rather than + // return one that was never decoded. + if err == nil && wasMetadata { + continue + } + return err + } +} + +// readFailure turns a failed read into the RPC's error. Every failure ends the +// response stream. +func (c *websocketClientConn) readFailure(readerErr error) *connect.Error { + c.endStreamSeen.Store(true) + if timeout, expired := c.call.keepAliveExpired(); expired { + c.endStreamError = errorf( + connect.CodeUnavailable, + "server sent nothing for %v, not even a Pong (keep-alive timeout)", timeout, + ) + return c.endStreamError + } + // A read that failed while the context was done is cancellation, not a + // transport fault. Report ctx.Err so callers see Canceled or + // DeadlineExceeded rather than whatever the socket happened to say. + if ctxErr := c.ctx.Err(); ctxErr != nil { + c.endStreamError = wsContextError(ctxErr) + return c.endStreamError + } + // The socket's read deadline and the context's timer are separate + // clocks, so the read can fail a moment before ctx.Err is set. A read + // that failed at or past the deadline is the deadline whichever fired + // first; calling it Unavailable would invite a retry that has no time + // left to run. + if deadline, ok := c.ctx.Deadline(); ok && !time.Now().Before(deadline) { + c.endStreamError = errorf(connect.CodeDeadlineExceeded, "%w", context.DeadlineExceeded) + return c.endStreamError + } + if isCleanWebSocketClose(readerErr) { + // A clean close with no EndStreamMessage means the RPC never reached + // a verdict. Unavailable, not EOF: the caller has no result, and + // retrying is reasonable. + c.endStreamError = errorf( + connect.CodeUnavailable, + "server closed WebSocket without EndStreamMessage", + ) + return c.endStreamError + } + // Classified like any other peer fault: a server sending more than this + // client agreed to read is the server's mistake, and the monitor should + // see it under the same name the server uses. + if errors.Is(readerErr, errMessageTooBig) { + c.fault = FaultSizeLimit + return exceedsReadLimit(c.readMaxBytes) + } + if limitErr := peerRejectedAsTooBig(readerErr); limitErr != nil { + c.fault = FaultSizeLimit + return limitErr + } + // §13: one of the two close codes a client may take an outcome from. The + // server failed the connection over a text message this client sent. + if websocket.CloseStatus(readerErr) == websocket.StatusInvalidFramePayloadData { + return errorf( + connect.CodeInternal, + "server rejected a text message from this client as invalid UTF-8: %w", readerErr, + ) + } + // %v, not %w: the cause is often io.EOF, which callers read as a normal + // end of stream rather than a failure. + return errorf(connect.CodeUnavailable, "read websocket message: %v", readerErr) +} + +// unmarshal reads and dispatches one message, and reports whether it was an M. +func (c *websocketClientConn) unmarshal(message any) (wasMetadata bool, err *connect.Error) { + if err := c.call.ensureDialed(c.ctx); err != nil { + c.endStreamSeen.Store(true) + c.endStreamError = err + return false, err + } + if c.endStreamSeen.Load() { + return false, errorf(connect.CodeUnknown, "%w", io.EOF) + } + wire, readErr := c.nextMessage() + if readErr != nil { + return false, readErr + } + return wire.marker == markerMetadata, c.dispatch(wire, message) +} + +// nextMessage reads one frame and returns the message it carries. +func (c *websocketClientConn) nextMessage() (wireMessage, *connect.Error) { + messageType, frame, readerErr := c.call.nextFrame(c.ctx) + if readerErr != nil { + return wireMessage{}, c.readFailure(readerErr) + } + wire, parseErr := c.parseFrame(messageType, frame) + if c.fault == FaultTextEncoding { + c.endStreamSeen.Store(true) + } + return wire, parseErr +} + +// dispatch interprets one message and decodes its payload into message. +func (c *websocketClientConn) dispatch(wire wireMessage, message any) *connect.Error { + // Every response stream opens with exactly one M, so anything else first + // means the peer is not speaking this protocol and there is no partial + // state worth keeping. + if !c.sawLeadingMetadata && wire.marker != markerMetadata { + return c.fail( + FaultMetadata, + "server's first message must be M; got %s", markerName(wire.marker), + ) + } + + switch wire.marker { + case markerClientEndStream: + return c.fail(FaultMarker, "server sent %s, which only a client may send", markerName(wire.marker)) + case markerMetadata: + // §6.1: M and S are always JSON, and a binary frame says the payload + // is not. + if !wire.text { + return c.fail(FaultFrameType, "server sent M in a binary frame; expected a text frame") + } + if mergeErr := c.mergeLeadingMetadata(wire.payload); mergeErr != nil { + return mergeErr + } + return nil + case markerServerEndStream: + if !wire.text { + return c.fail(FaultFrameType, "server sent S in a binary frame; expected a text frame") + } + return c.endStream(wire.payload) + case markerBody: + c.sawData = true + if err := c.decodeBody(c.ctx, c.call.negotiatedCodec(), wire, message); err != nil { + return err + } + if c.receiveStats != nil { + *c.receiveStats = connect.MessageStats{Size: len(wire.payload)} + } + return nil + default: + return c.fail(FaultMarker, "server sent unknown marker %s", markerName(wire.marker)) + } +} + +// endStream records the verdict an S message carries, and returns io.EOF as +// the end of the response stream. +func (c *websocketClientConn) endStream(payload []byte) *connect.Error { + // Parsed unconditionally, so a bare S fails here exactly as a zero-length + // end-of-stream payload fails in Connect's HTTP streaming protocol. + // §9: the payload is an EndStreamResponse, a JSON object. json accepts + // null for a struct, which would read as success. + if trimmed := bytes.TrimSpace(payload); len(trimmed) > 0 && trimmed[0] != '{' { + return c.fail(FaultMetadata, "S message is not a JSON EndStreamMessage object; the smallest is {}") + } + var end connectwire.EndStreamMessage + if err := json.Unmarshal(payload, &end); err != nil { + return c.fail(FaultMetadata, "unmarshal EndStreamMessage: %w", err) + } + trailer, decodeErr := decodeTrailer(end.Trailer) + if decodeErr != nil { + c.fault = FaultMetadata + return decodeErr + } + c.endStreamSeen.Store(true) + c.endStreamReceived.Store(true) + c.trailer = trailer + c.endStreamError = end.Error.AsError() + return errorf(connect.CodeUnknown, "%w", io.EOF) +} + +// serverFault is the first failure the server's framing caused: its message is +// the close reason, and code the close code. +type serverFault struct { + err *connect.Error + code websocket.StatusCode +} + +// clientCloseCode is the code a client closes with for a server's fault. +// §6.1 requires 1007 for invalid UTF-8, and §12.1 asks a non-browser client, +// which this is, for 1009 on an oversized message. Everything else is 3102. +func clientCloseCode(fault ProtocolFault) websocket.StatusCode { + switch fault { + case FaultTextEncoding: + return websocket.StatusInvalidFramePayloadData + case FaultSizeLimit: + return websocket.StatusMessageTooBig + case faultNone, FaultMarker, FaultFrameType, FaultMetadata, FaultMessageEncoding: + return wsStatusClientProtocolError + } + return wsStatusClientProtocolError +} + +func isCleanWebSocketClose(err error) bool { + // Not a switch: the repo's exhaustive linter wants every StatusCode listed, + // and enumerating thirteen irrelevant close codes would obscure the rule. + status := websocket.CloseStatus(err) + return status == websocket.StatusNormalClosure || status == websocket.StatusGoingAway +} diff --git a/internal/wstransport/client_handshake.go b/internal/wstransport/client_handshake.go new file mode 100644 index 00000000..c4ca375c --- /dev/null +++ b/internal/wstransport/client_handshake.go @@ -0,0 +1,202 @@ +// Copyright 2021-2026 The Connect Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package wstransport + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "strings" + + "connectrpc.com/connect/v2" + "connectrpc.com/connect/v2/internal/connectwire" + "github.com/coder/websocket" +) + +// handshake dials and checks what the server agreed to. A connection it +// rejects is closed. +func (c *wsClientCall) handshake(ctx context.Context) (*websocket.Conn, *connect.Error) { + // The handshake gets its own deadline; the connection outlives it. + dialCtx := ctx + if c.config.handshakeTimeout > 0 { + var cancelDial context.CancelFunc + dialCtx, cancelDial = context.WithTimeout(ctx, c.config.handshakeTimeout) + defer cancelDial() + } + conn, response, err := websocket.Dial(dialCtx, c.url.String(), c.dialOptions) + c.response = response + var failedBody []byte + if response != nil && response.Body != nil { + // We only need the upgrade response's headers; close the body to + // avoid leaking it. On a failed handshake the library has replaced + // it with the first KiB, which may hold a Connect error. + if err != nil { + failedBody, _ = io.ReadAll(response.Body) + } + _ = response.Body.Close() + } + if err != nil { + return nil, dialError(err, response, failedBody) + } + // The library has already failed a handshake that echoed a token this + // client did not offer (RFC 6455 §4.1). §4.3 fails one that echoed none + // the same way: the handshake failed, so no Close frame is sent. + token := c.config.selectedSubprotocol(conn.Subprotocol()) + if token == "" { + _ = conn.CloseNow() + return nil, errorf( + connect.CodeInternal, + "server echoed no Sec-WebSocket-Protocol (offered %s)", + strings.Join(c.config.offered, ", "), + ) + } + // Every offered token names a codec this client holds. + if codec, ok := c.config.codecs.get(codecForSubprotocol(token)); ok { + c.codec = codec + } + if takeoverErr := checkNoContextTakeover(response); takeoverErr != nil { + _ = closeClientWithError( + conn, c.drain, + "permessage-deflate requires client_no_context_takeover and server_no_context_takeover", + ) + return nil, takeoverErr + } + return conn, nil +} + +// dialError turns a failed handshake into the RPC's error. §4.5: a Connect +// error in the response body wins, then Connect-over-HTTP's status mapping. A +// 101 that still failed broke the handshake's own rules, such as echoing a +// token this client did not offer, which is the server's fault: Internal. +func dialError(err error, response *http.Response, body []byte) *connect.Error { + switch { + case errors.Is(err, context.Canceled): + return errorf(connect.CodeCanceled, "WebSocket upgrade canceled: %w", err) + case errors.Is(err, context.DeadlineExceeded): + return errorf(connect.CodeDeadlineExceeded, "WebSocket upgrade deadline exceeded: %w", err) + } + // Callers read io.EOF as a clean end of stream, so a connection dropped + // mid-handshake is reported as unexpected, as connecthttp does. + if errors.Is(err, io.EOF) { + err = fmt.Errorf("%s: %w", err.Error(), io.ErrUnexpectedEOF) + } + if response == nil { + return errorf(connect.CodeUnavailable, "WebSocket upgrade failed: %w", err) + } + if response.StatusCode == http.StatusSwitchingProtocols { + return errorf(connect.CodeInternal, "WebSocket upgrade failed: %w", err) + } + if wireErr := handshakeWireError(response, body); wireErr != nil { + return wireErr + } + return errorf( + httpToCode(response.StatusCode), + "WebSocket upgrade failed: HTTP %s: %w", + response.Status, err, + ) +} + +// handshakeWireError reads a Connect error from a rejected handshake's body, +// or returns nil if the body is not one. A body without a recognizable code +// is not one either, so the status mapping still applies to it. +func handshakeWireError(response *http.Response, body []byte) *connect.Error { + mediaType := strings.TrimSpace(strings.Split(response.Header.Get("Content-Type"), ";")[0]) + if !strings.EqualFold(mediaType, "application/json") || len(body) == 0 { + return nil + } + var wireErr connectwire.WireError + if json.Unmarshal(body, &wireErr) == nil && wireErr.Code != 0 { + return wireErr.AsError() + } + return nil +} + +// httpToCode maps an HTTP status to a Connect code. Copied from connecthttp, +// where it is unexported. +// +// https://github.com/grpc/grpc/blob/master/doc/http-grpc-status-mapping.md +// Note that this is NOT the inverse of the gRPC-to-HTTP or Connect-to-HTTP +// mappings. +func httpToCode(httpCode int) connect.Code { + // Literals are easier to compare to the specification (vs named + // constants). + switch httpCode { + case 400: + return connect.CodeInternal + case 401: + return connect.CodeUnauthenticated + case 403: + return connect.CodePermissionDenied + case 404: + return connect.CodeUnimplemented + case 429: + return connect.CodeUnavailable + case 502, 503, 504: + return connect.CodeUnavailable + default: + return connect.CodeUnknown + } +} + +// checkNoContextTakeover refuses a handshake that negotiated +// permessage-deflate with a compression context shared across messages. +// +// A shared context leaks plaintext between messages whenever attacker- +// influenced and secret data travel on one connection — the CRIME/BREACH +// family. The server is required to impose no-context-takeover, but a client +// that trusts it to have done so is protected only as far as the peer is +// conforming, and the client's own plaintext is what leaks. +// +// No extension at all is fine: nothing is compressed, so nothing leaks. +func checkNoContextTakeover(response *http.Response) *connect.Error { + if response == nil { + return nil + } + for _, value := range response.Header.Values(wsHeaderExtensions) { + for extension := range strings.SplitSeq(value, ",") { + parameters := strings.Split(extension, ";") + if strings.TrimSpace(parameters[0]) != "permessage-deflate" { + continue + } + var client, server bool + for _, parameter := range parameters[1:] { + switch strings.TrimSpace(parameter) { + case "client_no_context_takeover": + client = true + case "server_no_context_takeover": + server = true + } + } + if !client || !server { + return errorf( + connect.CodeInternal, + "server negotiated %q without no-context-takeover in both directions; "+ + "a shared compression context leaks plaintext across messages", + strings.TrimSpace(extension), + ) + } + } + } + return nil +} + +// closeClientWithError ends a client's connection with 3102. The code alone +// cannot tell a server what went wrong, so §13 requires the reason. +func closeClientWithError(conn *websocket.Conn, limiter *drainLimiter, reason string) error { + return closeWithDrain(conn, limiter, wsStatusClientProtocolError, closeReason(reason)) +} diff --git a/internal/wstransport/client_metadata.go b/internal/wstransport/client_metadata.go new file mode 100644 index 00000000..98f6af04 --- /dev/null +++ b/internal/wstransport/client_metadata.go @@ -0,0 +1,159 @@ +// Copyright 2021-2026 The Connect Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package wstransport + +import ( + "maps" + "net/http" + + "connectrpc.com/connect/v2" +) + +// requestMetadata reads the caller's request headers as they stand when M is +// written, which is the first Send as it is over HTTP. +// +// They travel in M and nowhere else. Copying them onto the handshake too would +// put the same keys on two channels, and the client's own M would be shadowed +// by its own headers the moment the two disagreed. +func (c *websocketClientConn) requestMetadata() http.Header { + header := make(http.Header, 8) + if c.callInfo == nil { + return header + } + for key, values := range c.callInfo.RequestHeader().All() { + header[http.CanonicalHeaderKey(key)] = append(header[http.CanonicalHeaderKey(key)], values...) + } + return header +} + +// ResponseHeader returns a copy of the response headers, safe to read while +// Receive runs. +func (c *websocketClientConn) ResponseHeader() http.Header { + // Dialed before locking: the handshake can take as long as its timeout, and + // Receive and ResponseTrailer would wait behind it. + dialErr := c.call.ensureDialed(c.ctx) + c.metadataMu.Lock() + defer c.metadataMu.Unlock() + // Leading-Metadata replaces same-key handshake values rather than appending + // to them, so this runs after the 101's headers and assigns rather than + // merging — which also keeps a second call from duplicating them. + c.responseHeaderOnce.Do(func() { + if dialErr != nil { + return + } + for key, values := range c.call.handshakeHeader() { + if isWebSocketProtocolHeader(key) { + continue + } + c.responseHeader[key] = values + } + }) + maps.Copy(c.responseHeader, c.header) + return c.responseHeader.Clone() +} + +// ResponseTrailer returns a copy of the response trailers, safe to read while +// Receive runs. +func (c *websocketClientConn) ResponseTrailer() http.Header { + c.metadataMu.Lock() + defer c.metadataMu.Unlock() + return c.responseTrailer.Clone() +} + +// mergeLeadingMetadata folds the server's M message into the response headers. +// +// Exactly one arrives, and it opens the response stream. A second would mean +// the server is rewriting headers the application may already have read, which +// is the same race the request side refuses. +func (c *websocketClientConn) mergeLeadingMetadata(payload []byte) *connect.Error { + if c.sawData { + return c.fail( + FaultMetadata, + "server sent M after a body; metadata is leading only before the first one", + ) + } + if c.sawLeadingMetadata { + return c.fail( + FaultMetadata, + "server sent a second M message; a stream carries exactly one, and it opens the stream", + ) + } + c.sawLeadingMetadata = true + entries, parseErr := c.metadataEntries(payload) + if parseErr != nil { + return parseErr + } + meta, decodeErr := c.metadataHeader(entries) + if decodeErr != nil { + return decodeErr + } + c.metadataMu.Lock() + defer c.metadataMu.Unlock() + if c.header == nil { + c.header = make(http.Header, len(meta)) + } + maps.Copy(c.header, meta) + return nil +} + +// publishMetadata copies the response metadata onto the call's +// [connect.CallInfo], where callers read it. It runs once. +// +// The write happens during Receive, so a caller reading CallInfo from another +// goroutine while receiving on the same stream races it. That is not specific +// to this transport — connecthttp writes the same object from inside its own +// Receive — so it is left to be fixed where connect.Header is defined rather +// than papered over here; see "Current limitations" in +// docs/websocket-transport-design.md. +func (c *websocketClientConn) publishMetadata() { + c.publishOnce.Do(func() { + if c.callInfo == nil { + return + } + c.publishHeaders() + for key, values := range c.ResponseTrailer() { + c.callInfo.ResponseTrailer().SetValues(key, values) + } + // Identity at the Connect layer: permessage-deflate is below the protocol. + c.callInfo.ResponseEncoding = connect.CompressionNameIdentity + }) +} + +// publishHeaders copies the response headers onto the call's +// [connect.CallInfo]. It runs once. +func (c *websocketClientConn) publishHeaders() { + c.publishHeadersOnce.Do(func() { + if c.callInfo == nil { + return + } + for key, values := range c.ResponseHeader() { + c.callInfo.ResponseHeader().SetValues(key, values) + } + }) +} + +func isWebSocketProtocolHeader(key string) bool { + switch http.CanonicalHeaderKey(key) { + case wsHeaderUpgrade, + wsHeaderConnection, + "Sec-Websocket-Accept", + wsHeaderProtocol, + wsHeaderExtensions, + "Sec-Websocket-Version", + "Sec-Websocket-Key": + return true + } + return false +} diff --git a/internal/wstransport/client_stream.go b/internal/wstransport/client_stream.go new file mode 100644 index 00000000..0fac9756 --- /dev/null +++ b/internal/wstransport/client_stream.go @@ -0,0 +1,87 @@ +// Copyright 2021-2026 The Connect Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package wstransport + +import ( + "errors" + "io" + + "connectrpc.com/connect/v2" +) + +// clientStream adapts [websocketClientConn] to [connect.ClientStream]. +type clientStream struct { + conn *websocketClientConn + singleResponse bool + // received marks the one response a single-response call has read. + received bool +} + +func (s *clientStream) SendHeaders() error { + return s.conn.SendHeaders() +} + +func (s *clientStream) Send(msg any) error { + return s.conn.Send(msg) +} + +func (s *clientStream) CloseSend() error { + return s.conn.CloseRequest() +} + +func (s *clientStream) Receive(msg any) error { + err := s.conn.Receive(msg) + if err != nil { + // Reading to completion is what makes response metadata available. + s.conn.publishMetadata() + // §6.2: a unary or client-streaming call returns exactly one message, + // so a successful end with none is a cardinality error, as over HTTP. + if s.singleResponse && !s.received && errors.Is(err, io.EOF) { + return connect.Errorf(connect.CodeUnimplemented, "unary stream has zero messages") + } + return err + } + // Leading metadata has arrived by now, and connecthttp makes it readable at + // exactly this point: after the first Receive, not before. + s.conn.publishHeaders() + if s.singleResponse { + s.received = true + // Such a caller receives exactly once, so nothing would ever read the + // end-of-stream message — and the trailers it carries would be lost. A + // server-streaming caller reaches it by reading to io.EOF. A second + // message where the S belongs is decoded into msg only to be refused. + endErr := s.conn.Receive(msg) + s.conn.publishMetadata() + if endErr == nil { + return connect.Errorf(connect.CodeUnimplemented, "unary stream has multiple messages") + } + if !errors.Is(endErr, io.EOF) { + return endErr + } + } + return nil +} + +// Close ends the stream without sending C: a client that closes before S +// without sending C cancels the RPC (§8), and one that has S needs no C. A +// stream that never dialed is closed without dialing. +func (s *clientStream) Close() error { + dialed := s.conn.preventDial() + s.conn.publishMetadata() + if !dialed { + return nil + } + return s.conn.CloseResponse() +} diff --git a/internal/wstransport/clientclose_ext_test.go b/internal/wstransport/clientclose_ext_test.go new file mode 100644 index 00000000..2ad67ac8 --- /dev/null +++ b/internal/wstransport/clientclose_ext_test.go @@ -0,0 +1,90 @@ +// Copyright 2021-2026 The Connect Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package wstransport_test + +import ( + "context" + "net" + "testing" + "time" + + "connectrpc.com/connect/v2" + "connectrpc.com/connect/v2/internal/assert" + pingv1 "connectrpc.com/connect/v2/internal/gen/connect/ping/v1" + "connectrpc.com/connect/v2/internal/gen/connect/ping/v1/pingv1connect" + "connectrpc.com/connect/v2/internal/wstransport" +) + +// closeWatchingServer accepts one upgrade, opens the stream with an empty M, +// and reports the code of the client's Close frame. +func closeWatchingServer(tb testing.TB) (string, <-chan int) { + tb.Helper() + listener, err := (&net.ListenConfig{}).Listen(tb.Context(), "tcp", "127.0.0.1:0") + assert.Nil(tb, err) + tb.Cleanup(func() { _ = listener.Close() }) + closes := make(chan int, 1) + go func() { + conn, reader := acceptRawUpgrade(tb, listener) + if _, err := conn.Write(serverFrame(true, []byte("M[]"))); err != nil { + return + } + _, closeCode, _ := watchFrames(reader, nil) + closes <- closeCode + }() + return "http://" + listener.Addr().String(), closes +} + +// §11.1 and §13: a client whose call ends before S, by cancellation or by its +// deadline, closes with 1000 rather than dropping the connection, so the +// server can tell it was canceled. +func TestClientClosesWithNormalClosureWhenItsCallEnds(t *testing.T) { + t.Parallel() + for _, test := range []struct { + name string + end func(context.CancelFunc) + timeout time.Duration + wantCode connect.Code + }{ + {name: "canceled", end: func(cancel context.CancelFunc) { cancel() }, wantCode: connect.CodeCanceled}, + {name: "deadline", end: func(context.CancelFunc) {}, timeout: 100 * time.Millisecond, wantCode: connect.CodeDeadlineExceeded}, + } { + t.Run(test.name, func(t *testing.T) { + t.Parallel() + url, closes := closeWatchingServer(t) + transport, err := wstransport.NewTransport(url) + assert.Nil(t, err) + client := pingv1connect.NewPingServiceClient(connect.NewClient(transport)) + ctx, cancel := context.WithCancel(t.Context()) + defer cancel() + if test.timeout > 0 { + ctx, cancel = context.WithTimeout(t.Context(), test.timeout) + defer cancel() + } + stream, err := client.CumSum(ctx) + assert.Nil(t, err) + assert.Nil(t, stream.Send(&pingv1.CumSumRequest{Number: 1})) + test.end(cancel) + _, err = stream.Receive() + assert.Equal(t, connect.CodeOf(err), test.wantCode) + + select { + case closeCode := <-closes: + assert.Equal(t, closeCode, 1000) + case <-time.After(wsTestReadTimeout): + t.Fatal("server never saw the connection end") + } + }) + } +} diff --git a/internal/wstransport/clientstream_ext_test.go b/internal/wstransport/clientstream_ext_test.go new file mode 100644 index 00000000..99147151 --- /dev/null +++ b/internal/wstransport/clientstream_ext_test.go @@ -0,0 +1,202 @@ +// Copyright 2021-2026 The Connect Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package wstransport_test + +import ( + "context" + "errors" + "io" + "strings" + "testing" + "time" + + "connectrpc.com/connect/v2" + "connectrpc.com/connect/v2/connecthttp" + "connectrpc.com/connect/v2/internal/assert" + pingv1 "connectrpc.com/connect/v2/internal/gen/connect/ping/v1" + "connectrpc.com/connect/v2/internal/gen/connect/ping/v1/pingv1connect" + "github.com/coder/websocket" + "google.golang.org/protobuf/proto" +) + +// The shape of a client-streaming RPC on the wire: an M message, several +// values, a C message; then the server's own M, one response message, one S, +// and the server's close. Written as a reference trace, because a second +// implementation has to reproduce it exactly. +func TestClientStreamingWireSequence(t *testing.T) { + t.Parallel() + httpServer := newServerFor(t, scriptedServer{}) + client := dialBrowserClient(t, httpServer, pingv1connect.PingServiceSumProcedure) + + var want int64 + for _, value := range []int64{1, 2, 3, 4} { + payload, err := proto.Marshal(&pingv1.SumRequest{Number: value}) + assert.Nil(t, err) + client.writeProto(t, payload) + want += value + } + // §6.1: C is bare and always text, whatever the codec. + client.writeJSON(t, wireClientEndStream, nil) + + // The response is three messages: the server's own opening M, the body, + // then the end-of-stream message carrying the trailers. A client that + // stops after the body silently drops them. + marker, payload, text := client.readMessage(t) + assert.Equal(t, marker, wireMetadata) + assert.True(t, text) // metadata is JSON + assert.Equal(t, string(payload), "[]") // this handler sets none + + marker, payload, text = client.readMessage(t) + assert.Equal(t, marker, wireBody) + assert.False(t, text) // Protobuf body, binary frame + var response pingv1.SumResponse + assert.Nil(t, proto.Unmarshal(payload, &response)) + assert.Equal(t, response.Sum, want) + + marker, payload, text = client.readMessage(t) + assert.Equal(t, marker, wireServerEndStream) + assert.True(t, text) // EndStreamMessage JSON, text frame + assert.True(t, strings.Contains(string(payload), "set-by-handler")) + assert.True(t, !strings.Contains(string(payload), "error")) + + // Nothing follows but the close, which the server sends itself: the RPC is + // over, and one connection carries only the one RPC. + readCtx, cancelRead := readContext(t) + defer cancelRead() + _, _, err := client.conn.Read(readCtx) + assert.NotNil(t, err) + assert.Equal(t, websocket.CloseStatus(err), websocket.StatusNormalClosure) +} + +// §6.1: C carries no payload and is always text, so an empty final message +// can never be mistaken for it. A C with a payload, or one in a binary frame, +// is a protocol error rather than a final message to deliver. +func TestEndOfClientStreamMustBeBareText(t *testing.T) { + t.Parallel() + for _, test := range []struct { + name string + text bool + want string + }{ + {name: "payload in a binary frame", want: "C in a binary frame; expected a text frame"}, + {name: "payload in a text frame", text: true, want: "C carries none"}, + } { + t.Run(test.name, func(t *testing.T) { + t.Parallel() + httpServer := newHybridServer(t, pingServer{}) + conn := dialCumSum(t, httpServer, "") + payload, err := proto.Marshal(&pingv1.CumSumRequest{Number: 1}) + assert.Nil(t, err) + if test.text { + payload = []byte(`{"number":"1"}`) + } + sendWireMessage(t, conn, test.text, wireClientEndStream, payload) + + data := readServerOpening(t, conn) + assert.Equal(t, data[0], wireServerEndStream) + assert.True(t, strings.Contains(string(data), "internal")) + assert.True(t, strings.Contains(string(data), test.want)) + }) + } +} + +// The same exchange through the generated client, which is what a Go caller +// actually writes. CloseAndReceive sends End-Of-Client-Stream, reads the single +// response, and reads the end-of-stream message behind it so the trailers survive. +func TestClientStreamingThroughTheGeneratedClient(t *testing.T) { + t.Parallel() + httpServer := newServerFor(t, scriptedServer{}) + transport := connecthttp.NewTransport( + httpServer.Client(), + httpServer.URL, + connecthttp.WithWebSocket(connecthttp.SelectStreaming), + ) + client := pingv1connect.NewPingServiceClient(connect.NewClient(transport)) + + ctx, info := connect.NewClientContext(t.Context()) + stream, err := client.Sum(ctx) + assert.Nil(t, err) + var want int64 + for _, value := range []int64{1, 2, 3, 4} { + assert.Nil(t, stream.Send(&pingv1.SumRequest{Number: value})) + want += value + } + response, err := stream.CloseAndReceive() + assert.Nil(t, err) + assert.Equal(t, response.Sum, want) + assert.Equal(t, info.ResponseTrailer().Get(trailerKey), "set-by-handler") +} + +// A client that keeps sending after its C message must not stall. The server +// has stopped delivering those messages, but it goes on reading and discarding +// them, so the peer's writes never block on a full socket buffer. +// +// The handler lingers on purpose, holding the connection open: once it +// returns, the connection closes and the writes drain into nothing, which +// would hide a stall. The assertion is that the writes finish while the +// handler is still in that window — without the drain they instead wait it +// out, because a full buffer only clears when the connection dies. +func TestMessagesAfterEndOfClientStreamAreDiscarded(t *testing.T) { + t.Parallel() + const linger = 5 * time.Second + handlerDone := make(chan struct{}) + httpServer := newHybridServer2(t, lingeringServer{linger: linger, done: handlerDone}) + conn := dialCumSum(t, httpServer, "") + conn.SetReadLimit(-1) + sendProtoBody(t, conn, &pingv1.CumSumRequest{Number: 1}) + sendJSONMessage(t, conn, wireClientEndStream, nil) + + // More than any socket buffer will hold. + ctx, cancel := context.WithTimeout(t.Context(), 30*time.Second) + defer cancel() + body := make([]byte, 64*1024) + for range 256 { + if err := conn.Write(ctx, websocket.MessageBinary, append([]byte("B"), body...)); err != nil { + t.Fatalf("write blocked or failed after C: %v", err) + } + } + + select { + case <-handlerDone: + t.Fatal("writes after C outlasted the handler, so nothing was draining them") + default: + } +} + +// lingeringServer reads to EOF and then stays in the handler, holding the +// connection open, before signalling that it has left. +type lingeringServer struct { + pingv1connect.UnimplementedPingServiceHandler + + linger time.Duration + done chan struct{} +} + +func (s lingeringServer) CumSum( + _ context.Context, + stream pingv1connect.PingServiceCumSumServerStream, +) error { + for { + if _, err := stream.Receive(); err != nil { + if errors.Is(err, io.EOF) { + break + } + return err + } + } + time.Sleep(s.linger) + close(s.done) + return nil +} diff --git a/internal/wstransport/close_test.go b/internal/wstransport/close_test.go new file mode 100644 index 00000000..203e028e --- /dev/null +++ b/internal/wstransport/close_test.go @@ -0,0 +1,254 @@ +// Copyright 2021-2026 The Connect Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package wstransport + +import ( + "context" + "errors" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + "unicode/utf8" + + "connectrpc.com/connect/v2" + "connectrpc.com/connect/v2/connectproto" + "connectrpc.com/connect/v2/internal/assert" + pingv1 "connectrpc.com/connect/v2/internal/gen/connect/ping/v1" + "github.com/coder/websocket" +) + +// wsTestReadTimeout bounds a raw-wire read: a backstop against a hang, not a +// latency assertion. The external test package has its own; the two packages +// cannot share one. +const wsTestReadTimeout = 10 * time.Second + +// deadSender fails every write, standing in for a socket whose peer has gone. +// A real disconnect cannot be provoked reliably — whether a write lands in a +// buffer or meets a reset is a matter of timing — so the condition is supplied +// directly here. +type deadSender struct{} + +func (deadSender) reason() string { + return "write tcp 127.0.0.1:8080->127.0.0.1:1234: write: broken pipe" +} + +func (d deadSender) send(context.Context, bool, []byte) (int64, error) { + return 0, errors.New(d.reason()) +} + +// A verdict that cannot be delivered because the client already left is not a +// server error. Reporting it would log one for every abandoned subscription. +func TestCloseSwallowsTheWriteErrorWhenThePeerIsGone(t *testing.T) { + t.Parallel() + for _, test := range []struct { + name string + sawEnd bool + eof bool + wantSwallow bool + }{ + { + name: "peer left without C", + eof: true, + wantSwallow: true, + }, + { + name: "peer sent C and is waiting for the verdict", + eof: true, + sawEnd: true, + }, + { + name: "read path never reached the end, so nothing says the peer left", + }, + } { + t.Run(test.name, func(t *testing.T) { + t.Parallel() + conn := &websocketHandlerConn{ + eof: test.eof, + sawEndOfClientStream: test.sawEnd, + } + writeErr := errorf(connect.CodeUnknown, "write message: %s", deadSender{}.reason()) + got := conn.terminalWriteError(writeErr) + if test.wantSwallow { + assert.Nil(t, got) + return + } + assert.NotNil(t, got) + assert.Equal(t, got.Code(), connect.CodeUnknown) + }) + } +} + +// connPair returns the two ends of a live WebSocket, so a test can drive one +// side through the handler's own types and observe the other as a peer does. +func connPair(tb testing.TB) (server, client *websocket.Conn) { + tb.Helper() + accepted := make(chan *websocket.Conn, 1) + httpServer := httptest.NewServer(http.HandlerFunc( + func(responseWriter http.ResponseWriter, request *http.Request) { + conn, err := websocket.Accept(responseWriter, request, nil) + if err != nil { + return + } + accepted <- conn + <-request.Context().Done() + }, + )) + tb.Cleanup(httpServer.Close) + + client, response, err := websocket.Dial(tb.Context(), + "ws"+strings.TrimPrefix(httpServer.URL, "http"), nil) + if response != nil && response.Body != nil { + _ = response.Body.Close() + } + assert.Nil(tb, err) + tb.Cleanup(func() { _ = client.CloseNow() }) + return <-accepted, client +} + +// A peer that is still listening must be told why it will get no verdict. The +// S message could not be written, so the close frame is the only channel left, +// and a bare 1000 would read as an orderly finish. +func TestCloseReportsAFailedVerdictToAPresentPeer(t *testing.T) { + t.Parallel() + serverConn, clientConn := connPair(t) + conn := &websocketHandlerConn{ + wsConn: serverConn, + marshaler: messageWriter{ + sender: deadSender{}, + }, + // The peer is still there: it never sent C, and the read path never + // reached EOF, so the failed write is not excused. + leadingSent: true, + } + + // Close runs the closing handshake, which waits for the peer's own close + // frame — the read below — so it cannot be called inline. + closed := make(chan error, 1) + go func() { closed <- conn.Close(t.Context(), nil) }() + + // Bounded: an unbounded read here would wait out the package's own timeout + // if the close frame never arrived, rather than failing this one test. + readCtx, cancelRead := context.WithTimeout(t.Context(), wsTestReadTimeout) + defer cancelRead() + _, _, readErr := clientConn.Read(readCtx) + assert.NotNil(t, readErr) + assert.Equal(t, websocket.CloseStatus(readErr), websocket.StatusInternalError) + var closeErr websocket.CloseError + assert.True(t, errors.As(readErr, &closeErr)) + assert.True(t, strings.Contains(closeErr.Reason, "broken pipe")) + + returned := <-closed + assert.NotNil(t, returned) + assert.True(t, strings.Contains(returned.Error(), "broken pipe")) +} + +// A close reason is whatever the failure said, and RFC 6455 caps a control +// payload at 125 bytes with two spent on the status code. The library rejects +// an over-long reason rather than trimming it, so a reason that does not fit +// means no close frame at all — the peer learns nothing. +func TestCloseReasonFitsTheFrame(t *testing.T) { + t.Parallel() + const limit = 123 + for _, test := range []struct { + name string + reason string + want int + }{ + {name: "short", reason: strings.Repeat("x", 1), want: 1}, + {name: "at the limit", reason: strings.Repeat("x", limit), want: limit}, + {name: "one past the limit", reason: strings.Repeat("x", limit+1), want: limit}, + {name: "far past the limit", reason: strings.Repeat("x", 4096), want: limit}, + { + // The cut lands one byte into a three-byte rune, so it has to back + // off past the whole rune: a close reason must be valid UTF-8. + name: "cut inside a multi-byte rune", + reason: strings.Repeat("x", limit-1) + "\u2603", + want: limit - 1, + }, + } { + t.Run(test.name, func(t *testing.T) { + t.Parallel() + got := closeReason(test.reason) + assert.Equal(t, len(got), test.want) + assert.True(t, strings.HasPrefix(test.reason, got)) + assert.True(t, utf8.ValidString(got)) + + // The contract is the library's, not arithmetic: a reason it + // refuses to marshal is a close frame that never goes out. + serverConn, clientConn := connPair(t) + // Answer the close frame, so the closing handshake finishes + // instead of waiting out its timeout. + go func() { _, _, _ = clientConn.Read(context.Background()) }() + err := serverConn.Close(websocket.StatusInternalError, got) + assert.True(t, err == nil || !strings.Contains(err.Error(), "reason string max")) + }) + } +} + +// A body that cannot be written must fail the Send that wrote it. Swallowing it +// would let a handler run to completion believing a peer got messages it never +// did. +func TestSendReportsAFailedBodyWrite(t *testing.T) { + t.Parallel() + conn := &websocketHandlerConn{ + ctx: t.Context(), + marshaler: messageWriter{ + sender: deadSender{}, + }, + info: SessionInfo{Codec: connectproto.NewBinaryCodec()}, + leadingSent: true, // isolate the body write from the metadata write + } + + err := conn.Send(&pingv1.CumSumResponse{Sum: 1}) + assert.NotNil(t, err) + assert.True(t, strings.Contains(err.Error(), "broken pipe")) +} + +// pastDeadlineContext is the window the two clocks leave open: the deadline has +// passed, but the context's timer goroutine has not yet set Err. It is supplied +// directly because the real window is a few microseconds wide. +type pastDeadlineContext struct{ context.Context } + +func (pastDeadlineContext) Deadline() (time.Time, bool) { + return time.Now().Add(-time.Second), true +} + +func (pastDeadlineContext) Err() error { return nil } + +// A read that fails at or past the deadline is the deadline, whichever clock +// noticed first. Reporting Unavailable would invite a retry with no time left +// to run it. +func TestReadFailureAtTheDeadlineIsDeadlineExceeded(t *testing.T) { + t.Parallel() + serverConn, clientConn := connPair(t) + _ = serverConn.CloseNow() + // Closed before the read, so the failure needs no timing of its own. + _ = clientConn.CloseNow() + + ctx := pastDeadlineContext{Context: t.Context()} + call := &wsClientCall{wsConn: clientConn} + call.dialOnce.Do(func() {}) // consume it, so ensureDialed will not dial + call.reader = newFrameReader(ctx, clientConn.Read, nil) + t.Cleanup(call.reader.close) + + conn := &websocketClientConn{ctx: ctx, call: call} + _, err := conn.unmarshal(&pingv1.CumSumResponse{}) + + assert.NotNil(t, err) + assert.Equal(t, err.Code(), connect.CodeDeadlineExceeded) + assert.True(t, errors.Is(err, context.DeadlineExceeded)) +} diff --git a/internal/wstransport/closerace_ext_test.go b/internal/wstransport/closerace_ext_test.go new file mode 100644 index 00000000..58e9a6de --- /dev/null +++ b/internal/wstransport/closerace_ext_test.go @@ -0,0 +1,90 @@ +// Copyright 2021-2026 The Connect Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package wstransport_test + +import ( + "context" + "net" + "sync" + "testing" + "time" + + "connectrpc.com/connect/v2" + "connectrpc.com/connect/v2/internal/assert" + pingv1 "connectrpc.com/connect/v2/internal/gen/connect/ping/v1" + "connectrpc.com/connect/v2/internal/gen/connect/ping/v1/pingv1connect" + "connectrpc.com/connect/v2/internal/wstransport" +) + +// faultingServer answers count handshakes on listener with M and then a +// message with an unknown marker, and completes each closing handshake. +func faultingServer(tb testing.TB, listener net.Listener, count int) { + tb.Helper() + opening := serverFrame(true, []byte("M[]")) + unknownMarker := serverFrame(true, []byte("X{}")) + closeFrame := []byte{0x88, 0x02, 0x03, 0xe8} + var group sync.WaitGroup + defer group.Wait() + for range count { + conn, reader := acceptRawUpgrade(tb, listener) + group.Go(func() { + if _, err := conn.Write(append(opening, unknownMarker...)); err != nil { + return + } + _, _, _ = watchFrames(reader, nil) + _, _ = conn.Write(closeFrame) + }) + } +} + +// The ClientStream contract lets Close run concurrently with Receive, so the +// fault a Receive records must be safe for Close to read. Run with -race. +func TestCloseDuringFaultingReceive(t *testing.T) { + t.Parallel() + listener, err := (&net.ListenConfig{}).Listen(t.Context(), "tcp", "127.0.0.1:0") + assert.Nil(t, err) + t.Cleanup(func() { _ = listener.Close() }) + const attempts = 20 + served := make(chan struct{}) + go func() { + defer close(served) + faultingServer(t, listener, attempts) + }() + transport, err := wstransport.NewTransport("http://" + listener.Addr().String()) + assert.Nil(t, err) + client := pingv1connect.NewPingServiceClient(connect.NewClient(transport)) + + for range attempts { + ctx, cancel := context.WithTimeout(t.Context(), 10*time.Second) + stream, err := client.CountUp(ctx, &pingv1.CountUpRequest{Number: 1}) + assert.Nil(t, err) + // Let the faulting message reach the read-ahead before both start. + time.Sleep(10 * time.Millisecond) + start := make(chan struct{}) + var group sync.WaitGroup + group.Go(func() { + <-start + _, _ = stream.Receive() + }) + group.Go(func() { + <-start + _ = stream.Close() + }) + close(start) + group.Wait() + cancel() + } + <-served +} diff --git a/internal/wstransport/codec.go b/internal/wstransport/codec.go new file mode 100644 index 00000000..4f59de03 --- /dev/null +++ b/internal/wstransport/codec.go @@ -0,0 +1,99 @@ +// Copyright 2021-2026 The Connect Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package wstransport + +import ( + "strings" + + "connectrpc.com/connect/v2" +) + +// wsSubprotocolPrefix starts every token §4.3 defines: connectrpc.1+ and then +// the codec's name, as Connect over HTTP spells it in application/connect+name. +const wsSubprotocolPrefix = "connectrpc.1+" + +// TextCodec is an optional interface for a [connect.Codec] whose encoding is +// UTF-8 text. Over WebSocket, the frame type tells a receiver how a body is +// encoded (§6.1), so a codec other than proto or json that returns true from +// IsText has its bodies sent in text frames; every other such codec's go in +// binary frames. The proto and json codecs are binary and text by definition, +// whatever they implement. +// +// A text codec must produce valid UTF-8, which RFC 6455 requires of a text +// frame. A body that is not is refused before it is sent. +type TextCodec interface { + connect.Codec + // IsText reports whether the codec's output is UTF-8 text. + IsText() bool +} + +// codecIsText reports whether codec's bodies travel in text frames. +func codecIsText(codec connect.Codec) bool { + switch codec.Name() { + case connect.CodecNameJSON: + return true + case connect.CodecNameProto: + return false + } + textCodec, ok := codec.(TextCodec) + return ok && textCodec.IsText() +} + +// subprotocolForCodec is the token that names a codec. +func subprotocolForCodec(name string) string { + return wsSubprotocolPrefix + name +} + +// codecForSubprotocol maps a token to the name of the codec it selects, or "" +// when the token is not one §4.3 defines. +func codecForSubprotocol(token string) string { + name, ok := strings.CutPrefix(token, wsSubprotocolPrefix) + if !ok || !validCodecName(name) { + return "" + } + return name +} + +// validCodecName reports whether a token can carry name. §4.3 requires a +// lower-case HTTP token, which also keeps the subprotocol a valid one. +func validCodecName(name string) bool { + if name == "" { + return false + } + for index := range len(name) { + if !isTokenByte(name[index]) || ('A' <= name[index] && name[index] <= 'Z') { + return false + } + } + return true +} + +// carriedCodecs filters codecs to those a token can name, in the order given, +// keeping the first of any name registered twice. +func carriedCodecs(codecs []connect.Codec) []connect.Codec { + seen := make(map[string]struct{}, len(codecs)) + carried := make([]connect.Codec, 0, len(codecs)) + for _, codec := range codecs { + name := codec.Name() + if _, duplicate := seen[name]; duplicate { + continue + } + seen[name] = struct{}{} + if validCodecName(name) { + carried = append(carried, codec) + } + } + return carried +} diff --git a/internal/wstransport/codec_ext_test.go b/internal/wstransport/codec_ext_test.go new file mode 100644 index 00000000..3db841c5 --- /dev/null +++ b/internal/wstransport/codec_ext_test.go @@ -0,0 +1,550 @@ +// Copyright 2021-2026 The Connect Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package wstransport_test + +import ( + "encoding/json" + "errors" + "io" + "net/http" + "net/http/httptest" + "strconv" + "strings" + "testing" + "time" + + "connectrpc.com/connect/v2" + "connectrpc.com/connect/v2/connecthttp" + "connectrpc.com/connect/v2/connectproto" + "connectrpc.com/connect/v2/internal/assert" + pingv1 "connectrpc.com/connect/v2/internal/gen/connect/ping/v1" + "connectrpc.com/connect/v2/internal/gen/connect/ping/v1/pingv1connect" + "github.com/coder/websocket" + "google.golang.org/protobuf/encoding/protojson" + "google.golang.org/protobuf/proto" +) + +// The subprotocol token is the only thing that says which codec is in use, so +// what it selects has to be checked against the bytes on the wire rather than +// against a round trip. A round trip succeeds whenever both ends agree, even +// if they agree on something other than what the token names. +func TestCodecSelectsWireFormat(t *testing.T) { + t.Parallel() + const value = int64(7) + for _, test := range []struct { + name string + token string + json bool + }{ + {name: "proto", token: "connectrpc.1+proto"}, + {name: "json", token: "connectrpc.1+json", json: true}, + } { + t.Run(test.name, func(t *testing.T) { + t.Parallel() + httpServer := newServerFor(t, scriptedServer{}) + client := dialBrowserClientWithToken( + t, httpServer, pingv1connect.PingServiceSumProcedure, test.token) + + request := &pingv1.SumRequest{Number: value} + var payload []byte + var err error + if test.json { + payload, err = protojson.Marshal(request) + } else { + payload, err = proto.Marshal(request) + } + assert.Nil(t, err) + // The frame type *is* the encoding: JSON goes out as text, + // Protobuf as binary. + client.writeMessage(t, wireBody, test.json, payload) + client.writeJSON(t, wireClientEndStream, nil) + + opening, _, _ := client.readMessage(t) + assert.Equal(t, opening, wireMetadata) + + marker, body, text := client.readMessage(t) + assert.Equal(t, marker, wireBody) + assert.Equal(t, text, test.json) + if test.json { + assertProtoJSON(t, body, value) + } else { + assertProtoBinary(t, body, value) + } + + // The terminal message is JSON whichever codec carries the bodies: + // it is protocol, not payload. A client built for the proto + // subprotocol still has to parse JSON here, in a text frame. + marker, body, text = client.readMessage(t) + assert.Equal(t, marker, wireServerEndStream) + assert.True(t, text) + assert.True(t, json.Valid(body)) + assert.True(t, strings.Contains(string(body), "set-by-handler")) + }) + } +} + +// assertProtoBinary checks that body is Protobuf binary carrying sum, and in +// particular that it is not JSON that happens to decode. +func assertProtoBinary(tb testing.TB, body []byte, sum int64) { + tb.Helper() + assert.True(tb, !json.Valid(body)) + var response pingv1.SumResponse + assert.Nil(tb, proto.Unmarshal(body, &response)) + assert.Equal(tb, response.Sum, sum) +} + +// assertProtoJSON checks that body is protobuf-JSON carrying sum. The int64 is +// asserted to be a *string*: protobuf-JSON quotes 64-bit integers, so a client +// that parses this as a JSON number loses precision above 2^53. The bytes are +// decoded rather than compared, because protojson varies its whitespace. +func assertProtoJSON(tb testing.TB, body []byte, sum int64) { + tb.Helper() + assert.True(tb, json.Valid(body)) + + var fields map[string]any + assert.Nil(tb, json.Unmarshal(body, &fields)) + raw, ok := fields["sum"] + assert.True(tb, ok) + quoted, isString := raw.(string) + assert.True(tb, isString) + assert.Equal(tb, quoted, strconv.FormatInt(sum, 10)) + + var response pingv1.SumResponse + assert.Nil(tb, protojson.Unmarshal(body, &response)) + assert.Equal(tb, response.Sum, sum) +} + +// §6.1: C is a control message like M and S, so it is a bare text frame +// whatever the codec. Only bodies follow the negotiated frame type. +func TestEndOfClientStreamIsAlwaysText(t *testing.T) { + t.Parallel() + for _, test := range []struct { + codec string + }{ + {codec: connect.CodecNameProto}, + {codec: connect.CodecNameJSON}, + } { + t.Run(test.codec, func(t *testing.T) { + t.Parallel() + frames := make(chan bool, 4) + httpServer := frameTypeRecordingServer(t, frames) + + transport := connecthttp.NewTransport( + httpServer.Client(), + httpServer.URL, + connecthttp.WithWebSocket(connecthttp.SelectAll), + connecthttp.WithSendCodec(test.codec), + ) + client := pingv1connect.NewPingServiceClient(connect.NewClient(transport)) + stream, err := client.Sum(t.Context()) + assert.Nil(t, err) + // This server never answers, so the call would block; the frames it + // has already sent are what the test reads. + go func() { _, _ = stream.CloseAndReceive() }() + + assert.Equal(t, readFrameType(t, frames), true) // opening M is JSON + assert.Equal(t, readFrameType(t, frames), true) // bare C is text + }) + } +} + +// closeCodeRecordingServer accepts an upgrade by hand and reports the close +// code and reason the client eventually sends, which is the only way to see +// them. A read that ended without a close frame reports code -1. +func closeCodeRecordingServer(tb testing.TB, codes chan<- websocket.CloseError) *httptest.Server { + tb.Helper() + httpServer := httptest.NewServer(http.HandlerFunc( + func(responseWriter http.ResponseWriter, request *http.Request) { + conn, err := websocket.Accept(responseWriter, request, &websocket.AcceptOptions{ + Subprotocols: []string{firstOfferedSubprotocol(request)}, + }) + if err != nil { + return + } + defer func() { _ = conn.CloseNow() }() + for { + if _, _, readErr := conn.Read(request.Context()); readErr != nil { + select { + case codes <- closeErrorOf(readErr): + default: + } + return + } + } + }, + )) + tb.Cleanup(httpServer.Close) + return httpServer +} + +func closeErrorOf(err error) websocket.CloseError { + if closeErr, ok := errors.AsType[websocket.CloseError](err); ok { + return closeErr + } + return websocket.CloseError{Code: -1} +} + +// §13.1: a client that ends an RPC on its own unexpected condition says so with +// 3102 and a reason, rather than the 1000 that would tell the server the stream +// finished normally. The server behaved here — only this end failed. +func TestClientClosesWithInternalErrorCode(t *testing.T) { + t.Parallel() + codes := make(chan websocket.CloseError, 1) + httpServer := closeCodeRecordingServer(t, codes) + + transport := connecthttp.NewTransport( + httpServer.Client(), + httpServer.URL, + connecthttp.WithWebSocket(connecthttp.SelectAll), + // Small enough that the message below cannot be encoded for the wire. + connecthttp.WithSendMaxBytes(16), + ) + client := pingv1connect.NewPingServiceClient(connect.NewClient(transport)) + + // Far past the limit, so the encode step refuses it before the wire. + _, callErr := client.Ping(t.Context(), &pingv1.PingRequest{ + Text: strings.Repeat("x", 4096), + }) + assert.NotNil(t, callErr) + assert.Equal(t, connect.CodeOf(callErr), connect.CodeResourceExhausted) + + select { + case closeErr := <-codes: + assert.Equal(t, closeErr.Code, websocket.StatusCode(3102)) + assert.True(t, strings.Contains(closeErr.Reason, "16")) + assert.True(t, len(closeErr.Reason) <= 123) + case <-time.After(10 * time.Second): + t.Fatal("the client never closed") + } +} + +// A stream that ends with nothing wrong closes 1000, so the code above cannot +// be what this client always sends. +func TestCleanStreamClosesNormally(t *testing.T) { + t.Parallel() + codes := make(chan websocket.CloseError, 1) + httpServer := closeCodeRecordingServer(t, codes) + + transport := connecthttp.NewTransport( + httpServer.Client(), + httpServer.URL, + connecthttp.WithWebSocket(connecthttp.SelectAll), + ) + client := pingv1connect.NewPingServiceClient(connect.NewClient(transport)) + stream, err := client.CumSum(t.Context()) + assert.Nil(t, err) + assert.Nil(t, stream.Send(&pingv1.CumSumRequest{Number: 1})) + assert.Nil(t, stream.Close()) + + select { + case closeErr := <-codes: + assert.Equal(t, closeErr.Code, websocket.StatusNormalClosure) + case <-time.After(10 * time.Second): + t.Fatal("the client never closed") + } +} + +// readFrameType takes the next observed frame type, failing rather than +// blocking if the client never sent one. +func readFrameType(tb testing.TB, frames <-chan bool) bool { + tb.Helper() + select { + case text := <-frames: + return text + case <-time.After(10 * time.Second): + tb.Fatal("the client sent no further message") + return false + } +} + +// frameTypeRecordingServer accepts an upgrade by hand and reports whether each +// client message arrived as text, which is the only way to see a frame type +// from outside. +func frameTypeRecordingServer(tb testing.TB, frames chan<- bool) *httptest.Server { + tb.Helper() + httpServer := httptest.NewServer(http.HandlerFunc( + func(responseWriter http.ResponseWriter, request *http.Request) { + conn, err := websocket.Accept(responseWriter, request, &websocket.AcceptOptions{ + Subprotocols: []string{firstOfferedSubprotocol(request)}, + }) + if err != nil { + return + } + defer func() { _ = conn.CloseNow() }() + for { + messageType, _, readErr := conn.Read(request.Context()) + if readErr != nil { + return + } + select { + case frames <- messageType == websocket.MessageText: + default: + } + } + }, + )) + tb.Cleanup(httpServer.Close) + return httpServer +} + +// A server configured with one codec is a supported configuration, not a +// broken one. It must negotiate what it has and refuse what it does not, +// rather than upgrading into a connection it cannot decode. +func TestPartialCodecSetNegotiates(t *testing.T) { + t.Parallel() + for _, test := range []struct { + name string + codecs []connect.Codec + offer string + status int + echoed string + }{ + { + name: "server takes the client's second choice", + codecs: []connect.Codec{connectproto.NewBinaryCodec()}, + // A codec the server lacks first: a server that failed on the + // first recognized token would refuse a client it can serve. + offer: "connectrpc.1+msgpack, connectrpc.1+proto", + status: http.StatusSwitchingProtocols, + echoed: "connectrpc.1+proto", + }, + { + // The bare token names no codec, so it is not one of this + // binding's tokens at all. + name: "the bare token is not a Connect subprotocol", + codecs: []connect.Codec{connectproto.NewJSONCodec()}, + offer: "connectrpc.1", + status: http.StatusBadRequest, + }, + { + name: "unrecognized tokens are not an encoding problem", + codecs: []connect.Codec{connectproto.NewBinaryCodec()}, + offer: "mqtt, chat", + status: http.StatusBadRequest, + }, + { + name: "no Sec-WebSocket-Protocol at all", + codecs: []connect.Codec{connectproto.NewBinaryCodec()}, + status: http.StatusBadRequest, + }, + } { + t.Run(test.name, func(t *testing.T) { + t.Parallel() + server := connect.NewServer() + pingv1connect.RegisterPingServiceHandler(server, pingServer{}) + mux := http.NewServeMux() + connecthttp.Mount(mux, server, connecthttp.WithCodecs(test.codecs...)) + httpServer := httptest.NewServer(mux) + t.Cleanup(httpServer.Close) + + response := offerSubprotocol(t, httpServer, test.offer) + defer func() { _ = response.Body.Close() }() + assert.Equal(t, response.StatusCode, test.status) + if test.echoed != "" { + assert.Equal(t, response.Header.Get("Sec-WebSocket-Protocol"), test.echoed) + } + }) + } +} + +// §4.3: a server that supports none of the offered tokens refuses the +// handshake with 400, even when it recognizes them. The body names what it +// does speak, for the non-browser clients and developer tools that can read it. +func TestUnsupportedCodecIsRejectedWithBadRequest(t *testing.T) { + t.Parallel() + for _, test := range []struct { + name string + codecs []connect.Codec + offer string + speaks string + }{ + { + // JSON is served even though the codecs name only proto (§4.3). + name: "proto server, client offering only a codec it lacks", + codecs: []connect.Codec{connectproto.NewBinaryCodec()}, + offer: "connectrpc.1+msgpack", + speaks: "connectrpc.1+proto, connectrpc.1+json", + }, + { + name: "JSON-only server, proto-only client", + codecs: []connect.Codec{connectproto.NewJSONCodec()}, + offer: "connectrpc.1+proto", + speaks: "connectrpc.1+json", + }, + { + name: "custom codecs are listed too", + codecs: []connect.Codec{ + connectproto.NewBinaryCodec(), + connectproto.NewJSONCodec(), + customTextCodec{connectproto.NewJSONCodec()}, + }, + offer: "connectrpc.1+nope", + speaks: "connectrpc.1+customtext", + }, + } { + t.Run(test.name, func(t *testing.T) { + t.Parallel() + server := connect.NewServer() + pingv1connect.RegisterPingServiceHandler(server, pingServer{}) + mux := http.NewServeMux() + connecthttp.Mount(mux, server, connecthttp.WithCodecs(test.codecs...)) + httpServer := httptest.NewServer(mux) + t.Cleanup(httpServer.Close) + + response := offerSubprotocol(t, httpServer, test.offer) + defer func() { _ = response.Body.Close() }() + assert.Equal(t, response.StatusCode, http.StatusBadRequest) + body, readErr := io.ReadAll(response.Body) + assert.Nil(t, readErr) + assert.True(t, strings.Contains(string(body), test.speaks)) + }) + } +} + +// §4.3: the client offers its preferred codec and then the other, and encodes +// with whichever the server echoes, and the call reports the codec actually +// used. +func TestClientFollowsServerCodecChoice(t *testing.T) { + t.Parallel() + for _, test := range []struct { + name string + server connect.Codec + sendCodec string + echoed string + }{ + { + // §4.3: a server supports JSON whatever its codecs were narrowed + // to, so the client's first choice is honored. + name: "client prefers JSON, server configured with only proto", + server: connectproto.NewBinaryCodec(), + sendCodec: connect.CodecNameJSON, + echoed: "connectrpc.1+json", + }, + { + name: "client prefers proto, server has only JSON", + server: connectproto.NewJSONCodec(), + sendCodec: connect.CodecNameProto, + echoed: "connectrpc.1+json", + }, + } { + t.Run(test.name, func(t *testing.T) { + t.Parallel() + server := connect.NewServer() + pingv1connect.RegisterPingServiceHandler(server, pingServer{}) + mux := http.NewServeMux() + connecthttp.Mount(mux, server, connecthttp.WithCodecs(test.server)) + httpServer := httptest.NewServer(mux) + t.Cleanup(httpServer.Close) + + recorder := &recordingTransport{base: httpServer.Client().Transport} + transport := connecthttp.NewTransport( + &http.Client{Transport: recorder}, + httpServer.URL, + connecthttp.WithWebSocket(connecthttp.SelectAll), + connecthttp.WithSendCodec(test.sendCodec), + ) + client := pingv1connect.NewPingServiceClient(connect.NewClient(transport)) + ctx, info := connect.NewClientContext(t.Context()) + stream, err := client.CumSum(ctx) + assert.Nil(t, err) + assert.Nil(t, stream.Send(&pingv1.CumSumRequest{Number: 4})) + sum, err := stream.Receive() + assert.Nil(t, err) + assert.Equal(t, sum.Sum, int64(4)) + assert.Nil(t, stream.CloseSend()) + assert.Nil(t, stream.Close()) + assert.Equal(t, *recorder.subprotocol.Load(), test.echoed) + assert.Equal(t, info.Codec, strings.TrimPrefix(test.echoed, "connectrpc.1+")) + }) + } +} + +// firstOfferedSubprotocol is the token a hand-built server echoes: the first +// one the client offered, which is what negotiation picks against a server +// holding both codecs. +func firstOfferedSubprotocol(request *http.Request) string { + offer, _, _ := strings.Cut(request.Header.Get("Sec-WebSocket-Protocol"), ",") + return strings.TrimSpace(offer) +} + +// offerSubprotocol sends one handshake with the given Sec-WebSocket-Protocol +// offer. A successful upgrade's body is the hijacked socket, so a caller that +// asserts on the status must not read it. +func offerSubprotocol(tb testing.TB, server *httptest.Server, offer string) *http.Response { + tb.Helper() + request, err := http.NewRequestWithContext(tb.Context(), http.MethodGet, + server.URL+pingv1connect.PingServiceCumSumProcedure, nil) + assert.Nil(tb, err) + request.Header.Set("Connection", "Upgrade") + request.Header.Set("Upgrade", "websocket") + request.Header.Set("Sec-WebSocket-Version", "13") + request.Header.Set("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==") + if offer != "" { + request.Header.Set("Sec-WebSocket-Protocol", offer) + } + response, err := server.Client().Do(request) + assert.Nil(tb, err) + tb.Cleanup(func() { _ = response.Body.Close() }) + return response +} + +// The subprotocol names the encoding, and nothing on the wire stops a peer +// from sending the other one. A receiver that decoded it anyway would let the +// peer pick an encoding the handshake did not agree on — so this is refused +// whether or not the receiver holds a codec for what arrived. +func TestBodyInTheWrongEncodingIsRejected(t *testing.T) { + t.Parallel() + for _, test := range []struct { + name string + codecs []connect.Codec + }{ + { + // The hole worth closing: the server has a JSON codec and could + // decode this, but the connection negotiated proto. + name: "receiver holds the codec anyway", + codecs: nil, // the default pair + }, + { + name: "receiver does not hold the codec", + codecs: []connect.Codec{connectproto.NewBinaryCodec()}, + }, + } { + t.Run(test.name, func(t *testing.T) { + t.Parallel() + server := connect.NewServer() + pingv1connect.RegisterPingServiceHandler(server, pingServer{}) + mux := http.NewServeMux() + var options []connecthttp.Option + if test.codecs != nil { + options = append(options, connecthttp.WithCodecs(test.codecs...)) + } + connecthttp.Mount(mux, server, options...) + httpServer := httptest.NewServer(mux) + t.Cleanup(httpServer.Close) + + // dialCumSum negotiates +proto and has sent the opening M. + conn := dialCumSum(t, httpServer, "") + // A JSON body in a text frame, on a Protobuf connection. + sendJSONMessage(t, conn, wireBody, []byte(`{"number":"1"}`)) + + data := readServerOpening(t, conn) + assert.Equal(t, data[0], wireServerEndStream) + assert.True(t, strings.Contains(string(data), "internal")) + // §6.1: names the frame type that was expected. + assert.True(t, strings.Contains(string(data), + "body in a text frame; the negotiated proto codec expects a binary frame")) + }) + } +} diff --git a/internal/wstransport/compressionbomb_ext_test.go b/internal/wstransport/compressionbomb_ext_test.go new file mode 100644 index 00000000..a534f4f3 --- /dev/null +++ b/internal/wstransport/compressionbomb_ext_test.go @@ -0,0 +1,338 @@ +// Copyright 2021-2026 The Connect Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package wstransport_test + +import ( + "bufio" + "context" + "crypto/rand" + "crypto/sha1" + "encoding/base64" + "encoding/binary" + "fmt" + "io" + "net" + "net/http" + "net/http/httptest" + "strings" + "sync/atomic" + "testing" + "time" + + "connectrpc.com/connect/v2" + "connectrpc.com/connect/v2/connecthttp" + "connectrpc.com/connect/v2/internal/assert" + pingv1 "connectrpc.com/connect/v2/internal/gen/connect/ping/v1" + "connectrpc.com/connect/v2/internal/gen/connect/ping/v1/pingv1connect" + "connectrpc.com/connect/v2/internal/wstransport" +) + +const ( + bombReadMaxBytes = 64 * 1024 // what the server will accept + bombCompressed = 8 * 1024 * 1024 // what the attacker sends + // What a side that rejects the bomb will read: its own wire bound, the + // closing drain's budget, which is the same bound again, and buffering. + bombInflateCeiling = 1024 * 1024 +) + +// countingListener reports how many bytes reached the server, which is the +// only way to tell a bounded read from one that ran to completion. +type countingListener struct { + net.Listener + + read atomic.Int64 +} + +func (l *countingListener) Accept() (net.Conn, error) { + conn, err := l.Listener.Accept() + if err != nil { + return nil, err + } + return &countingConn{Conn: conn, read: &l.read}, nil +} + +type countingConn struct { + net.Conn + + read *atomic.Int64 +} + +func (c *countingConn) Read(p []byte) (int, error) { + n, err := c.Conn.Read(p) + c.read.Add(int64(n)) + return n, err +} + +// zeroOutputDeflate builds a DEFLATE stream of empty stored blocks. Each +// 5-byte block (a non-final stored header, then LEN 0 and NLEN 0xFFFF) +// inflates to nothing, so the compressed size grows without the inflated size +// ever moving — the shape that would defeat a limit applied only after +// inflation. +func zeroOutputDeflate(size int) []byte { + payload := make([]byte, 0, size) + for len(payload) < size { + payload = append(payload, 0x00, 0x00, 0x00, 0xFF, 0xFF) + } + // permessage-deflate strips the trailing marker; the receiver appends it. + return payload[:len(payload)-4] +} + +// writeClientFragment writes one masked client frame with an explicit FIN bit +// and opcode, so a test can split one message across continuation frames. +func writeClientFragment(conn net.Conn, payload []byte, fin bool, opcode byte) error { + first := opcode + if fin { + first |= 0x80 + } + header := []byte{first} + switch n := len(payload); { + case n < 126: + header = append(header, byte(0x80|n)) + default: + header = append(header, 0x80|126, 0, 0) + binary.BigEndian.PutUint16(header[len(header)-2:], uint16(n)) + } + var mask [4]byte + if _, err := rand.Read(mask[:]); err != nil { + return err + } + header = append(header, mask[:]...) + masked := make([]byte, len(payload)) + for index, b := range payload { + masked[index] = b ^ mask[index%4] + } + if _, err := conn.Write(header); err != nil { + return err + } + _, err := conn.Write(masked) + return err +} + +// writeClientFrame writes one masked client frame with FIN set. compressed +// sets RSV1, which marks the payload as permessage-deflate compressed; text +// picks the text opcode, which is what a JSON payload travels under. +func writeClientFrame(conn net.Conn, payload []byte, compressed, text bool) error { + first := byte(0x80 | 0x02) // FIN | binary + if text { + first = byte(0x80 | 0x01) + } + if compressed { + first |= 0x40 // RSV1 + } + header := []byte{first} + switch n := len(payload); { + case n < 126: + header = append(header, byte(0x80|n)) + case n < 65536: + header = append(header, 0x80|126, 0, 0) + binary.BigEndian.PutUint16(header[len(header)-2:], uint16(n)) + default: + header = append(header, 0x80|127, 0, 0, 0, 0, 0, 0, 0, 0) + binary.BigEndian.PutUint64(header[len(header)-8:], uint64(n)) + } + var mask [4]byte + if _, err := rand.Read(mask[:]); err != nil { + return err + } + header = append(header, mask[:]...) + masked := make([]byte, len(payload)) + for i, b := range payload { + masked[i] = b ^ mask[i%4] + } + if _, err := conn.Write(header); err != nil { + return err + } + _, err := conn.Write(masked) + return err +} + +// rawHandshake performs a WebSocket upgrade by hand, so the test controls the +// extension negotiation that coder's client would otherwise own. +func rawHandshake(tb testing.TB, conn net.Conn, addr, procedure string) string { + tb.Helper() + var keyBytes [16]byte + _, err := rand.Read(keyBytes[:]) + assert.Nil(tb, err) + request := fmt.Sprintf( + "GET %s HTTP/1.1\r\nHost: %s\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n"+ + "Sec-WebSocket-Key: %s\r\nSec-WebSocket-Version: 13\r\n"+ + "Sec-WebSocket-Protocol: connectrpc.1+proto\r\n"+ + "Sec-WebSocket-Extensions: permessage-deflate; client_no_context_takeover; server_no_context_takeover\r\n\r\n", + procedure, addr, base64.StdEncoding.EncodeToString(keyBytes[:]), + ) + _, err = conn.Write([]byte(request)) + assert.Nil(tb, err) + + res, err := http.ReadResponse(bufio.NewReader(conn), nil) + assert.Nil(tb, err) + tb.Cleanup(func() { + if res.Body != nil { + _ = res.Body.Close() + } + }) + assert.Equal(tb, res.StatusCode, http.StatusSwitchingProtocols) + // Returned rather than asserted: a caller testing compression needs + // permessage-deflate, and one testing its absence needs it gone. + return res.Header.Get("Sec-WebSocket-Extensions") +} + +// TestCompressionBombIsBoundedOnTheWire pins a property the transport's safety +// depends on but does not itself implement: the read limit bounds compressed +// input, not only the inflated message. A stream of zero-output DEFLATE blocks +// never trips an inflated-size limit, so if the compressed side were unbounded +// a peer could make the server read forever from one frame. +// +// This guards a dependency, so it is the test that should fail first if a +// WebSocket library upgrade changes the behavior. +// bombAgainstServer sends one zero-output bomb and reports how many bytes the +// server was willing to read. +func bombAgainstServer(tb testing.TB, options ...wstransport.ServerOption) int64 { + tb.Helper() + server := connect.NewServer() + pingv1connect.RegisterPingServiceHandler(server, pingServer{}) + mux := http.NewServeMux() + mountBoth(mux, server, append( + []wstransport.ServerOption{wstransport.WithReadMaxBytes(bombReadMaxBytes)}, + options..., + )...) + + httpServer := httptest.NewUnstartedServer(mux) + listener := &countingListener{Listener: httpServer.Listener} + httpServer.Listener = listener + httpServer.Start() + tb.Cleanup(httpServer.Close) + + addr := httpServer.Listener.Addr().String() + dialer := &net.Dialer{} + ctx, cancel := context.WithTimeout(tb.Context(), 30*time.Second) + defer cancel() + conn, err := dialer.DialContext(ctx, "tcp", addr) + assert.Nil(tb, err) + tb.Cleanup(func() { _ = conn.Close() }) + + // Without permessage-deflate the payload below is not treated as compressed + // and the test would prove nothing. + assert.True(tb, strings.Contains(rawHandshake(tb, conn, addr, pingProcedure), "permessage-deflate")) + handshakeBytes := listener.read.Load() + + assert.Nil(tb, conn.SetWriteDeadline(time.Now().Add(20*time.Second))) + _ = writeClientFrame(conn, zeroOutputDeflate(bombCompressed), true, false) + // A close frame queued behind the bomb. A server that completes the closing + // handshake has to read past the bomb to reach it, so the measurement is + // the same as waiting the handshake out — without waiting five seconds for + // it. A server that hangs up never reads either, and the write just fails. + _ = writeClientFragment(conn, []byte{0x03, 0xE8}, true, opcodeClose) + + // Drain until the server closes, so the measurement covers everything it + // was willing to read. + assert.Nil(tb, conn.SetReadDeadline(time.Now().Add(20*time.Second))) + _, _ = io.Copy(io.Discard, conn) + + consumed := listener.read.Load() - handshakeBytes + tb.Logf("server consumed %d KiB of an %d KiB bomb (limit %d KiB)", + consumed/1024, bombCompressed/1024, bombReadMaxBytes/1024) + return consumed +} + +// A server that rejects a bomb still sends its close code, but the closing +// handshake stops reading at the drain's budget, so a bomb costs the +// attacker's bandwidth rather than the server's. +func TestCompressionBombIsBoundedOnTheWire(t *testing.T) { + t.Parallel() + assert.True(t, bombAgainstServer(t) < bombInflateCeiling) +} + +// hostileServer completes a WebSocket handshake by hand and then sends the +// client a compression bomb. coder's own server would compress for us, so the +// frame has to be built directly. +func hostileServer(tb testing.TB, read *atomic.Int64) string { + tb.Helper() + listener, err := (&net.ListenConfig{}).Listen(tb.Context(), "tcp", "127.0.0.1:0") + assert.Nil(tb, err) + tb.Cleanup(func() { _ = listener.Close() }) + + go func() { + conn, acceptErr := listener.Accept() + if acceptErr != nil { + return + } + defer conn.Close() + reader := bufio.NewReader(conn) + request, readErr := http.ReadRequest(reader) + if readErr != nil { + return + } + sum := sha1.Sum([]byte(request.Header.Get("Sec-WebSocket-Key") + websocketGUID)) + // Echo whatever the client offered: it verifies the server agreed to the + // token it asked for, which follows its codec. + _, _ = fmt.Fprintf(conn, + "HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n"+ + "Sec-WebSocket-Accept: %s\r\nSec-WebSocket-Protocol: %s\r\n"+ + "Sec-WebSocket-Extensions: permessage-deflate; client_no_context_takeover; server_no_context_takeover\r\n\r\n", + base64.StdEncoding.EncodeToString(sum[:]), + firstOfferedSubprotocol(request), + ) + // Server frames are unmasked; FIN | RSV1 | binary. + payload := zeroOutputDeflate(bombCompressed) + header := []byte{0x80 | 0x40 | 0x02, 127, 0, 0, 0, 0, 0, 0, 0, 0} + binary.BigEndian.PutUint64(header[2:10], uint64(len(payload))) + _, _ = conn.Write(header) + _, _ = conn.Write(payload) + // Hold the connection open so any draining by the client is visible. + time.Sleep(2 * time.Second) + }() + return "http://" + listener.Addr().String() +} + +const websocketGUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11" + +// TestCompressionBombFromServerIsBoundedOnTheWire is the client-side mirror: +// a hostile server must not be able to make the client drain an oversized +// frame while closing. +func TestCompressionBombFromServerIsBoundedOnTheWire(t *testing.T) { + t.Parallel() + var clientRead atomic.Int64 + url := hostileServer(t, &clientRead) + + httpClient := &http.Client{Transport: &http.Transport{ + DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) { + conn, err := (&net.Dialer{}).DialContext(ctx, network, addr) + if err != nil { + return nil, err + } + return &countingConn{Conn: conn, read: &clientRead}, nil + }, + }} + transport := connecthttp.NewTransport( + httpClient, + url, + connecthttp.WithWebSocket(connecthttp.SelectAll), + connecthttp.WithReadMaxBytes(bombReadMaxBytes), + ) + client := pingv1connect.NewPingServiceClient(connect.NewClient(transport)) + + stream, err := client.CumSum(t.Context()) + assert.Nil(t, err) + _ = stream.Send(&pingv1.CumSumRequest{Number: 1}) + _, receiveErr := stream.Receive() + assert.NotNil(t, receiveErr) + assert.Equal(t, connect.CodeOf(receiveErr), connect.CodeResourceExhausted) + _ = stream.Close() + + consumed := clientRead.Load() + t.Logf("client consumed %d KiB of an %d KiB bomb (limit %d KiB)", + consumed/1024, bombCompressed/1024, bombReadMaxBytes/1024) + assert.True(t, consumed < bombInflateCeiling) +} diff --git a/internal/wstransport/concurrency_ext_test.go b/internal/wstransport/concurrency_ext_test.go new file mode 100644 index 00000000..2205e0ef --- /dev/null +++ b/internal/wstransport/concurrency_ext_test.go @@ -0,0 +1,162 @@ +// Copyright 2021-2026 The Connect Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package wstransport_test + +import ( + "context" + "errors" + "io" + "net/http" + "net/http/httptest" + "sync" + "testing" + "time" + + "connectrpc.com/connect/v2" + "connectrpc.com/connect/v2/connecthttp" + "connectrpc.com/connect/v2/internal/assert" + pingv1 "connectrpc.com/connect/v2/internal/gen/connect/ping/v1" + "connectrpc.com/connect/v2/internal/gen/connect/ping/v1/pingv1connect" +) + +// newHybridServer2 mounts an arbitrary handler; newHybridServer is fixed to +// pingServer. +func newHybridServer2(tb testing.TB, handler pingv1connect.PingServiceHandler) *httptest.Server { + tb.Helper() + server := connect.NewServer() + pingv1connect.RegisterPingServiceHandler(server, handler) + mux := http.NewServeMux() + connecthttp.Mount(mux, server) + httpServer := httptest.NewServer(mux) + tb.Cleanup(httpServer.Close) + return httpServer +} + +func newBidiClient(tb testing.TB) pingv1connect.PingServiceClient { + tb.Helper() + httpServer := newHybridServer(tb, pingServer{}) + transport := connecthttp.NewTransport( + httpServer.Client(), + httpServer.URL, + connecthttp.WithWebSocket(connecthttp.SelectStreaming), + ) + return pingv1connect.NewPingServiceClient(connect.NewClient(transport)) +} + +// Close is documented as safe to call while a Receive is blocked — "typically +// as defer stream.Close()" — so the two share state by design. +func TestCloseDuringBlockedReceive(t *testing.T) { + t.Parallel() + client := newBidiClient(t) + stream, err := client.CumSum(t.Context()) + assert.Nil(t, err) + assert.Nil(t, stream.Send(&pingv1.CumSumRequest{Number: 1})) + _, err = stream.Receive() + assert.Nil(t, err) + + // Nothing more is coming, so this Receive blocks until Close tears the + // stream down. + received := make(chan error, 1) + go func() { + _, err = stream.Receive() + received <- err + }() + time.Sleep(50 * time.Millisecond) // let the read block + assert.Nil(t, stream.Close()) + + select { + case <-received: + case <-time.After(10 * time.Second): + t.Fatal("Receive did not unblock after Close") + } +} + +// concurrentServer drives its side of the stream from two goroutines, which +// ServerStream permits and no other test here exercises. +type concurrentServer struct { + pingv1connect.UnimplementedPingServiceHandler +} + +func (concurrentServer) CumSum(_ context.Context, stream pingv1connect.PingServiceCumSumServerStream) error { + numbers := make(chan int64, 64) + var receiving sync.WaitGroup + receiving.Add(1) + var receiveErr error + go func() { + defer receiving.Done() + defer close(numbers) + for { + req, err := stream.Receive() + if errors.Is(err, io.EOF) { + return + } + if err != nil { + receiveErr = err + return + } + numbers <- req.Number + } + }() + + var total int64 + for number := range numbers { + total += number + if err := stream.Send(&pingv1.CumSumResponse{Sum: total}); err != nil { + receiving.Wait() + return err + } + } + receiving.Wait() + return receiveErr +} + +func TestBidiConcurrentOnBothSides(t *testing.T) { + t.Parallel() + const messages = 50 + httpServer := newHybridServer2(t, concurrentServer{}) + transport := connecthttp.NewTransport( + httpServer.Client(), + httpServer.URL, + connecthttp.WithWebSocket(connecthttp.SelectStreaming), + ) + client := pingv1connect.NewPingServiceClient(connect.NewClient(transport)) + + stream, err := client.CumSum(t.Context()) + assert.Nil(t, err) + sendErr := make(chan error, 1) + go func() { + for range messages { + if err := stream.Send(&pingv1.CumSumRequest{Number: 1}); err != nil { + sendErr <- err + return + } + } + sendErr <- stream.CloseSend() + }() + + var count int + for { + res, err := stream.Receive() + if errors.Is(err, io.EOF) { + break + } + assert.Nil(t, err) + count++ + assert.Equal(t, res.Sum, int64(count)) + } + assert.Nil(t, <-sendErr) + assert.Nil(t, stream.Close()) + assert.Equal(t, count, messages) +} diff --git a/internal/wstransport/customcodec_ext_test.go b/internal/wstransport/customcodec_ext_test.go new file mode 100644 index 00000000..f78cd893 --- /dev/null +++ b/internal/wstransport/customcodec_ext_test.go @@ -0,0 +1,234 @@ +// Copyright 2021-2026 The Connect Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package wstransport_test + +import ( + "context" + "io" + "net/http" + "net/http/httptest" + "strings" + "sync/atomic" + "testing" + + "connectrpc.com/connect/v2" + "connectrpc.com/connect/v2/connecthttp" + "connectrpc.com/connect/v2/connectproto" + "connectrpc.com/connect/v2/internal/assert" + pingv1 "connectrpc.com/connect/v2/internal/gen/connect/ping/v1" + "connectrpc.com/connect/v2/internal/gen/connect/ping/v1/pingv1connect" + "google.golang.org/protobuf/proto" +) + +// customBinaryCodec is Protobuf binary under a name of its own, so it takes +// the default binary frame type. +type customBinaryCodec struct { + *connectproto.BinaryCodec +} + +func (customBinaryCodec) Name() string { return "custom" } + +// customTextCodec is Protobuf JSON under a name of its own, declared as text. +type customTextCodec struct { + *connectproto.JSONCodec +} + +func (customTextCodec) Name() string { return "customtext" } +func (customTextCodec) IsText() bool { return true } + +// invalidUTF8Codec claims to be text but writes a byte that is never UTF-8. +type invalidUTF8Codec struct { + *connectproto.JSONCodec +} + +func (invalidUTF8Codec) Name() string { return "badtext" } +func (invalidUTF8Codec) IsText() bool { return true } +func (invalidUTF8Codec) MarshalWrite(_ context.Context, dst io.Writer, _ any) error { + _, err := dst.Write([]byte{0xff}) + return err +} + +var ( + _ connecthttp.TextCodec = customTextCodec{} + _ connecthttp.TextCodec = invalidUTF8Codec{} +) + +// newCustomCodecServer serves Ping and CumSum with the default codecs and +// the given extra ones. +func newCustomCodecServer(tb testing.TB, extra ...connect.Codec) *httptest.Server { + tb.Helper() + server := connect.NewServer() + pingv1connect.RegisterPingServiceHandler(server, pingServer{}) + mux := http.NewServeMux() + codecs := append([]connect.Codec{connectproto.NewBinaryCodec(), connectproto.NewJSONCodec()}, extra...) + connecthttp.Mount(mux, server, connecthttp.WithCodecs(codecs...)) + httpServer := httptest.NewServer(mux) + tb.Cleanup(httpServer.Close) + return httpServer +} + +// §4.3: a codec other than proto or json travels as connectrpc.1+ and its +// name, and §6.1: its bodies use the frame type its definition states. +func TestCustomCodecRoundTrips(t *testing.T) { + t.Parallel() + for _, test := range []struct { + codec connect.Codec + text bool + }{ + {codec: customBinaryCodec{connectproto.NewBinaryCodec()}, text: false}, + {codec: customTextCodec{connectproto.NewJSONCodec()}, text: true}, + } { + t.Run(test.codec.Name(), func(t *testing.T) { + t.Parallel() + httpServer := newCustomCodecServer(t, test.codec) + + transport := connecthttp.NewTransport( + httpServer.Client(), + httpServer.URL, + connecthttp.WithWebSocket(connecthttp.SelectAll), + connecthttp.WithCodecs(test.codec), + ) + client := pingv1connect.NewPingServiceClient(connect.NewClient(transport)) + ctx, info := connect.NewClientContext(t.Context()) + response, err := client.Ping(ctx, &pingv1.PingRequest{Number: 7}) + assert.Nil(t, err) + assert.Equal(t, response.Number, int64(7)) + assert.Equal(t, info.Codec, test.codec.Name()) + + // On the wire, the body goes in the codec's frame type both ways. + browser := dialBrowserClientWithToken( + t, httpServer, pingv1connect.PingServicePingProcedure, "connectrpc.1+"+test.codec.Name(), + ) + var payload []byte + if test.text { + payload = []byte(`{"number":"7"}`) + } else { + payload, err = proto.Marshal(&pingv1.PingRequest{Number: 7}) + assert.Nil(t, err) + } + browser.writeMessage(t, wireBody, test.text, payload) + browser.writeJSON(t, wireClientEndStream, nil) + marker, _, _ := browser.readMessage(t) + assert.Equal(t, marker, wireMetadata) + marker, _, text := browser.readMessage(t) + assert.Equal(t, marker, wireBody) + assert.Equal(t, text, test.text) + marker, endStream, _ := browser.readMessage(t) + assert.Equal(t, marker, wireServerEndStream) + assert.False(t, strings.Contains(string(endStream), "error")) + }) + } +} + +// A client offers its other codecs after its send codec, so a server without +// the custom codec answers in one they share and the client follows it. +func TestClientFallsBackFromCustomCodec(t *testing.T) { + t.Parallel() + httpServer := newCustomCodecServer(t) + transport := connecthttp.NewTransport( + httpServer.Client(), + httpServer.URL, + connecthttp.WithWebSocket(connecthttp.SelectAll), + connecthttp.WithCodecs(customBinaryCodec{connectproto.NewBinaryCodec()}, connectproto.NewJSONCodec()), + ) + client := pingv1connect.NewPingServiceClient(connect.NewClient(transport)) + ctx, info := connect.NewClientContext(t.Context()) + response, err := client.Ping(ctx, &pingv1.PingRequest{Number: 3}) + assert.Nil(t, err) + assert.Equal(t, response.Number, int64(3)) + assert.Equal(t, info.Codec, connect.CodecNameJSON) +} + +// Regression: without WithSendCodec, a client sends with the first codec given +// to WithCodecs, over WebSocket as over HTTP. WebSocket used to default to +// proto regardless. +func TestFirstRegisteredCodecIsTheDefaultSendCodec(t *testing.T) { + t.Parallel() + httpServer := newCustomCodecServer(t) + transport := connecthttp.NewTransport( + httpServer.Client(), + httpServer.URL, + connecthttp.WithWebSocket(connecthttp.SelectAll), + connecthttp.WithCodecs(connectproto.NewJSONCodec(), connectproto.NewBinaryCodec()), + ) + client := pingv1connect.NewPingServiceClient(connect.NewClient(transport)) + ctx, info := connect.NewClientContext(t.Context()) + _, err := client.Ping(ctx, &pingv1.PingRequest{Number: 1}) + assert.Nil(t, err) + assert.Equal(t, info.Codec, connect.CodecNameJSON) +} + +// §6.1: a text codec must produce valid UTF-8. A body that is not would make +// the peer fail the connection with 1007, so the sender refuses it instead. +func TestTextCodecMustProduceUTF8(t *testing.T) { + t.Parallel() + codec := invalidUTF8Codec{connectproto.NewJSONCodec()} + httpServer := newCustomCodecServer(t, codec) + transport := connecthttp.NewTransport( + httpServer.Client(), + httpServer.URL, + connecthttp.WithWebSocket(connecthttp.SelectAll), + connecthttp.WithCodecs(codec), + ) + client := pingv1connect.NewPingServiceClient(connect.NewClient(transport)) + _, err := client.Ping(t.Context(), &pingv1.PingRequest{Number: 1}) + if !assert.NotNil(t, err) { + return + } + assert.Equal(t, connect.CodeOf(err), connect.CodeInternal) + assert.True(t, strings.Contains(err.Error(), `codec "badtext" produced invalid UTF-8`)) +} + +// Regression: a send codec whose name no token can carry used to be offered +// as connectrpc.1+proto. It is refused before anything is dialed. +func TestUncarriableSendCodecIsRefusedBeforeDialing(t *testing.T) { + t.Parallel() + var upgrades atomic.Int32 + server := connect.NewServer() + pingv1connect.RegisterPingServiceHandler(server, pingServer{}) + mux := http.NewServeMux() + connecthttp.Mount(mux, server) + httpServer := httptest.NewServer(http.HandlerFunc( + func(responseWriter http.ResponseWriter, request *http.Request) { + if connecthttp.IsWebSocketUpgrade(request) { + upgrades.Add(1) + } + mux.ServeHTTP(responseWriter, request) + }, + )) + t.Cleanup(httpServer.Close) + + transport := connecthttp.NewTransport( + httpServer.Client(), + httpServer.URL, + connecthttp.WithWebSocket(connecthttp.SelectAll), + connecthttp.WithCodecs(upperCaseCodec{connectproto.NewBinaryCodec()}, connectproto.NewBinaryCodec()), + ) + client := pingv1connect.NewPingServiceClient(connect.NewClient(transport)) + _, err := client.Ping(t.Context(), &pingv1.PingRequest{Number: 1}) + if !assert.NotNil(t, err) { + return + } + assert.Equal(t, connect.CodeOf(err), connect.CodeUnknown) + assert.True(t, strings.Contains(err.Error(), `send codec "Custom" has no WebSocket subprotocol`)) + assert.Equal(t, upgrades.Load(), int32(0)) +} + +// upperCaseCodec has a name §4.3 does not allow in a token. +type upperCaseCodec struct { + *connectproto.BinaryCodec +} + +func (upperCaseCodec) Name() string { return "Custom" } diff --git a/internal/wstransport/dial_ext_test.go b/internal/wstransport/dial_ext_test.go new file mode 100644 index 00000000..e8e545f9 --- /dev/null +++ b/internal/wstransport/dial_ext_test.go @@ -0,0 +1,157 @@ +// Copyright 2021-2026 The Connect Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package wstransport_test + +import ( + "context" + "errors" + "io" + "net/http" + "net/http/httptest" + "testing" + "time" + + "connectrpc.com/connect/v2" + "connectrpc.com/connect/v2/connecthttp" + "connectrpc.com/connect/v2/internal/assert" + pingv1 "connectrpc.com/connect/v2/internal/gen/connect/ping/v1" + "connectrpc.com/connect/v2/internal/gen/connect/ping/v1/pingv1connect" +) + +// newFailingClient points a WebSocket-only client at a server that answers +// every request with status, so the handshake fails in a controlled way. +// SelectAll keeps the unary call off the HTTP fallback. +func newFailingClient(tb testing.TB, status int) pingv1connect.PingServiceClient { + tb.Helper() + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(status) + })) + tb.Cleanup(server.Close) + transport := connecthttp.NewTransport( + server.Client(), + server.URL, + connecthttp.WithWebSocket(connecthttp.SelectAll), + ) + return pingv1connect.NewPingServiceClient(connect.NewClient(transport)) +} + +// A failed upgrade must carry the HTTP status through to a Connect code, so a +// caller can tell "no such method" from "try again later". +func TestDialFailureMapsHTTPStatus(t *testing.T) { + t.Parallel() + for _, test := range []struct { + status int + want connect.Code + }{ + {http.StatusBadRequest, connect.CodeInternal}, // 400 + {http.StatusUnauthorized, connect.CodeUnauthenticated}, // 401 + {http.StatusForbidden, connect.CodePermissionDenied}, // 403 + {http.StatusNotFound, connect.CodeUnimplemented}, // 404 + {http.StatusTooManyRequests, connect.CodeUnavailable}, // 429 + {http.StatusBadGateway, connect.CodeUnavailable}, // 502 + {http.StatusServiceUnavailable, connect.CodeUnavailable}, // 503 + {http.StatusGatewayTimeout, connect.CodeUnavailable}, // 504 + {http.StatusTeapot, connect.CodeUnknown}, // anything else + } { + t.Run(http.StatusText(test.status), func(t *testing.T) { + t.Parallel() + client := newFailingClient(t, test.status) + _, err := client.Ping(t.Context(), &pingv1.PingRequest{Number: 1}) + assert.NotNil(t, err) + assert.Equal(t, connect.CodeOf(err), test.want) + }) + } +} + +// No server at all: there is no response to read a status from, so the code +// comes from the dial failure itself. +func TestDialFailureUnreachableServer(t *testing.T) { + t.Parallel() + server := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {})) + url := server.URL + httpClient := server.Client() + server.Close() // nothing is listening from here on + + transport := connecthttp.NewTransport( + httpClient, + url, + connecthttp.WithWebSocket(connecthttp.SelectAll), + ) + client := pingv1connect.NewPingServiceClient(connect.NewClient(transport)) + + _, err := client.Ping(t.Context(), &pingv1.PingRequest{Number: 1}) + assert.NotNil(t, err) + assert.Equal(t, connect.CodeOf(err), connect.CodeUnavailable) +} + +// Cancellation is the caller's doing, so it must not be reported as a +// transport failure a caller might retry. +func TestDialFailureCanceledContext(t *testing.T) { + t.Parallel() + client := newFailingClient(t, http.StatusOK) + ctx, cancel := context.WithCancel(t.Context()) + cancel() + _, err := client.Ping(ctx, &pingv1.PingRequest{Number: 1}) + assert.NotNil(t, err) + assert.Equal(t, connect.CodeOf(err), connect.CodeCanceled) +} + +func TestDialFailureDeadlineExceeded(t *testing.T) { + t.Parallel() + client := newFailingClient(t, http.StatusOK) + ctx, cancel := context.WithTimeout(t.Context(), time.Nanosecond) + defer cancel() + time.Sleep(time.Millisecond) // make sure it really has expired + _, err := client.Ping(ctx, &pingv1.PingRequest{Number: 1}) + assert.NotNil(t, err) + assert.Equal(t, connect.CodeOf(err), connect.CodeDeadlineExceeded) +} + +// A server that drops the connection mid-handshake leaves io.EOF at the bottom +// of the dial error. Callers read io.EOF as a clean end of stream, so a +// receive loop would take the failed call for an empty one that succeeded. +func TestDialFailureDroppedConnectionIsNotEndOfStream(t *testing.T) { + t.Parallel() + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + hijacker, ok := w.(http.Hijacker) + if !ok { + return + } + if conn, _, err := hijacker.Hijack(); err == nil { + _ = conn.Close() + } + })) + t.Cleanup(server.Close) + transport := connecthttp.NewTransport( + server.Client(), + server.URL, + connecthttp.WithWebSocket(connecthttp.SelectAll), + ) + client := pingv1connect.NewPingServiceClient(connect.NewClient(transport)) + + // The dial runs on the opening Send, so the error may come from the call + // itself or, if a transport defers it, from the first Receive. + stream, err := client.CountUp(t.Context(), &pingv1.CountUpRequest{Number: 1}) + if err == nil { + _, err = stream.Receive() + _ = stream.Close() + } + assert.False(t, errors.Is(err, io.EOF), assert.Sprintf("%v", err)) + assert.True(t, errors.Is(err, io.ErrUnexpectedEOF), assert.Sprintf("%v", err)) + assert.Equal(t, connect.CodeOf(err), connect.CodeUnavailable) + + _, err = client.Ping(t.Context(), &pingv1.PingRequest{Number: 1}) + assert.Equal(t, connect.CodeOf(err), connect.CodeUnavailable) +} diff --git a/internal/wstransport/drain.go b/internal/wstransport/drain.go new file mode 100644 index 00000000..3eeb1b85 --- /dev/null +++ b/internal/wstransport/drain.go @@ -0,0 +1,224 @@ +// Copyright 2021-2026 The Connect Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package wstransport + +import ( + "bufio" + "errors" + "io" + "net" + "net/http" + "sync/atomic" + + "github.com/coder/websocket" +) + +// defaultDrainBudget bounds the closing drain of a side with no read limit. +// It matches the 4MiB message limit common to gRPC implementations. +const defaultDrainBudget = 4 << 20 + +// compressedReadMargin is what a message may take on the wire beyond twice its +// size limit, for frame headers, deflate overhead and buffering. Any fixed +// bound keeps a stream of zero-output deflate blocks from being read forever. +const compressedReadMargin = 64 << 10 + +// maxDrainBudget caps the closing drain of a side with a read limit. Draining +// discards without inflating, so a larger limit is no reason to read more. +const maxDrainBudget = 1 << 20 + +var ( + errDrainBudgetSpent = errors.New("closing drain reached its byte limit") + errWireLimit = errors.New("message exceeded its compressed size limit") +) + +// drainLimiter caps how much of a connection is read once this side starts a +// closing handshake. The WebSocket library's handshake reads and discards the +// peer's frames until its Close frame arrives, bounded at five seconds but by +// no number of bytes, so a peer with a compression bomb queued could make the +// drain read all of it. §13.2 asks for a bound on bytes as well as time, and +// this supplies it. +// +// Every method is a no-op on a nil drainLimiter. +// +// It also bounds the compressed bytes of each message read before then +// (§12), which only the connection underneath the library can count. +type drainLimiter struct { + budget int64 + // remaining is negative until the drain begins. + remaining atomic.Int64 + // messageRemaining is what the message being read may still take from the + // connection, or negative between messages. + messageRemaining atomic.Int64 +} + +// newDrainLimiter budgets one message's wire bound (§12), capped, so the rest of +// an oversized message is drained rather than reset away with the S (§13.2). +func newDrainLimiter(readLimit int64) *drainLimiter { + limiter := &drainLimiter{budget: maxDrainBudget} + switch { + case readLimit <= 0: + limiter.budget = defaultDrainBudget + case readLimit < (maxDrainBudget-compressedReadMargin)/2: + limiter.budget = 2*readLimit + compressedReadMargin + } + limiter.remaining.Store(-1) + limiter.messageRemaining.Store(-1) + return limiter +} + +// beginMessage starts bounding what the connection yields for one message at +// twice readLimit plus compressedReadMargin. Bytes the library buffered before +// it are not counted, which the margin covers. +func (l *drainLimiter) beginMessage(readLimit int64) { + if l == nil { + return + } + l.messageRemaining.Store(2*readLimit + compressedReadMargin) +} + +// endMessage stops bounding the message begun by beginMessage. +func (l *drainLimiter) endMessage() { + if l == nil { + return + } + l.messageRemaining.Store(-1) +} + +// begin starts counting reads against the budget. Only the first call counts. +func (l *drainLimiter) begin() { + if l == nil { + return + } + l.remaining.CompareAndSwap(-1, l.budget) +} + +func (l *drainLimiter) read(reader io.Reader, data []byte) (int, error) { + if l == nil { + return reader.Read(data) + } + remaining := l.remaining.Load() + if remaining < 0 { + return l.readMessage(reader, data) + } + if remaining == 0 { + return 0, errDrainBudgetSpent + } + if int64(len(data)) > remaining { + data = data[:remaining] + } + n, err := reader.Read(data) + l.remaining.Add(-int64(n)) + return n, err +} + +// readMessage reads within the current message's compressed bound, if any. +func (l *drainLimiter) readMessage(reader io.Reader, data []byte) (int, error) { + remaining := l.messageRemaining.Load() + if remaining < 0 { + return reader.Read(data) + } + if remaining == 0 { + return 0, errWireLimit + } + if int64(len(data)) > remaining { + data = data[:remaining] + } + n, err := reader.Read(data) + l.messageRemaining.Add(-int64(n)) + return n, err +} + +// closeWithDrain sends a Close frame with code and completes the closing +// handshake, reading at most the limiter's budget while it waits for the +// peer's own Close frame. +func closeWithDrain(conn *websocket.Conn, limiter *drainLimiter, code websocket.StatusCode, reason string) error { + limiter.begin() + return conn.Close(code, reason) +} + +// drainConn is a hijacked server connection whose reads a drainLimiter caps. +type drainConn struct { + net.Conn + + limiter *drainLimiter +} + +func (c *drainConn) Read(data []byte) (int, error) { + return c.limiter.read(c.Conn, data) +} + +// drainResponseWriter hands the WebSocket library a drainConn when it +// hijacks the handshake's connection. +type drainResponseWriter struct { + http.ResponseWriter + + limiter *drainLimiter +} + +func (w *drainResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) { + conn, readWriter, err := http.NewResponseController(w.ResponseWriter).Hijack() + if err != nil { + return nil, nil, err + } + // The library reads what readWriter already buffered, then reads the + // returned connection. + return &drainConn{Conn: conn, limiter: w.limiter}, readWriter, nil +} + +func (w *drainResponseWriter) Unwrap() http.ResponseWriter { + return w.ResponseWriter +} + +// drainBody is the body of a client's 101 response, which is the upgraded +// connection, with its reads capped by a drainLimiter. +type drainBody struct { + io.ReadWriteCloser + + limiter *drainLimiter +} + +func (b *drainBody) Read(data []byte) (int, error) { + return b.limiter.read(b.ReadWriteCloser, data) +} + +// drainRoundTripper caps the reads of the connection that a WebSocket +// handshake upgrades. +type drainRoundTripper struct { + base http.RoundTripper + limiter *drainLimiter +} + +func (t *drainRoundTripper) RoundTrip(request *http.Request) (*http.Response, error) { + response, err := t.base.RoundTrip(request) + if err != nil || response.StatusCode != http.StatusSwitchingProtocols { + return response, err + } + if body, ok := response.Body.(io.ReadWriteCloser); ok { + response.Body = &drainBody{ReadWriteCloser: body, limiter: t.limiter} + } + return response, nil +} + +// withDrainLimiter returns a copy of client whose WebSocket handshakes yield +// connections that limiter caps. +func withDrainLimiter(client *http.Client, limiter *drainLimiter) *http.Client { + limited := *client + base := client.Transport + if base == nil { + base = http.DefaultTransport + } + limited.Transport = &drainRoundTripper{base: base, limiter: limiter} + return &limited +} diff --git a/internal/wstransport/drain_test.go b/internal/wstransport/drain_test.go new file mode 100644 index 00000000..d5e335f6 --- /dev/null +++ b/internal/wstransport/drain_test.go @@ -0,0 +1,69 @@ +// Copyright 2021-2026 The Connect Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package wstransport + +import ( + "errors" + "math" + "strings" + "testing" + + "connectrpc.com/connect/v2/internal/assert" +) + +func TestDrainLimiter(t *testing.T) { + t.Parallel() + limiter := newDrainLimiter(10) + reader := strings.NewReader(strings.Repeat("x", int(limiter.budget)+100)) + buf := make([]byte, 64) + + // Reads before the drain are not counted. + n, err := limiter.read(reader, buf) + assert.Nil(t, err) + assert.Equal(t, n, 64) + + limiter.begin() + var drained int64 + for { + n, err = limiter.read(reader, buf) + drained += int64(n) + if err != nil { + break + } + } + assert.True(t, errors.Is(err, errDrainBudgetSpent)) + assert.Equal(t, drained, limiter.budget) + + // A second begin does not refill the budget. + limiter.begin() + _, err = limiter.read(reader, buf) + assert.True(t, errors.Is(err, errDrainBudgetSpent)) +} + +func TestDrainLimiterBudget(t *testing.T) { + t.Parallel() + // One message's wire bound (§12), whose limit leaves room for the marker. + assert.Equal(t, newDrainLimiter(messageReadLimit(1024)).budget, int64(2*1025+compressedReadMargin)) + // A large limit is capped, and one near the int64 maximum must not overflow. + assert.Equal(t, newDrainLimiter(messageReadLimit(4<<20)).budget, int64(maxDrainBudget)) + assert.Equal(t, newDrainLimiter(math.MaxInt64).budget, int64(maxDrainBudget)) + assert.Equal(t, newDrainLimiter(messageReadLimit(0)).budget, int64(defaultDrainBudget)) + + var limiter *drainLimiter + limiter.begin() + n, err := limiter.read(strings.NewReader("abc"), make([]byte, 8)) + assert.Nil(t, err) + assert.Equal(t, n, 3) +} diff --git a/internal/wstransport/emptystream_ext_test.go b/internal/wstransport/emptystream_ext_test.go new file mode 100644 index 00000000..78d025f5 --- /dev/null +++ b/internal/wstransport/emptystream_ext_test.go @@ -0,0 +1,255 @@ +// Copyright 2021-2026 The Connect Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package wstransport_test + +import ( + "context" + "errors" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "connectrpc.com/connect/v2" + "connectrpc.com/connect/v2/connecthttp" + "connectrpc.com/connect/v2/internal/assert" + pingv1 "connectrpc.com/connect/v2/internal/gen/connect/ping/v1" + "connectrpc.com/connect/v2/internal/gen/connect/ping/v1/pingv1connect" +) + +// scriptedServer sends a fixed number of messages and then either ends the +// stream or fails, so a test can place the error before, after, or instead of +// the messages. Every RPC sets a trailer: the end-of-stream message carries it, and +// a stream that ends the wrong way loses it. +type scriptedServer struct { + pingv1connect.UnimplementedPingServiceHandler + + messages int // messages to send before finishing + err error // returned after those messages; nil ends the stream cleanly +} + +func (s scriptedServer) setTrailer(ctx context.Context) { + if info, ok := connect.CallInfoForServerContext(ctx); ok { + info.ResponseTrailer().Set(trailerKey, "set-by-handler") + } +} + +func (s scriptedServer) CountUp( + ctx context.Context, + _ *pingv1.CountUpRequest, + stream pingv1connect.PingServiceCountUpServerStream, +) error { + s.setTrailer(ctx) + for i := range s.messages { + if err := stream.Send(&pingv1.CountUpResponse{Number: int64(i)}); err != nil { + return err + } + } + return s.err +} + +func (s scriptedServer) CumSum( + ctx context.Context, + stream pingv1connect.PingServiceCumSumServerStream, +) error { + s.setTrailer(ctx) + var sent int + for { + req, err := stream.Receive() + if errors.Is(err, io.EOF) { + return s.err + } + if err != nil { + return err + } + if sent == s.messages { + return s.err + } + if err := stream.Send(&pingv1.CumSumResponse{Sum: req.Number}); err != nil { + return err + } + sent++ + } +} + +func (s scriptedServer) Sum( + ctx context.Context, + stream pingv1connect.PingServiceSumServerStream, +) (*pingv1.SumResponse, error) { + s.setTrailer(ctx) + var total int64 + for { + req, err := stream.Receive() + if errors.Is(err, io.EOF) { + break + } + if err != nil { + return nil, err + } + total += req.Number + } + if s.err != nil { + return nil, s.err + } + return &pingv1.SumResponse{Sum: total}, nil +} + +func newScriptedClient(tb testing.TB, handler scriptedServer) pingv1connect.PingServiceClient { + tb.Helper() + server := connect.NewServer() + pingv1connect.RegisterPingServiceHandler(server, handler) + mux := http.NewServeMux() + connecthttp.Mount(mux, server) + httpServer := httptest.NewServer(mux) + tb.Cleanup(httpServer.Close) + + transport := connecthttp.NewTransport( + httpServer.Client(), + httpServer.URL, + connecthttp.WithWebSocket(connecthttp.SelectAll), + ) + return pingv1connect.NewPingServiceClient(connect.NewClient(transport)) +} + +// A server stream that sends nothing still has to terminate: the client's very +// first Receive is the one that must report io.EOF, with the trailers intact. +func TestServerStreamEndsWithNoMessages(t *testing.T) { + t.Parallel() + client := newScriptedClient(t, scriptedServer{}) + ctx, info := connect.NewClientContext(t.Context()) + stream, err := client.CountUp(ctx, &pingv1.CountUpRequest{Number: 0}) + assert.Nil(t, err) + _, err = stream.Receive() + assert.True(t, errors.Is(err, io.EOF)) + assert.Nil(t, stream.Close()) + assert.Equal(t, info.ResponseTrailer().Get(trailerKey), "set-by-handler") +} + +// Neither side sends a message: the client closes its half immediately and the +// handler returns on the resulting EOF. +func TestBidiEndsWithNoMessagesEitherWay(t *testing.T) { + t.Parallel() + client := newScriptedClient(t, scriptedServer{}) + ctx, info := connect.NewClientContext(t.Context()) + stream, err := client.CumSum(ctx) + assert.Nil(t, err) + assert.Nil(t, stream.CloseSend()) + _, err = stream.Receive() + assert.True(t, errors.Is(err, io.EOF)) + assert.Nil(t, stream.Close()) + assert.Equal(t, info.ResponseTrailer().Get(trailerKey), "set-by-handler") +} + +// A client stream with no messages: the request side opens and closes without +// a single message, and the handler still answers. +func TestClientStreamEndsWithNoMessages(t *testing.T) { + t.Parallel() + client := newScriptedClient(t, scriptedServer{}) + ctx, info := connect.NewClientContext(t.Context()) + stream, err := client.Sum(ctx) + assert.Nil(t, err) + res, err := stream.CloseAndReceive() + assert.Nil(t, err) + assert.Equal(t, res.Sum, int64(0)) + assert.Equal(t, info.ResponseTrailer().Get(trailerKey), "set-by-handler") +} + +// An error with no messages ahead of it must arrive as the error, not as EOF: +// the two are a single message apart on the wire. +func TestServerStreamErrorsBeforeAnyMessage(t *testing.T) { + t.Parallel() + client := newScriptedClient(t, scriptedServer{ + err: connect.NewError(connect.CodeResourceExhausted, "nothing to give"), + }) + ctx, info := connect.NewClientContext(t.Context()) + stream, err := client.CountUp(ctx, &pingv1.CountUpRequest{Number: 0}) + assert.Nil(t, err) + _, err = stream.Receive() + assert.NotNil(t, err) + assert.True(t, !errors.Is(err, io.EOF)) + assert.Equal(t, connect.CodeOf(err), connect.CodeResourceExhausted) + assert.Equal(t, connect.CodeOf(err).String(), "resource_exhausted") + assert.Nil(t, stream.Close()) + assert.Equal(t, info.ResponseTrailer().Get(trailerKey), "set-by-handler") +} + +// Messages already delivered must survive the failure that follows them: a +// caller reads all three, and only then hears why the stream stopped. +func TestServerStreamErrorsAfterMessages(t *testing.T) { + t.Parallel() + client := newScriptedClient(t, scriptedServer{ + messages: 3, + err: connect.NewError(connect.CodeAborted, "gave up partway"), + }) + ctx, info := connect.NewClientContext(t.Context()) + stream, err := client.CountUp(ctx, &pingv1.CountUpRequest{Number: 3}) + assert.Nil(t, err) + for i := range 3 { + res, err := stream.Receive() + assert.Nil(t, err) + assert.Equal(t, res.Number, int64(i)) + } + _, err = stream.Receive() + assert.NotNil(t, err) + assert.Equal(t, connect.CodeOf(err), connect.CodeAborted) + assert.True(t, strings.Contains(err.Error(), "gave up partway")) + assert.Nil(t, stream.Close()) + assert.Equal(t, info.ResponseTrailer().Get(trailerKey), "set-by-handler") +} + +// The bidi shape of the same thing, with traffic in both directions before the +// handler fails: the client's send side is still open when the error arrives. +func TestBidiErrorsAfterMessagesBothWays(t *testing.T) { + t.Parallel() + client := newScriptedClient(t, scriptedServer{ + messages: 2, + err: connect.NewError(connect.CodeInternal, "stopped after two"), + }) + ctx, info := connect.NewClientContext(t.Context()) + stream, err := client.CumSum(ctx) + assert.Nil(t, err) + for i := range 2 { + assert.Nil(t, stream.Send(&pingv1.CumSumRequest{Number: int64(i + 1)})) + res, err := stream.Receive() + assert.Nil(t, err) + assert.Equal(t, res.Sum, int64(i+1)) + } + // The third send is what trips the handler into returning its error. The + // send itself may succeed: it only has to reach the socket. + _ = stream.Send(&pingv1.CumSumRequest{Number: 3}) + _, err = stream.Receive() + assert.NotNil(t, err) + assert.Equal(t, connect.CodeOf(err), connect.CodeInternal) + assert.Nil(t, stream.Close()) + assert.Equal(t, info.ResponseTrailer().Get(trailerKey), "set-by-handler") +} + +// A client stream that fails has no response message at all, so the error has +// to surface from CloseAndReceive rather than from a message read. +func TestClientStreamErrorsWithNoResponse(t *testing.T) { + t.Parallel() + client := newScriptedClient(t, scriptedServer{ + err: connect.NewError(connect.CodeInvalidArgument, "bad sum"), + }) + ctx, info := connect.NewClientContext(t.Context()) + stream, err := client.Sum(ctx) + assert.Nil(t, err) + assert.Nil(t, stream.Send(&pingv1.SumRequest{Number: 1})) + _, err = stream.CloseAndReceive() + assert.NotNil(t, err) + assert.Equal(t, connect.CodeOf(err), connect.CodeInvalidArgument) + assert.Equal(t, info.ResponseTrailer().Get(trailerKey), "set-by-handler") +} diff --git a/internal/wstransport/endstreamspec_ext_test.go b/internal/wstransport/endstreamspec_ext_test.go new file mode 100644 index 00000000..6ad0b23f --- /dev/null +++ b/internal/wstransport/endstreamspec_ext_test.go @@ -0,0 +1,109 @@ +// Copyright 2021-2026 The Connect Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package wstransport_test + +import ( + "context" + "strings" + "testing" + "time" + + "connectrpc.com/connect/v2" + "connectrpc.com/connect/v2/connecthttp" + "connectrpc.com/connect/v2/internal/assert" + pingv1 "connectrpc.com/connect/v2/internal/gen/connect/ping/v1" + "connectrpc.com/connect/v2/internal/gen/connect/ping/v1/pingv1connect" + "connectrpc.com/connect/v2/internal/wstransport" + "github.com/coder/websocket" +) + +// readCloseStatus reads past whatever the server sends until its Close frame. +func readCloseStatus(tb testing.TB, conn *websocket.Conn) websocket.StatusCode { + tb.Helper() + ctx, cancel := readContext(tb) + defer cancel() + for { + if _, _, err := conn.Read(ctx); err != nil { + return websocket.CloseStatus(err) + } + } +} + +// §8 and §12.1: an oversized message after C is still a message after C. It +// cannot be read, so the server closes with 1009 after its S. +func TestOversizedMessageAfterEndOfClientStreamIsRejected(t *testing.T) { + t.Parallel() + httpServer := newServerFor(t, lingeringServer{ + linger: 300 * time.Millisecond, + done: make(chan struct{}), + }, wstransport.WithReadMaxBytes(1024)) + conn := dialCumSum(t, httpServer, "") + sendProtoBody(t, conn, &pingv1.CumSumRequest{Number: 1}) + sendJSONMessage(t, conn, wireClientEndStream, nil) + ctx, cancel := readContext(t) + defer cancel() + // The server hangs up after a bounded drain, so the rest of the write may + // be reset; the verdict and close are already queued. + _ = conn.Write(ctx, websocket.MessageBinary, append([]byte{wireBody}, make([]byte, 4096)...)) + + data := readServerOpening(t, conn) + assert.Equal(t, data[0], wireServerEndStream) + assert.True(t, strings.Contains(string(data), "resource_exhausted"), assert.Sprintf("%s", data)) + assert.Equal(t, readCloseStatus(t, conn), websocket.StatusMessageTooBig) +} + +// §9: the S payload is an EndStreamResponse, a JSON object. null is not one, +// and must not read as success. +func TestNullEndStreamIsAProtocolError(t *testing.T) { + t.Parallel() + url := scriptedResponseServer(t, serverFrame(true, []byte("M[]")), serverFrame(true, []byte("Snull"))) + transport, err := wstransport.NewTransport(url) + assert.Nil(t, err) + client := pingv1connect.NewPingServiceClient(connect.NewClient(transport)) + ctx, cancel := context.WithTimeout(t.Context(), 10*time.Second) + defer cancel() + stream, err := client.CountUp(ctx, &pingv1.CountUpRequest{Number: 1}) + assert.Nil(t, err) + _, err = stream.Receive() + assert.Equal(t, connect.CodeOf(err), connect.CodeInternal) + assert.True(t, err != nil && strings.Contains(err.Error(), "JSON EndStreamMessage object")) + // The scripted server never answers the client's Close frame, so the + // closing handshake waits out its timeout. + go func() { _ = stream.Close() }() +} + +// errorServer fails every RPC with a long message. +type errorServer struct { + pingv1connect.UnimplementedPingServiceHandler +} + +func (errorServer) Ping(context.Context, *pingv1.PingRequest) (*pingv1.PingResponse, error) { + return nil, connect.NewError(connect.CodeFailedPrecondition, strings.Repeat("x", 200)) +} + +// §9: a server ends every stream with exactly one S. The send limit bounds RPC +// messages, so it cannot suppress the verdict. +func TestSendLimitDoesNotSuppressTheVerdict(t *testing.T) { + t.Parallel() + httpServer := newServerFor(t, errorServer{}, wstransport.WithSendMaxBytes(16)) + transport := connecthttp.NewTransport( + httpServer.Client(), + httpServer.URL, + connecthttp.WithWebSocket(connecthttp.SelectAll), + ) + client := pingv1connect.NewPingServiceClient(connect.NewClient(transport)) + _, err := client.Ping(t.Context(), &pingv1.PingRequest{Number: 1}) + assert.Equal(t, connect.CodeOf(err), connect.CodeFailedPrecondition) +} diff --git a/internal/wstransport/error.go b/internal/wstransport/error.go new file mode 100644 index 00000000..671c33e1 --- /dev/null +++ b/internal/wstransport/error.go @@ -0,0 +1,47 @@ +// Copyright 2021-2026 The Connect Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package wstransport + +import ( + "fmt" + + "connectrpc.com/connect/v2" +) + +// errorf returns a [connect.Error] with a formatted message, attaching +// anything wrapped with %w as the local cause. +// +// [connect.Errorf] formats with fmt.Sprintf, which renders %w as %!w(...) and +// drops the cause. The framing code relies on errors.Is reaching io.EOF and +// context cancellation through the returned error, so it needs fmt.Errorf +// semantics plus [connect.Error.WithCause]. +func errorf(code connect.Code, format string, args ...any) *connect.Error { + formatted := fmt.Errorf(format, args...) + connectErr := connect.NewError(code, formatted.Error()) + if wraps(formatted) { + // Attach the whole chain, so multiple %w verbs survive too. + return connectErr.WithCause(formatted) + } + return connectErr +} + +// wraps reports whether err carries a cause that errors.Is should reach. +func wraps(err error) bool { + switch err.(type) { //nolint:errorlint // asking about err itself, not its chain + case interface{ Unwrap() error }, interface{ Unwrap() []error }: + return true + } + return false +} diff --git a/internal/wstransport/fallback_ext_test.go b/internal/wstransport/fallback_ext_test.go new file mode 100644 index 00000000..46d71eba --- /dev/null +++ b/internal/wstransport/fallback_ext_test.go @@ -0,0 +1,114 @@ +// Copyright 2021-2026 The Connect Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package wstransport_test + +import ( + "context" + "net/http" + "net/http/httptest" + "sync/atomic" + "testing" + + "connectrpc.com/connect/v2" + "connectrpc.com/connect/v2/connecthttp" + "connectrpc.com/connect/v2/internal/assert" + pingv1 "connectrpc.com/connect/v2/internal/gen/connect/ping/v1" + "connectrpc.com/connect/v2/internal/gen/connect/ping/v1/pingv1connect" +) + +// newHTTPOnlyServer serves Connect over HTTP with the WebSocket transport +// turned off, so an upgrade attempt fails while ordinary RPCs succeed. That is +// exactly the situation WithFallbackOnUpgradeError exists for: a peer that +// does not speak this transport. +// +// WithoutWebSocket is load-bearing here. Mount registers both transports by +// default, so without it this server would accept the upgrade and the tests +// below would pass without ever reaching the fallback. +func newHTTPOnlyServer(tb testing.TB) (*httptest.Server, *atomic.Int64) { + tb.Helper() + server := connect.NewServer() + pingv1connect.RegisterPingServiceHandler(server, pingServer{}) + mux := http.NewServeMux() + connecthttp.Mount(mux, server, connecthttp.WithoutWebSocket()) + var rpcs atomic.Int64 + counted := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + // Only a real RPC counts; the refused upgrade is a GET. + if r.Method == http.MethodPost { + rpcs.Add(1) + } + mux.ServeHTTP(w, r) + }) + httpServer := httptest.NewServer(counted) + tb.Cleanup(httpServer.Close) + return httpServer, &rpcs +} + +// The retry reaches the HTTP half exactly once, rather than the call happening +// to succeed for some other reason. +func TestFallbackOnUpgradeErrorRetriesOverHTTP(t *testing.T) { + t.Parallel() + httpServer, rpcs := newHTTPOnlyServer(t) + transport := connecthttp.NewTransport( + httpServer.Client(), + httpServer.URL, + connecthttp.WithWebSocket(connecthttp.SelectAll), + connecthttp.WithFallbackOnUpgradeError(), + ) + client := pingv1connect.NewPingServiceClient(connect.NewClient(transport)) + + res, err := client.Ping(t.Context(), &pingv1.PingRequest{Number: 9, Text: "hi"}) + assert.Nil(t, err) + assert.Equal(t, res.Number, int64(9)) + assert.Equal(t, res.Text, "hi") + assert.Equal(t, rpcs.Load(), int64(1)) +} + +// The same server without the option must fail, so the test above cannot pass +// for some reason other than the retry. +func TestWithoutFallbackOnUpgradeErrorTheCallFails(t *testing.T) { + t.Parallel() + httpServer, _ := newHTTPOnlyServer(t) + transport := connecthttp.NewTransport( + httpServer.Client(), + httpServer.URL, + connecthttp.WithWebSocket(connecthttp.SelectAll), + ) + client := pingv1connect.NewPingServiceClient(connect.NewClient(transport)) + + _, err := client.Ping(t.Context(), &pingv1.PingRequest{Number: 9}) + assert.NotNil(t, err) +} + +// A canceled call must not be retried on the fallback: the peer did nothing +// wrong, the caller gave up, and a retry would be work nobody asked for. +func TestFallbackOnUpgradeErrorSkipsRetryWhenCanceled(t *testing.T) { + t.Parallel() + httpServer, rpcs := newHTTPOnlyServer(t) + transport := connecthttp.NewTransport( + httpServer.Client(), + httpServer.URL, + connecthttp.WithWebSocket(connecthttp.SelectAll), + connecthttp.WithFallbackOnUpgradeError(), + ) + client := pingv1connect.NewPingServiceClient(connect.NewClient(transport)) + + ctx, cancel := context.WithCancel(t.Context()) + cancel() + _, err := client.Ping(ctx, &pingv1.PingRequest{Number: 1}) + assert.NotNil(t, err) + assert.Equal(t, connect.CodeOf(err), connect.CodeCanceled) + // The count is the assertion: no RPC reached the HTTP half. + assert.Equal(t, rpcs.Load(), int64(0)) +} diff --git a/internal/wstransport/faultclose_ext_test.go b/internal/wstransport/faultclose_ext_test.go new file mode 100644 index 00000000..5eadb948 --- /dev/null +++ b/internal/wstransport/faultclose_ext_test.go @@ -0,0 +1,176 @@ +// Copyright 2021-2026 The Connect Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package wstransport_test + +import ( + "context" + "net" + "strings" + "testing" + "time" + + "connectrpc.com/connect/v2" + "connectrpc.com/connect/v2/internal/assert" + pingv1 "connectrpc.com/connect/v2/internal/gen/connect/ping/v1" + "connectrpc.com/connect/v2/internal/gen/connect/ping/v1/pingv1connect" + "connectrpc.com/connect/v2/internal/wstransport" +) + +// §5 and §13: a client that reads a protocol error from the server fails the +// RPC and closes with 3102, without being asked to. The reason is what tells +// the server which mistake it made. The RPC fails as Internal, as a malformed +// response does in Connect over HTTP. Two faults have codes of their own: +// invalid UTF-8 is 1007 (§6.1), and an oversized message is 1009 (§12.1). +func TestClientClosesFaultedServerWithCode(t *testing.T) { + t.Parallel() + const readMaxBytes = 1024 + for _, test := range []struct { + name string + frame []byte + // withoutMetadata leaves out the opening M, for a frame that is one. + withoutMetadata bool + wantReason string + // wantCode is the RPC's error code when it is not Internal. + wantCode connect.Code + // wantClose is the close code when it is not 3102. + wantClose int + }{ + // Server frames are unmasked: FIN | text, then the length. + { + name: "unknown marker", + frame: []byte{0x81, 3, 'Z', '{', '}'}, + wantReason: "server sent unknown marker", + }, + { + name: "invalid UTF-8", + frame: []byte{0x81, 3, 'M', '[', 0x80}, + wantReason: "not valid UTF-8", + wantClose: 1007, + }, + { + // §5: whatever its error code, a fault in the server's framing is a + // protocol error, not an ordinary end to the RPC. + name: "client end-stream marker", + frame: []byte{0x81, 1, 'C'}, + wantReason: "only a client may send", + }, + { + name: "bare end-stream", + frame: []byte{0x81, 1, 'S'}, + wantReason: "EndStreamMessage", + }, + { + name: "end-stream not JSON", + frame: []byte{0x81, 4, 'S', 'b', 'a', 'd'}, + wantReason: "EndStreamMessage", + }, + { + name: "bare metadata", + frame: []byte{0x81, 1, 'M'}, + withoutMetadata: true, + wantReason: "empty M message", + }, + { + name: "metadata not JSON", + frame: []byte{0x81, 4, 'M', 'b', 'a', 'd'}, + withoutMetadata: true, + wantReason: "unmarshal M message", + }, + { + // §6.1: M and S are always JSON, so a binary frame is the wrong one + // even when the payload parses. + name: "metadata in a binary frame", + frame: []byte{0x82, 3, 'M', '[', ']'}, + withoutMetadata: true, + wantReason: "M in a binary frame", + }, + { + name: "end-stream in a binary frame", + frame: []byte{0x82, 3, 'S', '{', '}'}, + wantReason: "S in a binary frame", + }, + { + // §12.1: a non-browser client closes with 1009, and the reason + // names the limit. + name: "message past the read limit", + frame: oversizedBinaryFrame(2 * readMaxBytes), + wantReason: "1024", + wantCode: connect.CodeResourceExhausted, + wantClose: 1009, + }, + } { + t.Run(test.name, func(t *testing.T) { + t.Parallel() + listener, err := (&net.ListenConfig{}).Listen(t.Context(), "tcp", "127.0.0.1:0") + assert.Nil(t, err) + t.Cleanup(func() { _ = listener.Close() }) + type closeFrame struct { + code int + reason string + } + closes := make(chan closeFrame, 1) + go func() { + conn, reader := acceptRawUpgrade(t, listener) + if !test.withoutMetadata { + _, _ = conn.Write([]byte{0x81, 3, 'M', '[', ']'}) + } + _, _ = conn.Write(test.frame) + _, code, reason := watchFrames(reader, nil) + closes <- closeFrame{code: code, reason: reason} + _ = conn.Close() + }() + + transport, err := wstransport.NewTransport( + "http://"+listener.Addr().String(), + wstransport.WithReadMaxBytes(readMaxBytes), + ) + assert.Nil(t, err) + client := pingv1connect.NewPingServiceClient(connect.NewClient(transport)) + ctx, cancel := context.WithTimeout(t.Context(), 10*time.Second) + defer cancel() + stream, err := client.CumSum(ctx) + assert.Nil(t, err) + assert.Nil(t, stream.Send(&pingv1.CumSumRequest{Number: 1})) + _, err = stream.Receive() + wantCode := test.wantCode + if wantCode == 0 { + wantCode = connect.CodeInternal + } + assert.Equal(t, connect.CodeOf(err), wantCode) + go func() { _ = stream.Close() }() + + select { + case got := <-closes: + wantClose := test.wantClose + if wantClose == 0 { + wantClose = 3102 + } + assert.Equal(t, got.code, wantClose) + assert.True(t, strings.Contains(got.reason, test.wantReason)) + assert.True(t, len(got.reason) <= 123) + case <-ctx.Done(): + t.Fatal("client did not close the connection") + } + }) + } +} + +// oversizedBinaryFrame is an unmasked binary B frame whose payload is size +// bytes, using the 16-bit extended length. +func oversizedBinaryFrame(size int) []byte { + length := size + 1 + frame := []byte{0x82, 126, byte(length >> 8), byte(length), 'B'} + return append(frame, make([]byte, size)...) +} diff --git a/internal/wstransport/faults_ext_test.go b/internal/wstransport/faults_ext_test.go new file mode 100644 index 00000000..066fc0ef --- /dev/null +++ b/internal/wstransport/faults_ext_test.go @@ -0,0 +1,432 @@ +// Copyright 2021-2026 The Connect Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package wstransport_test + +import ( + "context" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" + "time" + + "connectrpc.com/connect/v2" + "connectrpc.com/connect/v2/connecthttp" + "connectrpc.com/connect/v2/internal/assert" + pingv1 "connectrpc.com/connect/v2/internal/gen/connect/ping/v1" + "connectrpc.com/connect/v2/internal/gen/connect/ping/v1/pingv1connect" + "connectrpc.com/connect/v2/internal/wstransport" + "github.com/coder/websocket" + "google.golang.org/protobuf/proto" +) + +// faultRecorder collects what the protocol error handler was told. +type faultRecorder struct { + mu sync.Mutex + faults []connecthttp.ProtocolFault + peers []string + errors []*connect.Error +} + +func (r *faultRecorder) handle( + peerAddr string, + _ *http.Request, + fault connecthttp.ProtocolFault, + err *connect.Error, +) { + r.mu.Lock() + defer r.mu.Unlock() + r.faults = append(r.faults, fault) + r.peers = append(r.peers, peerAddr) + r.errors = append(r.errors, err) +} + +func (r *faultRecorder) seen() ([]connecthttp.ProtocolFault, []string) { + r.mu.Lock() + defer r.mu.Unlock() + return append([]connecthttp.ProtocolFault(nil), r.faults...), + append([]string(nil), r.peers...) +} + +// newFaultServer mounts a server whose framing faults are reported to recorder. +func newFaultServer(tb testing.TB, recorder *faultRecorder) *httptest.Server { + tb.Helper() + return newFaultServerFor(tb, recorder, pingServer{}) +} + +// newFaultServerFor is newFaultServer with the given handler. +func newFaultServerFor( + tb testing.TB, + recorder *faultRecorder, + handler pingv1connect.PingServiceHandler, +) *httptest.Server { + tb.Helper() + server := connect.NewServer() + pingv1connect.RegisterPingServiceHandler(server, handler) + mux := http.NewServeMux() + connecthttp.Mount(mux, server, + connecthttp.WithReadMaxBytes(1024), + connecthttp.WithWebSocketServerProtocolErrorHandler(recorder.handle), + ) + httpServer := httptest.NewServer(mux) + tb.Cleanup(httpServer.Close) + return httpServer +} + +// Each kind of framing fault must be reported under its own classification. +// The Connect code cannot do this: all but one of these are InvalidArgument, +// and telling them apart otherwise means matching message strings. +func TestProtocolFaultsAreClassified(t *testing.T) { + t.Parallel() + message, err := proto.Marshal(&pingv1.CumSumRequest{Number: 7}) + assert.Nil(t, err) + + for _, test := range []struct { + name string + marker byte + text bool + payload []byte + // raw replaces the whole frame, for a message the marker scheme cannot + // express. + raw []byte + want wstransport.ProtocolFault + }{ + { + name: "unknown marker", + marker: 'Z', + payload: message, + want: connecthttp.FaultMarker, + }, + { + name: "server-only marker", + marker: wireServerEndStream, + text: true, + payload: []byte("{}"), + want: connecthttp.FaultMarker, + }, + { + name: "marker with the reserved high bit set", + // Refused on the first byte, before anything behind it is read. + raw: append([]byte{0x80}, message...), + want: connecthttp.FaultMarker, + }, + { + name: "empty message", + raw: []byte{}, + want: connecthttp.FaultMarker, + }, + { + name: "message past the read limit", + marker: wireBody, + payload: make([]byte, 4096), + want: connecthttp.FaultSizeLimit, + }, + { + name: "malformed metadata", + marker: wireMetadata, + text: true, + payload: []byte("not json"), + want: connecthttp.FaultMetadata, + }, + { + name: "undecodable payload", + marker: wireBody, + payload: []byte{0xff, 0xff, 0xff, 0xff}, + want: connecthttp.FaultMessageEncoding, + }, + { + // A text frame on a connection that negotiated Protobuf. Caught by + // the encoding check before the codec sees the payload. + name: "a body in the encoding the handshake did not agree on", + marker: wireBody, + text: true, + want: connecthttp.FaultFrameType, + }, + } { + t.Run(test.name, func(t *testing.T) { + t.Parallel() + recorder := &faultRecorder{} + httpServer := newFaultServer(t, recorder) + conn := dialCumSum(t, httpServer, "") + + frame := test.raw + if frame == nil { + frame = append([]byte{test.marker}, test.payload...) + } + messageType := websocket.MessageBinary + if test.text { + messageType = websocket.MessageText + } + // The server may hang up before an oversized write finishes; the + // recorder, not the write, says whether the fault arrived. + _ = conn.Write(t.Context(), messageType, frame) + + // Read the server's verdict, which is what makes the fault + // observable to the peer as well as to the monitor. + readCtx, cancelRead := readContext(t) + _, _, readErr := conn.Read(readCtx) + cancelRead() + _ = readErr + + faults, peers := recorder.seen() + assert.Equal(t, faults, []connecthttp.ProtocolFault{test.want}) + for _, peer := range peers { + assert.True(t, strings.HasPrefix(peer, "127.0.0.1:")) + } + }) + } +} + +// §8: a message after C is the client's framing mistake, so the monitor hears +// of it like any other, under the classification its close code reflects. +func TestMessageAfterEndOfClientStreamIsReported(t *testing.T) { + t.Parallel() + message, err := proto.Marshal(&pingv1.CumSumRequest{Number: 2}) + assert.Nil(t, err) + for _, test := range []struct { + name string + payload []byte + want connecthttp.ProtocolFault + wantClose websocket.StatusCode + }{ + { + name: "message", + payload: message, + want: connecthttp.FaultMarker, + wantClose: websocket.StatusProtocolError, + }, + { + name: "message past the read limit", + payload: make([]byte, 4096), + want: connecthttp.FaultSizeLimit, + wantClose: websocket.StatusMessageTooBig, + }, + } { + t.Run(test.name, func(t *testing.T) { + t.Parallel() + recorder := &faultRecorder{} + // The late answer keeps the RPC open until the message after C has + // arrived, so Close is certain to find it. + httpServer := newFaultServerFor(t, recorder, lateAnswerServer{delay: 300 * time.Millisecond}) + conn := dialCumSum(t, httpServer, "") + sendProtoBody(t, conn, &pingv1.CumSumRequest{Number: 1}) + sendJSONMessage(t, conn, wireClientEndStream, nil) + // The server may hang up before an oversized write finishes. + _ = conn.Write(t.Context(), websocket.MessageBinary, append([]byte{wireBody}, test.payload...)) + + // The close follows the S, which follows the report. + assert.Equal(t, readCloseStatus(t, conn), test.wantClose) + faults, _ := recorder.seen() + assert.Equal(t, faults, []connecthttp.ProtocolFault{test.want}) + }) + } +} + +// A well-behaved peer must not be reported at all: the handler is for faults, +// not for traffic. +func TestProtocolErrorHandlerSilentOnCleanTraffic(t *testing.T) { + t.Parallel() + recorder := &faultRecorder{} + httpServer := newFaultServer(t, recorder) + + transport := connecthttp.NewTransport( + httpServer.Client(), + httpServer.URL, + connecthttp.WithWebSocket(connecthttp.SelectStreaming), + ) + client := pingv1connect.NewPingServiceClient(connect.NewClient(transport)) + stream, err := client.CumSum(t.Context()) + assert.Nil(t, err) + assert.Nil(t, stream.Send(&pingv1.CumSumRequest{Number: 1})) + _, err = stream.Receive() + assert.Nil(t, err) + assert.Nil(t, stream.CloseSend()) + assert.Nil(t, stream.Close()) + + faults, _ := recorder.seen() + assert.Equal(t, len(faults), 0) +} + +// clientFaultRecorder is the client-side twin of faultRecorder. +type clientFaultRecorder struct { + mu sync.Mutex + faults []connecthttp.ProtocolFault + procedures []string +} + +func (r *clientFaultRecorder) handle( + spec connect.Spec, + fault wstransport.ProtocolFault, + _ *connect.Error, +) { + r.mu.Lock() + defer r.mu.Unlock() + r.faults = append(r.faults, fault) + r.procedures = append(r.procedures, spec.Procedure) +} + +func (r *clientFaultRecorder) seen() ([]wstransport.ProtocolFault, []string) { + r.mu.Lock() + defer r.mu.Unlock() + return append([]connecthttp.ProtocolFault(nil), r.faults...), + append([]string(nil), r.procedures...) +} + +// misframingServer accepts an upgrade and writes whatever frame the test wants, +// so the client's read path can be driven the way a real server never would. +func misframingServer(tb testing.TB, write func(*websocket.Conn)) *httptest.Server { + tb.Helper() + httpServer := httptest.NewServer(http.HandlerFunc( + func(responseWriter http.ResponseWriter, request *http.Request) { + conn, err := websocket.Accept(responseWriter, request, &websocket.AcceptOptions{ + Subprotocols: []string{"connectrpc.1+proto"}, + InsecureSkipVerify: true, + }) + if err != nil { + return + } + defer func() { _ = conn.CloseNow() }() + // Every response stream opens with an M, so the malformed message + // has to come behind a well-formed one. Without this the client + // refuses the opening itself, and every case below would report + // the same metadata fault rather than the one it provokes. + _ = conn.Write(request.Context(), websocket.MessageText, []byte("M[]")) + write(conn) + // Stay up until the client is done. Closing straight after the + // write would race the client's own frames, and the test would see + // a write failure rather than the fault it asked for. + readCtx, cancel := context.WithTimeout(request.Context(), 5*time.Second) + defer cancel() + for { + if _, _, err := conn.Read(readCtx); err != nil { + return + } + } + }, + )) + tb.Cleanup(httpServer.Close) + return httpServer +} + +// A server that frames its responses wrongly is reported to the client's +// handler, classified the same way a client's mistakes are to the server's. +// The caller sees Internal: InvalidArgument would blame its own request. +func TestClientProtocolFaultsAreClassified(t *testing.T) { + t.Parallel() + message, err := proto.Marshal(&pingv1.CumSumResponse{Sum: 7}) + assert.Nil(t, err) + + for _, test := range []struct { + name string + write func(*websocket.Conn) + want wstransport.ProtocolFault + }{ + { + name: "unknown marker", + write: func(conn *websocket.Conn) { + writeRawFrame(conn, false, 'Z', message) + }, + want: connecthttp.FaultMarker, + }, + { + name: "client-only marker", + write: func(conn *websocket.Conn) { + writeRawFrame(conn, true, wireClientEndStream, nil) + }, + want: connecthttp.FaultMarker, + }, + { + name: "marker with the reserved high bit set", + write: func(conn *websocket.Conn) { + writeRawFrame(conn, false, 0x80, message) + }, + want: connecthttp.FaultMarker, + }, + { + name: "undecodable payload", + write: func(conn *websocket.Conn) { + writeRawFrame(conn, false, wireBody, []byte{0xff, 0xff, 0xff, 0xff}) + }, + want: connecthttp.FaultMessageEncoding, + }, + { + name: "malformed EndStream message", + write: func(conn *websocket.Conn) { + writeRawFrame(conn, true, wireServerEndStream, []byte("not json")) + }, + want: connecthttp.FaultMetadata, + }, + { + name: "null metadata", + write: func(conn *websocket.Conn) { + writeRawFrame(conn, true, wireMetadata, []byte("null")) + }, + want: connecthttp.FaultMetadata, + }, + { + name: "invalid UTF-8 in a text message", + write: func(conn *websocket.Conn) { + writeRawFrame(conn, true, wireMetadata, []byte{'[', 0x80, ']'}) + }, + want: connecthttp.FaultTextEncoding, + }, + { + // The client's twin of the server case above: a text body where the + // subprotocol named Protobuf. + name: "a body in the encoding the handshake did not agree on", + write: func(conn *websocket.Conn) { + writeRawFrame(conn, true, wireBody, nil) + }, + want: connecthttp.FaultFrameType, + }, + } { + t.Run(test.name, func(t *testing.T) { + t.Parallel() + httpServer := misframingServer(t, test.write) + recorder := &clientFaultRecorder{} + transport := connecthttp.NewTransport( + httpServer.Client(), + httpServer.URL, + connecthttp.WithWebSocket(connecthttp.SelectStreaming), + connecthttp.WithWebSocketClientProtocolErrorHandler(recorder.handle), + ) + client := pingv1connect.NewPingServiceClient(connect.NewClient(transport)) + + stream, err := client.CumSum(t.Context()) + assert.Nil(t, err) + t.Cleanup(func() { _ = stream.Close() }) + assert.Nil(t, stream.Send(&pingv1.CumSumRequest{Number: 1})) + _, err = stream.Receive() + assert.NotNil(t, err) + assert.Equal(t, connect.CodeOf(err), connect.CodeInternal) + + faults, procedures := recorder.seen() + assert.Equal(t, faults, []connecthttp.ProtocolFault{test.want}) + assert.Equal(t, procedures, []string{pingv1connect.PingServiceCumSumProcedure}) + }) + } +} + +// writeRawFrame sends one message with an arbitrary marker and frame type, +// which is how a misframing server produces a mistake the transport would not. +func writeRawFrame(conn *websocket.Conn, text bool, marker byte, payload []byte) { + frame := append([]byte{marker}, payload...) + messageType := websocket.MessageBinary + if text { + messageType = websocket.MessageText + } + _ = conn.Write(context.Background(), messageType, frame) +} diff --git a/internal/wstransport/frame_decoder.go b/internal/wstransport/frame_decoder.go new file mode 100644 index 00000000..36a02104 --- /dev/null +++ b/internal/wstransport/frame_decoder.go @@ -0,0 +1,143 @@ +// Copyright 2021-2026 The Connect Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package wstransport + +import ( + "bytes" + "context" + "encoding/json" + "net/http" + + "connectrpc.com/connect/v2" + "github.com/coder/websocket" +) + +// frameDecoder is the inbound framing both ends share: it validates a frame, +// decodes bodies and leading metadata, and classifies each fault the peer's +// framing causes. What a message means in sequence stays with each end. +type frameDecoder struct { + // fromServer is set on a client, whose peer is the server. It names the + // peer in errors and decides who a body the codec rejects blames. + fromServer bool + readMaxBytes int + // fault classifies the most recent peer fault for the protocol error + // monitor. + fault ProtocolFault +} + +func (d *frameDecoder) peer() string { + if d.fromServer { + return "server" + } + return "client" +} + +// fail records what kind of fault this is before building its error, so a +// monitor can tell them apart without matching message strings. +// +// §5 reports a protocol error as Internal. A request body the codec cannot +// decode is not one — the framing was fine — so it keeps Connect-over-HTTP's +// InvalidArgument. On a client that code would blame the caller's request, so +// a malformed response stays Internal, as in Connect over HTTP. +func (d *frameDecoder) fail(fault ProtocolFault, format string, args ...any) *connect.Error { + d.fault = fault + if fault == FaultMessageEncoding && !d.fromServer { + return errorf(connect.CodeInvalidArgument, format, args...) + } + return errorf(connect.CodeInternal, format, args...) +} + +// parseFrame validates a frame and returns the message it carries. On invalid +// UTF-8 it sets fault to FaultTextEncoding, which ends the read path for good. +func (d *frameDecoder) parseFrame(messageType websocket.MessageType, frame []byte) (wireMessage, *connect.Error) { + text := messageType == websocket.MessageText + if !text && messageType != websocket.MessageBinary { + return wireMessage{}, d.fail(FaultFrameType, "unknown WebSocket message type %d", messageType) + } + // §6.1: validated before the marker is read, so that invalid UTF-8 is + // never mistaken for an unknown marker. + if utf8Err := textEncodingError(frame, text); utf8Err != nil { + d.fault = FaultTextEncoding + return wireMessage{}, utf8Err + } + wire, decodeErr := decodeMessage(frame, text) + if decodeErr != nil { + d.fault = FaultMarker + return wireMessage{}, decodeErr + } + // §12: the limit covers the payload, not the marker. + if d.readMaxBytes > 0 && len(wire.payload) > d.readMaxBytes { + d.fault = FaultSizeLimit + return wireMessage{}, errorf( + connect.CodeResourceExhausted, + "message size %d is larger than configured max %d", len(wire.payload), d.readMaxBytes, + ) + } + return wire, nil +} + +// decodeBody decodes a B message's payload with the negotiated codec. +func (d *frameDecoder) decodeBody( + ctx context.Context, + codec connect.Codec, + wire wireMessage, + message any, +) *connect.Error { + bodyIsText := codecIsText(codec) + if wire.text != bodyIsText { + // The subprotocol named one encoding and the frame names another. This + // end may well hold a codec for what arrived, which is exactly why it + // has to be refused rather than decoded: accepting it would let a peer + // choose an encoding the handshake did not agree on (§6.1). + return d.fail( + FaultFrameType, + "%s sent a body in a %s frame; the negotiated %s codec expects a %s frame", + d.peer(), frameName(wire.text), codec.Name(), frameName(bodyIsText), + ) + } + if err := codec.UnmarshalRead(ctx, bytes.NewReader(wire.payload), message); err != nil { + return d.fail(FaultMessageEncoding, "unmarshal message: %w", err) + } + return nil +} + +// metadataEntries parses an M message's payload into its entries, before +// any check on what they name. +func (d *frameDecoder) metadataEntries(payload []byte) ([][]string, *connect.Error) { + // The empty array, never null: an M carries a JSON array, and a bare + // marker is not one. + if len(payload) == 0 { + return nil, d.fail(FaultMetadata, "empty M message; empty metadata is []") + } + var entries [][]string + if err := json.Unmarshal(payload, &entries); err != nil { + return nil, d.fail(FaultMetadata, "unmarshal M message: %w", err) + } + // json.Unmarshal accepts null for a slice; [] decodes to an empty one. + if entries == nil { + return nil, d.fail(FaultMetadata, "M message is null; empty metadata is []") + } + return entries, nil +} + +// metadataHeader turns M message entries into the headers they set. +func (d *frameDecoder) metadataHeader(entries [][]string) (http.Header, *connect.Error) { + meta, err := decodeMetadata(entries) + if err != nil { + d.fault = FaultMetadata + return nil, err + } + return meta, nil +} diff --git a/internal/wstransport/frame_reader.go b/internal/wstransport/frame_reader.go new file mode 100644 index 00000000..9f71e764 --- /dev/null +++ b/internal/wstransport/frame_reader.go @@ -0,0 +1,359 @@ +// Copyright 2021-2026 The Connect Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package wstransport + +import ( + "context" + "errors" + "sync" + "sync/atomic" + "time" + + "github.com/coder/websocket" +) + +// readAheadBytes is how much the reader buffers for a consumer that is not +// receiving. It is what lets the peer's C and Close frame, which queue behind +// any messages it sent, reach this end while a handler is busy (§8.1). Past +// it, the reader stops and backpressure reaches the peer through TCP. +const readAheadBytes = 64 << 10 + +// queuedMessageOverhead is charged per buffered message on top of its bytes, +// so that a stream of tiny messages cannot buffer an unbounded number of them. +const queuedMessageOverhead = 64 + +// frameReader reads a connection on its own goroutine, ahead of its consumer. +// +// The WebSocket library processes control frames only inside a read, so a +// connection read only when the caller receives would leave Pongs unread and +// its peer indistinguishable from a dead one. Reading ahead keeps the socket +// drained of control frames, and lets this end see the connection end while +// the consumer is busy elsewhere. Read-ahead is bounded by readAheadBytes, but +// one message is always read, whatever its size. +// +// It also records when this end last heard from the peer, which is what +// keep-alive judges liveness by. +type frameReader struct { + read func(context.Context) (websocket.MessageType, []byte, error) + onEnded func() + stopped chan struct{} + stop func() + done chan struct{} + // ended is closed as soon as a read fails for any reason but the size + // limit, which is the earliest this end can know the peer has gone. + ended chan struct{} + closeEnds func() + // taken wakes the goroutine when the consumer frees read-ahead room. + taken chan struct{} + + mu sync.Mutex + queue []frameResult + queuedBytes int + // finished is set once the goroutine will add nothing more to queue. + finished bool + // changed is closed and replaced whenever queue or finished changes. + changed chan struct{} + + // waitingSince is when the goroutine began waiting on the socket, or zero + // while read-ahead is full. Silence counts only while it is waiting: a + // backlog is this end's delay, not the peer's. + waitingSince atomic.Int64 + lastHeard atomic.Int64 +} + +// heartbeat forwards the peer's PING and PONG frames to a frameReader as signs +// of life (§4.6). The WebSocket library takes its callbacks at the handshake, +// before the reader exists, so the reader is attached afterwards. Every method +// is a no-op on a nil heartbeat. +type heartbeat struct { + reader atomic.Pointer[frameReader] +} + +func (h *heartbeat) attach(reader *frameReader) { + if h != nil { + h.reader.Store(reader) + } +} + +func (h *heartbeat) heard() { + if h == nil { + return + } + if reader := h.reader.Load(); reader != nil { + reader.heard() + } +} + +// onPing answers every PING, as RFC 6455 §5.5.2 requires. +func (h *heartbeat) onPing(context.Context, []byte) bool { + h.heard() + return true +} + +func (h *heartbeat) onPong(context.Context, []byte) { + h.heard() +} + +// errFrameReaderStopped is what a read after the connection ended returns, +// once the error that ended it has been delivered. +var errFrameReaderStopped = errors.New("websocket reader stopped") + +type frameResult struct { + messageType websocket.MessageType + frame []byte + err error +} + +func (r frameResult) cost() int { + return len(r.frame) + queuedMessageOverhead +} + +// newFrameReader starts reading with read, which runs under ctx. The goroutine +// ends after the first failed read, when ctx is done, or when stop is called. +// onEnded, if not nil, runs on the goroutine when the connection ends. +func newFrameReader( + ctx context.Context, + read func(context.Context) (websocket.MessageType, []byte, error), + onEnded func(), +) *frameReader { + stopped := make(chan struct{}) + ended := make(chan struct{}) + reader := &frameReader{ + read: read, + onEnded: onEnded, + stopped: stopped, + stop: sync.OnceFunc(func() { close(stopped) }), + done: make(chan struct{}), + ended: ended, + closeEnds: sync.OnceFunc(func() { close(ended) }), + taken: make(chan struct{}, 1), + changed: make(chan struct{}), + } + reader.lastHeard.Store(time.Now().UnixNano()) + go reader.run(ctx) + return reader +} + +// next returns the next message, or the error that ended the connection. A +// canceled ctx returns ctx.Err without waiting for the read in flight. +func (r *frameReader) next(ctx context.Context) (websocket.MessageType, []byte, error) { + for { + if err := ctx.Err(); err != nil { + return 0, nil, err + } + result, ok, changed := r.pop() + if ok { + return result.messageType, result.frame, result.err + } + if changed == nil { + return 0, nil, errFrameReaderStopped + } + select { + case <-changed: + case <-ctx.Done(): + return 0, nil, ctx.Err() + } + } +} + +// await blocks until a result is queued or the reader is finished, and reports +// false if ctx ended first. It takes nothing. +func (r *frameReader) await(ctx context.Context) bool { + for { + r.mu.Lock() + ready := len(r.queue) > 0 || r.finished + changed := r.changed + r.mu.Unlock() + if ready { + return true + } + select { + case <-changed: + case <-ctx.Done(): + return false + } + } +} + +// drained reports whether the reader is finished and everything it read has +// been taken. +func (r *frameReader) drained() bool { + r.mu.Lock() + defer r.mu.Unlock() + return r.finished && len(r.queue) == 0 +} + +// nextAfterEnd is next for a reader whose connection has ended: it returns +// what was read before the end, then the error that ended it. It needs no +// context because it never waits. +func (r *frameReader) nextAfterEnd() (websocket.MessageType, []byte, error) { + if result, ok, _ := r.pop(); ok { + return result.messageType, result.frame, result.err + } + return 0, nil, errFrameReaderStopped +} + +// pop takes the oldest unread result. Without one, it returns the channel +// that will signal a change, or nil when the reader is finished. +func (r *frameReader) pop() (frameResult, bool, chan struct{}) { + r.mu.Lock() + if len(r.queue) == 0 { + defer r.mu.Unlock() + if r.finished { + return frameResult{}, false, nil + } + return frameResult{}, false, r.changed + } + result := r.queue[0] + r.queue[0] = frameResult{} + r.queue = r.queue[1:] + r.queuedBytes -= result.cost() + r.mu.Unlock() + select { + case r.taken <- struct{}{}: + default: + } + return result, true, nil +} + +// close stops the goroutine and waits for it. The connection must already be +// closed, or the read in flight will not return. +func (r *frameReader) close() { + r.stop() + <-r.done +} + +// hasEnded reports whether a read has already failed because the connection +// ended. +func (r *frameReader) hasEnded() bool { + if r == nil { + return false + } + select { + case <-r.ended: + return true + default: + return false + } +} + +// connectionEnded reports whether a read has failed because the connection +// ended. A write that just failed may have raced the read that notices, so +// the caller may wait up to grace for it. +func (r *frameReader) connectionEnded(grace time.Duration) bool { + if r == nil { + return false + } + timer := time.NewTimer(grace) + defer timer.Stop() + select { + case <-r.ended: + return true + case <-timer.C: + return false + } +} + +// heard records a sign of life that did not arrive as a message: a Pong. +func (r *frameReader) heard() { + r.lastHeard.Store(time.Now().UnixNano()) +} + +// silence reports how long the goroutine has waited on the socket without +// hearing from the peer. It is zero while read-ahead is full. +func (r *frameReader) silence(now time.Time) time.Duration { + waitingSince := r.waitingSince.Load() + if waitingSince == 0 { + return 0 + } + return now.Sub(time.Unix(0, max(waitingSince, r.lastHeard.Load()))) +} + +func (r *frameReader) run(ctx context.Context) { + defer close(r.done) + defer r.finish(nil) + for { + if !r.awaitRoom(ctx) { + return + } + r.waitingSince.Store(time.Now().UnixNano()) + messageType, frame, err := r.read(ctx) + r.waitingSince.Store(0) + if err == nil { + r.heard() + r.push(frameResult{messageType: messageType, frame: frame}) + continue + } + // Queued before anyone is told, so a consumer woken by the end finds + // the error that caused it. + r.finish(&frameResult{err: err}) + if !errors.Is(err, errMessageTooBig) { + r.closeEnds() + if r.onEnded != nil { + r.onEnded() + } + } + return + } +} + +// awaitRoom waits until read-ahead has room, and reports false if the reader +// was stopped or its context ended first. +func (r *frameReader) awaitRoom(ctx context.Context) bool { + for { + r.mu.Lock() + full := len(r.queue) > 0 && r.queuedBytes >= readAheadBytes + r.mu.Unlock() + if !full { + return true + } + select { + case <-r.taken: + case <-r.stopped: + return false + case <-ctx.Done(): + return false + } + } +} + +func (r *frameReader) push(result frameResult) { + r.mu.Lock() + defer r.mu.Unlock() + r.queue = append(r.queue, result) + r.queuedBytes += result.cost() + r.notifyLocked() +} + +// finish marks the reader finished, queuing last first if there is one. Only +// the first call has any effect. +func (r *frameReader) finish(last *frameResult) { + r.mu.Lock() + defer r.mu.Unlock() + if r.finished { + return + } + if last != nil { + r.queue = append(r.queue, *last) + r.queuedBytes += last.cost() + } + r.finished = true + r.notifyLocked() +} + +func (r *frameReader) notifyLocked() { + close(r.changed) + r.changed = make(chan struct{}) +} diff --git a/internal/wstransport/framing_ext_test.go b/internal/wstransport/framing_ext_test.go new file mode 100644 index 00000000..405d189c --- /dev/null +++ b/internal/wstransport/framing_ext_test.go @@ -0,0 +1,523 @@ +// Copyright 2021-2026 The Connect Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package wstransport_test + +import ( + "context" + "crypto/sha1" + "encoding/base64" + "encoding/binary" + "fmt" + "io" + "net" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "connectrpc.com/connect/v2" + "connectrpc.com/connect/v2/connecthttp" + "connectrpc.com/connect/v2/internal/assert" + pingv1 "connectrpc.com/connect/v2/internal/gen/connect/ping/v1" + "connectrpc.com/connect/v2/internal/gen/connect/ping/v1/pingv1connect" + "connectrpc.com/connect/v2/internal/wstransport" + "github.com/coder/websocket" + "google.golang.org/protobuf/proto" +) + +const pingUnaryProcedure = "/connect.ping.v1.PingService/Ping" + +// WebSocket opcodes, for tests that build frames by hand. +const ( + opcodeContinuation = 0x00 + opcodeText = 0x01 + opcodeBinary = 0x02 + opcodeClose = 0x08 +) + +// readServerFrame reads one frame from the server and reports whether RSV1 is +// set — the bit that says the payload is permessage-deflate compressed. It is +// the only way to observe compression from outside: the library inflates +// transparently, so a decoded message looks the same either way. +func readServerFrame(tb testing.TB, conn net.Conn) (compressed bool, payload []byte) { + tb.Helper() + header := make([]byte, 2) + _, err := io.ReadFull(conn, header) + assert.Nil(tb, err) + compressed = header[0]&0x40 != 0 // RSV1 + // Server frames are never masked. + assert.Equal(tb, header[1]&0x80, byte(0)) + + size := int(header[1] & 0x7F) + switch size { + case 126: + extended := make([]byte, 2) + _, err = io.ReadFull(conn, extended) + assert.Nil(tb, err) + size = int(binary.BigEndian.Uint16(extended)) + case 127: + extended := make([]byte, 8) + _, err = io.ReadFull(conn, extended) + assert.Nil(tb, err) + size = int(binary.BigEndian.Uint64(extended)) + } + payload = make([]byte, size) + _, err = io.ReadFull(conn, payload) + assert.Nil(tb, err) + return compressed, payload +} + +// bodyFor frames a proto message as one B message. +func bodyFor(tb testing.TB, message proto.Message) []byte { + tb.Helper() + encoded, err := proto.Marshal(message) + assert.Nil(tb, err) + return append([]byte{wireBody}, encoded...) +} + +// pingOverRawFrames sends one unary Ping and reports whether the server +// compressed its response. +func pingOverRawFrames(tb testing.TB, text string, options ...wstransport.ServerOption) bool { + tb.Helper() + server := connect.NewServer() + pingv1connect.RegisterPingServiceHandler(server, pingServer{}) + mux := http.NewServeMux() + mountBoth(mux, server, options...) + httpServer := httptest.NewServer(mux) + tb.Cleanup(httpServer.Close) + + addr := httpServer.Listener.Addr().String() + ctx, cancel := context.WithTimeout(tb.Context(), 20*time.Second) + defer cancel() + conn, err := (&net.Dialer{}).DialContext(ctx, "tcp", addr) + assert.Nil(tb, err) + tb.Cleanup(func() { _ = conn.Close() }) + _ = rawHandshake(tb, conn, addr, pingUnaryProcedure) + + assert.Nil(tb, conn.SetDeadline(time.Now().Add(20*time.Second))) + // Every stream opens with Leading-Metadata before anything else. + assert.Nil(tb, writeClientFrame(conn, openMessage(), false, true)) + // The request goes uncompressed: RSV1 is per message, so a peer may send + // plain frames even once the extension is negotiated. + assert.Nil(tb, writeClientFrame(conn, bodyFor(tb, &pingv1.PingRequest{Text: text}), false, false)) + assert.Nil(tb, writeClientFrame(conn, []byte{wireClientEndStream}, false, true)) + + // Past the server's opening M, which is tiny and says nothing about how + // the response body was framed. + _, opening := readServerFrame(tb, conn) + assert.Equal(tb, opening[0], wireMetadata) + + compressed, payload := readServerFrame(tb, conn) + // The response must be the echoed message, not the terminal one. Its + // marker is unreadable here when the frame is compressed, which is the + // case under test, so length is all this can check. + assert.True(tb, len(payload) > 0) + return compressed +} + +// openMessage is the empty M message that starts a stream. +func openMessage() []byte { + return append([]byte{wireMetadata}, []byte("[]")...) +} + +// The server compresses a response comfortably over the threshold and skips +// one under it, since deflate on a tiny payload costs bytes. Raising the +// threshold, or WithoutCompression, turns it off for a payload that would +// otherwise be compressed. +func TestServerCompressionFollowsTheThreshold(t *testing.T) { + t.Parallel() + large := strings.Repeat("compress me ", 1024) // ~12KiB, compressed by default + for _, test := range []struct { + name string + text string + options []wstransport.ServerOption + want bool + }{ + {name: "over the threshold", text: large, want: true}, + {name: "under the threshold", text: "tiny"}, + {name: "threshold raised past it", text: large, options: []wstransport.ServerOption{ + wstransport.WithCompressMinBytes(1 << 20), + }}, + {name: "compression off", text: large, options: []wstransport.ServerOption{ + wstransport.WithoutCompression(), + }}, + } { + t.Run(test.name, func(t *testing.T) { + t.Parallel() + assert.Equal(t, pingOverRawFrames(t, test.text, test.options...), test.want) + }) + } +} + +// A marker that belongs to the other direction is a different mistake from one +// nobody has defined, and the peer can only correct what it is told. S is the +// server's to send; a client sending it has the roles backwards, which +// "unknown marker" would not convey. +func TestWrongDirectionMarkerIsNamedAsSuch(t *testing.T) { + t.Parallel() + for _, test := range []struct { + name string + marker byte + want string + }{ + {"end-stream is server-only", wireServerEndStream, "only a server may send"}, + {"nothing recognized is unknown", 'Z', "unknown marker Z"}, + } { + t.Run(test.name, func(t *testing.T) { + t.Parallel() + httpServer := newHybridServer(t, pingServer{}) + conn := dialCumSum(t, httpServer, "") + sendJSONMessage(t, conn, test.marker, []byte(`{}`)) + + data := readServerOpening(t, conn) + assert.True(t, strings.Contains(string(data), test.want)) + assert.True(t, strings.Contains(string(data), "internal")) + }) + } +} + +// RFC 6455 §8.1 requires every text message to be valid UTF-8, and §6.1 has +// the receiver fail the connection with 1007 and no S message. Nothing below +// this layer checks: a browser peer would sever the connection itself, so a +// server that passed the bytes to a codec would only see the bug in production. +func TestInvalidUTF8InATextMessageIsRejected(t *testing.T) { + t.Parallel() + for _, test := range []struct { + name string + frame []byte + }{ + // A lone continuation byte, which can never begin a sequence. + {name: "bare continuation byte", frame: []byte{wireMetadata, '[', 0x80, ']'}}, + // A truncated three-byte sequence: 0xE2 0x98 wants a third byte. + {name: "truncated sequence", frame: []byte{wireMetadata, 0xE2, 0x98}}, + // 0xFF never appears in UTF-8 at all. + {name: "impossible byte", frame: []byte{wireBody, 0xFF}}, + } { + t.Run(test.name, func(t *testing.T) { + t.Parallel() + recorder := &faultRecorder{} + httpServer := newFaultServer(t, recorder) + conn := dialCumSum(t, httpServer, "") + assert.Nil(t, conn.Write(t.Context(), websocket.MessageText, test.frame)) + + // No M and no S: the first thing back is the close. + readCtx, cancelRead := readContext(t) + defer cancelRead() + _, _, err := conn.Read(readCtx) + assert.Equal(t, websocket.CloseStatus(err), websocket.StatusInvalidFramePayloadData) + assert.True(t, strings.Contains(err.Error(), "not valid UTF-8")) + + faults, _ := recorder.seen() + assert.Equal(t, faults, []connecthttp.ProtocolFault{connecthttp.FaultTextEncoding}) + }) + } +} + +// A text message that is valid UTF-8 passes, so the check above cannot be +// rejecting every text frame. +func TestValidUTF8InATextMessageIsAccepted(t *testing.T) { + t.Parallel() + httpServer := newHybridServer(t, pingServer{}) + client := dialBrowserClientWithToken( + t, httpServer, pingv1connect.PingServicePingProcedure, "connectrpc.1+json") + // Multi-byte runes in a JSON body, since metadata values are ASCII + // (§7.3.1): a snowman and an accented vowel. + client.writeMessage(t, wireBody, true, []byte(`{"text":"☃ café"}`)) + client.writeJSON(t, wireClientEndStream, nil) + + marker, _, _ := client.readMessage(t) + assert.Equal(t, marker, wireMetadata) + marker, body, text := client.readMessage(t) + assert.Equal(t, marker, wireBody) + assert.True(t, text) + assert.True(t, strings.Contains(string(body), "☃ café")) +} + +// §6.1: an empty B payload goes to the codec like any other. Under JSON it +// fails to decode, so it gets the same error as any malformed body. +func TestEmptyJSONBodyIsADecodeFailure(t *testing.T) { + t.Parallel() + for _, test := range []struct { + name string + payload []byte + }{ + {name: "empty", payload: nil}, + {name: "truncated", payload: []byte("{")}, + } { + t.Run(test.name, func(t *testing.T) { + t.Parallel() + httpServer := newHybridServer(t, pingServer{}) + client := dialBrowserClientWithToken( + t, httpServer, pingv1connect.PingServicePingProcedure, "connectrpc.1+json") + client.writeMessage(t, wireBody, true, test.payload) + + marker, _, _ := client.readMessage(t) + assert.Equal(t, marker, wireMetadata) + marker, end, _ := client.readMessage(t) + assert.Equal(t, marker, wireServerEndStream) + assert.True(t, strings.Contains(string(end), "invalid_argument")) + assert.True(t, strings.Contains(string(end), "unmarshal message")) + }) + } +} + +// §13 assigns each fault a close code, and it is the only part of a verdict a +// browser script can read: the WebSocket API hands a script the code, never the +// message body. A more specific code wins over the generic protocol error. +func TestFaultCloseCodeNamesTheFault(t *testing.T) { + t.Parallel() + for _, test := range []struct { + name string + send func(testing.TB, *websocket.Conn) + want websocket.StatusCode + // noEndStream marks the one fault §6.1 closes on without a verdict. + noEndStream bool + }{ + { + name: "unknown marker is a protocol error", + send: func(tb testing.TB, conn *websocket.Conn) { + tb.Helper() + sendJSONMessage(tb, conn, 'Z', []byte(`{}`)) + }, + want: websocket.StatusProtocolError, // 1002 + }, + { + name: "an empty text body is the wrong frame type", + send: func(tb testing.TB, conn *websocket.Conn) { + tb.Helper() + sendJSONMessage(tb, conn, wireBody, nil) + }, + want: websocket.StatusProtocolError, // 1002 + }, + { + name: "invalid UTF-8 in a text message is invalid payload data", + send: func(tb testing.TB, conn *websocket.Conn) { + tb.Helper() + sendJSONMessage(tb, conn, wireMetadata, []byte{'[', 0x80, ']'}) + }, + want: websocket.StatusInvalidFramePayloadData, // 1007 + noEndStream: true, + }, + { + name: "an oversized message is too big", + send: func(tb testing.TB, conn *websocket.Conn) { + tb.Helper() + // The server hangs up after a bounded drain, so the rest of the + // write may be reset; the verdict and close are already queued. + _ = conn.Write(tb.Context(), websocket.MessageBinary, append([]byte{wireBody}, make([]byte, 8192)...)) + }, + want: websocket.StatusMessageTooBig, // 1009 + }, + } { + t.Run(test.name, func(t *testing.T) { + t.Parallel() + server := connect.NewServer() + pingv1connect.RegisterPingServiceHandler(server, pingServer{}) + mux := http.NewServeMux() + connecthttp.Mount(mux, server, connecthttp.WithReadMaxBytes(1024)) + httpServer := httptest.NewServer(mux) + t.Cleanup(httpServer.Close) + + conn := dialCumSum(t, httpServer, "") + test.send(t, conn) + + // The verdict comes first; the code only says which kind it was. + if !test.noEndStream { + data := readServerOpening(t, conn) + assert.Equal(t, data[0], wireServerEndStream) + } + + readCtx, cancelRead := readContext(t) + defer cancelRead() + _, _, err := conn.Read(readCtx) + assert.Equal(t, websocket.CloseStatus(err), test.want) + }) + } +} + +// §13.2: a server that rejects a moderately oversized message drains the rest +// of it before closing. Closing with it unread resets the connection, and +// Windows then discards the S and Close frame the client has yet to read. +func TestServerDrainsAnOversizedMessageBeforeClosing(t *testing.T) { + t.Parallel() + server := connect.NewServer() + pingv1connect.RegisterPingServiceHandler(server, pingServer{}) + mux := http.NewServeMux() + connecthttp.Mount(mux, server, connecthttp.WithReadMaxBytes(1024)) + httpServer := httptest.NewServer(mux) + t.Cleanup(httpServer.Close) + + addr := httpServer.Listener.Addr().String() + conn, err := (&net.Dialer{}).DialContext(t.Context(), "tcp", addr) + assert.Nil(t, err) + t.Cleanup(func() { _ = conn.Close() }) + _ = rawHandshake(t, conn, addr, pingProcedure) + assert.Nil(t, conn.SetDeadline(time.Now().Add(10*time.Second))) + assert.Nil(t, writeClientFrame(conn, openMessage(), false, true)) + _ = writeClientFrame(conn, append([]byte{wireBody}, make([]byte, 32<<10)...), false, false) + + _, closeCode, _ := watchFrames(conn, nil) + assert.Equal(t, closeCode, int(websocket.StatusMessageTooBig)) + _ = writeClientFragment(conn, []byte{0x03, 0xF1}, true, opcodeClose) + // A clean close reads as EOF; a reset reads as an error of its own. + _, err = conn.Read(make([]byte, 1)) + assert.ErrorIs(t, err, io.EOF) +} + +// §6.1: M is always JSON, so an M in a binary frame, which says its payload is +// Protobuf, is the wrong frame type even though its payload parses as JSON. +func TestMetadataInABinaryFrameIsRejected(t *testing.T) { + t.Parallel() + httpServer := newHybridServer(t, pingServer{}) + conn := dialRaw(t, httpServer, pingv1connect.PingServiceCumSumProcedure) + sendWireMessage(t, conn, false, wireMetadata, []byte(`[]`)) + + data := readServerOpening(t, conn) + assert.Equal(t, data[0], wireServerEndStream) + assert.True(t, strings.Contains(string(data), "internal")) + assert.True(t, strings.Contains(string(data), "binary frame")) + readCtx, cancelRead := readContext(t) + defer cancelRead() + _, _, err := conn.Read(readCtx) + assert.Equal(t, websocket.CloseStatus(err), websocket.StatusProtocolError) +} + +// A server that negotiates permessage-deflate without no-context-takeover is +// refused. The server is required not to do it, but a client that trusted the +// server to be conforming would be protected only as far as the peer is — and +// the plaintext leaking across messages would be the client's own. +func TestClientRefusesSharedCompressionContext(t *testing.T) { + t.Parallel() + for _, test := range []struct { + name string + extension string + refuse bool + }{ + { + name: "both directions bounded", + extension: "permessage-deflate; client_no_context_takeover; server_no_context_takeover", + }, + { + name: "no extension at all", + extension: "", + }, + { + name: "plain deflate", + extension: "permessage-deflate", + refuse: true, + }, + { + name: "only the server's side bounded", + extension: "permessage-deflate; server_no_context_takeover", + refuse: true, + }, + } { + t.Run(test.name, func(t *testing.T) { + t.Parallel() + closes := make(chan websocket.CloseError, 1) + httpServer := httptest.NewServer(http.HandlerFunc( + func(responseWriter http.ResponseWriter, request *http.Request) { + handshakeWithExtension(t, responseWriter, request, test.extension, closes) + }, + )) + t.Cleanup(httpServer.Close) + + transport := connecthttp.NewTransport( + httpServer.Client(), + httpServer.URL, + connecthttp.WithWebSocket(connecthttp.SelectStreaming), + ) + client := pingv1connect.NewPingServiceClient(connect.NewClient(transport)) + stream, err := client.CumSum(t.Context()) + assert.Nil(t, err) + sendErr := stream.Send(&pingv1.CumSumRequest{Number: 1}) + + if !test.refuse { + assert.Nil(t, sendErr) + assert.Nil(t, stream.CloseSend()) + return + } + assert.NotNil(t, sendErr) + assert.True(t, strings.Contains(sendErr.Error(), "no-context-takeover")) + // §10: 3102, with the reason naming what the server left out. + select { + case closeErr := <-closes: + assert.Equal(t, closeErr.Code, websocket.StatusCode(3102)) + assert.True(t, strings.Contains(closeErr.Reason, "no_context_takeover")) + case <-time.After(10 * time.Second): + t.Fatal("the client never closed") + } + }) + } +} + +// handshakeWithExtension completes an upgrade by hand, echoing an arbitrary +// Sec-WebSocket-Extensions value that coder's own server would never produce. +// It reports the client's close frame on closes. +func handshakeWithExtension( + tb testing.TB, + responseWriter http.ResponseWriter, + request *http.Request, + extension string, + closes chan<- websocket.CloseError, +) { + tb.Helper() + hijacker, ok := responseWriter.(http.Hijacker) + if !ok { + return + } + conn, _, err := hijacker.Hijack() + if err != nil { + return + } + defer func() { _ = conn.Close() }() + sum := sha1.Sum([]byte(request.Header.Get("Sec-WebSocket-Key") + websocketGUID)) + response := "HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n" + + "Sec-WebSocket-Accept: " + base64.StdEncoding.EncodeToString(sum[:]) + "\r\n" + + "Sec-WebSocket-Protocol: " + firstOfferedSubprotocol(request) + "\r\n" + if extension != "" { + response += "Sec-WebSocket-Extensions: " + extension + "\r\n" + } + if _, err := conn.Write([]byte(response + "\r\n")); err != nil { + return + } + // Hold the connection open so the client's own verdict is what the test + // observes, not a closed socket. + _, code, reason := watchFrames(conn, nil) + closes <- websocket.CloseError{Code: websocket.StatusCode(code), Reason: reason} +} + +// §5.1: every byte but the four markers is unknown, and an unknown marker is a +// protocol error rather than something to skip. Bytes with the high bit set get +// no special treatment; in a binary frame they are simply unknown. +func TestUnassignedMarkersAreUnknown(t *testing.T) { + t.Parallel() + // One of each class: control, letter, DEL, and the high-bit range's ends. + for _, marker := range []byte{0x00, 'A', 0x7F, 0x80, 0xFF} { + t.Run(fmt.Sprintf("0x%02x", marker), func(t *testing.T) { + t.Parallel() + httpServer := newHybridServer(t, pingServer{}) + conn := dialCumSum(t, httpServer, "") + assert.Nil(t, conn.Write(t.Context(), websocket.MessageBinary, + append([]byte{marker}, 0x01))) + + data := readServerOpening(t, conn) + assert.Equal(t, data[0], wireServerEndStream) + assert.True(t, strings.Contains(string(data), "internal")) + assert.True(t, strings.Contains(string(data), "unknown marker")) + }) + } +} diff --git a/internal/wstransport/handler_conn.go b/internal/wstransport/handler_conn.go new file mode 100644 index 00000000..001c7a22 --- /dev/null +++ b/internal/wstransport/handler_conn.go @@ -0,0 +1,514 @@ +// Copyright 2021-2026 The Connect Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package wstransport + +import ( + "context" + "errors" + "io" + "sync" + "time" + + "connectrpc.com/connect/v2" + "connectrpc.com/connect/v2/internal/connecterr" + "github.com/coder/websocket" +) + +// abandonWriteAfter is how long a write may go on after its RPC ends. One that +// takes longer is stuck on a peer that stopped reading, so the connection goes. +const abandonWriteAfter = time.Second + +// peerGoneGrace bounds how long a failed write waits for the reader to notice +// the connection it failed on is gone, which takes microseconds when it is. +const peerGoneGrace = 100 * time.Millisecond + +// websocketHandlerConn is the server's view of one RPC. [session.Serve] wraps +// it in a [connect.ServerStream] and hands that to [connect.Server.Call]. +type websocketHandlerConn struct { + frameDecoder + + // ctx is the RPC's, for both directions. Send, SendHeaders and Receive come + // from the handler, which passes none. + ctx context.Context //nolint:containedctx + wsConn *websocket.Conn + + marshaler messageWriter + + // The read side takes one message per WebSocket frame, handling C and M + // itself before decoding bodies. No read state carries between frames. + reader *frameReader + // keeper is consulted only to say why the connection ended. Nil when + // keep-alive is off. + keeper *keepAlive + // callInfo receives M messages. They arrive after the + // handshake, so this is the only way a browser's metadata reaches the + // handler. + callInfo *connect.CallInfo + // info is carried so a fault can be attributed to the connection that + // produced it; its OnProtocolError is the monitor. Its + // InfrastructureHeaders are what a client may not send in an M message. + info SessionInfo + + // eof stops the read path; sawEndOfClientStream says why it stopped. A + // client that sent C finished, and one whose connection died did not — + // the same condition at the same call site, told apart only by this. + eof bool + sawEndOfClientStream bool + peerFaulted bool + // textEncodingErr ends the read path for good: §6.1 has invalid UTF-8 fail + // the connection outright, with 1007 and no S message, as RFC 6455 §8.1 + // requires. + textEncodingErr *connect.Error + // discardOnce guards the post-C drain, which must not be started twice. + discardOnce sync.Once + // cancelCall ends the RPC when the drain finds a message after C. + cancelCall context.CancelFunc + // afterEndOfStreamMu orders the drain goroutine and Close, which both look + // for a message after C. afterEndOfStream and afterEndOfStreamFault record + // the first one found, which Close reports. + afterEndOfStreamMu sync.Mutex + afterEndOfStream *connect.Error + afterEndOfStreamFault ProtocolFault + + leadingSent bool + // headerErr is a response header the handler set that §7.3.1 does not let + // this server send. + headerErr *connect.Error + // shuttingDown reports that the HTTP server is shutting down, which §13 + // reports as unavailable and closes with 1001. Nil means it never is. + shuttingDown func() bool +} + +// Receive records whether a failure was the peer's doing, which decides how +// the connection is torn down. +func (c *websocketHandlerConn) Receive(msg any) error { + c.fault = faultNone + err := c.unmarshal(c.ctx, msg) + c.reportFault(err) + if err != nil { + return err + } + return nil // literal nil; a nil *Error is a non-nil error +} + +// SendHeaders sends the M message now, before any body (§7.4). Headers set +// after it are late and are not sent. +func (c *websocketHandlerConn) SendHeaders() error { + if err := c.flushLeadingMetadata(c.ctx); err != nil { + return err + } + return nil // literal nil; a nil *Error is a non-nil error +} + +func (c *websocketHandlerConn) Send(msg any) error { + if err := c.flushLeadingMetadata(c.ctx); err != nil { + return err + } + if err := c.marshaler.writeBody(c.ctx, c.info.Codec, msg); err != nil { + return err + } + return nil // literal nil; a nil *Error is a non-nil error +} + +// terminalWriteError decides whether a failed terminal write is worth +// reporting. +// +// It is not when the peer has already left: the write was always going to +// fail, a sender must not assume its S was read anyway, and reporting it would +// log an error for every subscription a client walks away from. +func (c *websocketHandlerConn) terminalWriteError(marshalErr *connect.Error) *connect.Error { + if marshalErr != nil && c.peerGone() { + return nil + } + return marshalErr +} + +// peerGone reports that the read path already saw this connection end without +// the client's C message. Anything written afterwards is written to nobody. +func (c *websocketHandlerConn) peerGone() bool { + // Two ways to lose a peer: it never sent C and stopped reading, or it sent + // C and then went away while the handler was still working. §8 makes no + // distinction — either way the connection ended before S. + if c.reader.hasEnded() { + return true + } + if c.eof && !c.sawEndOfClientStream { + return true + } + // The reader runs ahead of the handler and of the post-C drain, so it can + // see the connection end before either has read the failure. + return c.reader.connectionEnded(peerGoneGrace) +} + +// Close sends the verdict and closes the connection. ctx is the RPC's context, +// and an expired deadline there is often the verdict itself, so the final +// writes run detached from it, bounded by wsCloseWriteTimeout from this call. +func (c *websocketHandlerConn) Close(ctx context.Context, err error) error { + goingAway, err := c.outcome(err) + closeCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), wsCloseWriteTimeout) + defer cancel() + // §6.1: invalid UTF-8 fails the connection outright, with no S message. + if utf8Err := c.textEncodingErr; utf8Err != nil { + _ = closeWithDrain( + c.wsConn, c.info.drain, websocket.StatusInvalidFramePayloadData, closeReason(utf8Err.Message()), + ) + return nil + } + // §8: a connection that ended before S means the caller can no longer + // receive one, so none is attempted. Gated on the reader's own signal, not + // on peerGone: eof is set by any failed read, including an oversized + // message this end refused while its sender waits for the verdict. + if c.reader.hasEnded() { + _ = c.wsConn.CloseNow() + return nil + } + marshalErr, err := c.writeVerdict(closeCtx, err) + closeCode, closeMessage := c.closeStatus(err, marshalErr, goingAway) + // §13: a faulted peer gets the code for its fault too, since a browser + // script can read the code but not the S message. The drain is capped, so + // a peer with a bomb queued behind its fault cannot make this read it all. + _ = closeWithDrain(c.wsConn, c.info.drain, closeCode, closeReason(closeMessage)) + if marshalErr != nil { + return marshalErr + } + return nil +} + +// outcome decides what the RPC's result is, given what the handler returned, +// and reports whether the server shutting down produced it. +func (c *websocketHandlerConn) outcome(err error) (goingAway bool, result error) { + // As over HTTP, only a locally authored *connect.Error reaches the client + // intact, so a handler cannot leak internal text or relay an upstream's + // verdict as its own. + err = connecterr.ScrubHandlerError(err) + // The shutdown canceled the RPC, so the cancellation is the server's, and + // the client may retry elsewhere. + goingAway = err != nil && connect.CodeOf(err) == connect.CodeCanceled && + c.shuttingDown != nil && c.shuttingDown() + if goingAway { + err = errorf(connect.CodeUnavailable, "server is shutting down") + } + // A message after C is the RPC's outcome whatever the handler concluded: + // the peer broke the framing, and §8 makes that a protocol error. One the + // reader has already taken counts, even if the drain has not seen it yet. + if !c.sawEndOfClientStream { + return goingAway, err + } + if afterC, fault := c.checkAfterEndOfStream(); afterC != nil { + err = afterC + c.fault = fault + c.reportFault(afterC) + } + return goingAway, err +} + +// writeVerdict sends the leading metadata if it is still pending, then the S +// message. It returns the write's failure, and the outcome, which an +// unsendable header can replace. +func (c *websocketHandlerConn) writeVerdict(ctx context.Context, err error) (writeErr *connect.Error, result error) { + // Leading metadata precedes the S message even when no body was + // sent, so headers stay headers rather than folding into the trailers. + marshalErr := c.flushLeadingMetadata(ctx) + if marshalErr != nil && marshalErr == c.headerErr { + marshalErr = nil + } + // An unsendable header is the outcome unless the handler reported its own. + if err == nil && c.headerErr != nil { + err = c.headerErr + } + if marshalErr == nil { + marshalErr = c.marshaler.writeEndStream(ctx, err, c.responseTrailer()) + } + return c.terminalWriteError(marshalErr), err +} + +// closeStatus picks the close code and reason that end the connection. +func (c *websocketHandlerConn) closeStatus( + err error, + marshalErr *connect.Error, + goingAway bool, +) (websocket.StatusCode, string) { + switch { + case marshalErr != nil: + return websocket.StatusInternalError, marshalErr.Message() + case c.peerFaulted: + // The S message carries the verdict; the code says which kind of + // mistake it was to a peer that reads codes and not JSON — which is + // every browser script. + var closeMessage string + if connectErr, ok := errors.AsType[*connect.Error](err); ok { + closeMessage = connectErr.Message() + } + return serverCloseCode(c.fault), closeMessage + case goingAway: + return websocket.StatusGoingAway, "" + } + return websocket.StatusNormalClosure, "" +} + +// reportFault hands a framing fault to the monitor. The dispatch loop, +// drainLeadingMetadata, and Close's check for a message after C all detect +// faults, so all must report through here or one would be silently dropped. +// +// Reporting is gated on the classification, not on peerFault: that predicate +// decides how to tear the connection down, and some framing faults are reported +// to the caller as Internal rather than as the peer's fault. Observation only — +// callers return err unchanged. +func (c *websocketHandlerConn) reportFault(err *connect.Error) { + if err == nil { + return + } + if c.fault != faultNone || peerFault(err) { + c.peerFaulted = true + } + if c.fault != faultNone && c.info.OnProtocolError != nil { + c.info.OnProtocolError(c.info, c.fault, err) + } +} + +func (c *websocketHandlerConn) unmarshal(ctx context.Context, message any) *connect.Error { + if c.textEncodingErr != nil { + return c.textEncodingErr + } + if c.eof { + return c.endOfStreamError() + } + wire, readErr := c.nextMessage(ctx) + if readErr != nil { + return readErr + } + return c.dispatch(ctx, wire, message) +} + +// endOfStreamError says why the request stream stopped: the client finished, +// or it went away. +// +// The cancellation deliberately does not wrap the transport's error. A read on +// a closed connection reports io.EOF at the bottom of its chain, and wrapping +// it would make errors.Is(err, io.EOF) true — the test every handler uses to +// learn that a stream ended cleanly. A dead client would read as a finished +// one, and a handler that commits on end-of-stream would commit a truncated +// stream. The text keeps the detail; the chain must not. +func (c *websocketHandlerConn) endOfStreamError() *connect.Error { + if c.sawEndOfClientStream { + return errorf(connect.CodeUnknown, "%w", io.EOF) + } + if c.keeper.timedOut() { + return errorf( + connect.CodeCanceled, + "client sent nothing for %v, not even a Pong (keep-alive timeout)", c.keeper.timeout(), + ) + } + // Canceled rather than Unavailable: the peer stopped, the transport did + // not fail, and a caller should not retry on the client's behalf. + return errorf(connect.CodeCanceled, "websocket closed before end-of-stream") +} + +// nextMessage reads one frame and returns the message it carries. +func (c *websocketHandlerConn) nextMessage(ctx context.Context) (wireMessage, *connect.Error) { + messageType, frame, readerErr := c.reader.next(ctx) + if readerErr != nil && errors.Is(readerErr, context.Canceled) && c.reader.hasEnded() { + // The reader canceled the call because the connection ended. What it + // read before the end is still delivered, in order, and then the end + // itself, so the handler hears why rather than a bare cancellation. + messageType, frame, readerErr = c.reader.nextAfterEnd() + } + if readerErr != nil { + c.eof = true + // The call ended, not the connection: a deadline is deadline_exceeded. + if ctxErr := ctx.Err(); ctxErr != nil && errors.Is(readerErr, ctxErr) { + return wireMessage{}, wsContextError(ctxErr) + } + if errors.Is(readerErr, errMessageTooBig) { + c.fault = FaultSizeLimit + return wireMessage{}, exceedsReadLimit(c.readMaxBytes) + } + if limitErr := peerRejectedAsTooBig(readerErr); limitErr != nil { + c.fault = FaultSizeLimit + return wireMessage{}, limitErr + } + return wireMessage{}, c.endOfStreamError() + } + wire, parseErr := c.parseFrame(messageType, frame) + if c.fault == FaultTextEncoding { + c.textEncodingErr = parseErr + } + return wire, parseErr +} + +// dispatch interprets one message and decodes its payload into message. +func (c *websocketHandlerConn) dispatch(ctx context.Context, wire wireMessage, message any) *connect.Error { + switch wire.marker { + case markerMetadata: + // The opening message was consumed before dispatch; a second one would + // write CallInfo while the handler is already reading it. + return c.fail( + FaultMetadata, + "client sent a second M message; a stream carries exactly one, and it opens the stream", + ) + case markerClientEndStream: + // §6.1: C is a bare control message, always text. The last request + // message travels in a B before it. + if !wire.text { + return c.fail(FaultFrameType, "client sent C in a binary frame; expected a text frame") + } + if len(wire.payload) != 0 { + return c.fail( + FaultMarker, + "client sent C with a %d-byte payload; C carries none, so the last message goes in a B", + len(wire.payload), + ) + } + c.eof = true + c.sawEndOfClientStream = true + c.discardAfterEndOfStream(ctx) + return errorf(connect.CodeUnknown, "%w", io.EOF) + case markerBody: + if err := c.decodeBody(ctx, c.info.Codec, wire, message); err != nil { + return err + } + if c.callInfo != nil { + c.callInfo.ReceiveStats = connect.MessageStats{Size: len(wire.payload)} + } + return nil + case markerServerEndStream: + return c.fail( + FaultMarker, + "client sent %s, which only a server may send", markerName(wire.marker), + ) + default: + return c.fail(FaultMarker, "client sent unknown marker %s", markerName(wire.marker)) + } +} + +// discardAfterEndOfStream reads and throws away whatever the client sends +// after its C message, until the connection closes. +// +// Nothing reads this stream again — Receive returns io.EOF from the flag — so +// without this the socket buffer fills and a peer that keeps sending blocks in +// its own write. Its protocol mistake would become a stall on its side, at the +// point where this end has already decided to ignore it. +// +// Each message is still bounded by the read limit, and the RPC's deadline +// bounds the whole thing, so a peer cannot use this to buy unbounded work. The +// goroutine ends when the context is done or the connection closes, except +// after a protocol error: then it reads until the connection closes. +func (c *websocketHandlerConn) discardAfterEndOfStream(ctx context.Context) { + c.discardOnce.Do(func() { go c.drainAfterEndOfStream(ctx) }) +} + +func (c *websocketHandlerConn) drainAfterEndOfStream(ctx context.Context) { + for c.reader.await(ctx) { + if afterC, _ := c.checkAfterEndOfStream(); afterC != nil { + // §5 has a protocol error end the stream: canceling the call stops + // the handler, and Close sends the S. + if c.cancelCall != nil { + c.cancelCall() + } + c.readUntilClosed(ctx) + return + } + // The connection ended. The reader has already canceled the call (§8). + if c.reader.drained() { + return + } + } +} + +// readUntilClosed discards messages past the call's cancellation, so the peer +// reaches the verdict rather than stalling on a full buffer. +func (c *websocketHandlerConn) readUntilClosed(ctx context.Context) { + uncanceled := context.WithoutCancel(ctx) + for { + if _, _, err := c.reader.next(uncanceled); err != nil { + return + } + } +} + +// checkAfterEndOfStream looks for a message the client sent after C, and +// records the first one as the RPC's outcome (§8). It takes only what has +// already arrived, so Close can call it without waiting. +func (c *websocketHandlerConn) checkAfterEndOfStream() (*connect.Error, ProtocolFault) { + c.afterEndOfStreamMu.Lock() + defer c.afterEndOfStreamMu.Unlock() + if c.afterEndOfStream != nil || c.reader == nil { + return c.afterEndOfStream, c.afterEndOfStreamFault + } + result, ok, _ := c.reader.pop() + if !ok { + return nil, faultNone + } + switch { + case result.err == nil: + c.afterEndOfStream = errorf( + connect.CodeInternal, + "protocol error: client sent a message after its C message", + ) + c.afterEndOfStreamFault = FaultMarker + case errors.Is(result.err, errMessageTooBig): + // Still a message after C, and one over the limit, which §12.1 closes + // with 1009. + c.afterEndOfStream = errorf( + connect.CodeResourceExhausted, + "protocol error: client sent a message after its C message, larger than the %d-byte limit", + c.readMaxBytes, + ) + c.afterEndOfStreamFault = FaultSizeLimit + } + return c.afterEndOfStream, c.afterEndOfStreamFault +} + +// websocketBinarySender is the server's [messageSender]: it writes each +// message as one WebSocket frame rather than appending it to an HTTP response +// body. +type websocketBinarySender struct { + conn *websocket.Conn +} + +func (s *websocketBinarySender) send(ctx context.Context, text bool, data []byte) (int64, error) { + if err := ctx.Err(); err != nil { + return 0, err + } + // Detached, because the library closes the connection when a write's + // context ends, even mid-write, leaving nowhere to send the S that says why. + written := make(chan struct{}) + stop := context.AfterFunc(ctx, func() { + timer := time.NewTimer(abandonWriteAfter) + defer timer.Stop() + select { + case <-timer.C: + _ = s.conn.CloseNow() + case <-written: + } + }) + defer stop() + defer close(written) + return writeFrame(context.WithoutCancel(ctx), s.conn, text, data) +} + +// serverCloseCode is the code §13 assigns each framing fault. A more specific +// one wins over the generic protocol error. +func serverCloseCode(fault ProtocolFault) websocket.StatusCode { + switch fault { + case FaultSizeLimit: + return websocket.StatusMessageTooBig + case FaultTextEncoding: + return websocket.StatusInvalidFramePayloadData + case FaultMarker, FaultFrameType, FaultMetadata, FaultMessageEncoding, faultNone: + return websocket.StatusProtocolError + } + return websocket.StatusProtocolError +} diff --git a/internal/wstransport/handler_metadata.go b/internal/wstransport/handler_metadata.go new file mode 100644 index 00000000..f920239d --- /dev/null +++ b/internal/wstransport/handler_metadata.go @@ -0,0 +1,173 @@ +// Copyright 2021-2026 The Connect Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package wstransport + +import ( + "context" + "errors" + "net/http" + "strings" + + "connectrpc.com/connect/v2" +) + +// errNoOpeningMessage is the cause when a client's opening M does not arrive +// within the handshake timeout. +var errNoOpeningMessage = errors.New("no opening M message") + +// drainLeadingMetadata consumes the single M message that opens +// every stream, so CallInfo is complete and frozen before the handler exists. +// Without it the merge happens on the read path, under the handler, and +// anything the handler does concurrently with its first Receive races that +// write. +// +// Exactly one message, not one-or-more: a drain that kept reading while frames +// were metadata could only discover the end by blocking for a frame the client +// may never send. A receive-only client sends its opening metadata and then +// waits for the server, so the drain must know it is done after one frame. +func (c *websocketHandlerConn) drainLeadingMetadata(ctx context.Context) *connect.Error { + c.fault = faultNone + wire, readErr := c.nextOpeningMessage(ctx) + if readErr != nil { + c.reportFault(readErr) + return readErr + } + if wire.marker != markerMetadata { + // Anything before the opening metadata means the peer is not speaking + // this protocol; there is no partial state worth keeping. + failure := c.fail( + FaultMetadata, + "client's first message must be M; got %s", markerName(wire.marker), + ) + c.reportFault(failure) + return failure + } + // §6.1: M is always JSON, and a binary frame says its payload is not. + if !wire.text { + failure := c.fail(FaultFrameType, "client sent M in a binary frame; expected a text frame") + c.reportFault(failure) + return failure + } + mergeErr := c.mergeLeadingMetadata(wire.payload) + if mergeErr != nil { + c.reportFault(mergeErr) + } + return mergeErr +} + +// nextOpeningMessage reads the client's first message, which must arrive +// within the handshake timeout rather than the RPC's much longer deadline. +func (c *websocketHandlerConn) nextOpeningMessage(callCtx context.Context) (wireMessage, *connect.Error) { + timeout := c.info.HandshakeTimeout + if timeout <= 0 { + return c.nextMessage(callCtx) + } + openingCtx, cancel := context.WithTimeoutCause(callCtx, timeout, errNoOpeningMessage) + defer cancel() + wire, readErr := c.nextMessage(openingCtx) + if readErr != nil && callCtx.Err() == nil && errors.Is(context.Cause(openingCtx), errNoOpeningMessage) { + return wire, errorf( + connect.CodeDeadlineExceeded, "client sent no opening M message within %v", timeout, + ) + } + return wire, readErr +} + +func (c *websocketHandlerConn) mergeLeadingMetadata(payload []byte) *connect.Error { + entries, parseErr := c.metadataEntries(payload) + if parseErr != nil { + return parseErr + } + // Checked against the keys as sent, before canonicalization, so the error + // names the spelling the client used rather than an internal form of it. + // A reserved key ends the RPC rather than being dropped: a client that + // believed it had set an identity header would otherwise never learn that + // the server does not have it. + for _, entry := range entries { + if len(entry) == 0 { + continue // decodeMetadata rejects it + } + if reason, reserved := reservedHeaderReason(entry[0], c.info.InfrastructureHeaders); reserved { + return c.fail( + FaultMetadata, + "client set %q in its M message, which is %s", entry[0], reason, + ) + } + } + meta, decodeErr := c.metadataHeader(entries) + if decodeErr != nil { + return decodeErr + } + // An M key replaces the upgrade request's value, producing the effective + // headers the handler and its interceptors see. What the connection itself + // established is protected by the reserved list above, not by precedence. + header := c.callInfo.RequestHeader() + for key, values := range meta { + header.SetValues(key, values) + } + return nil +} + +// flushLeadingMetadata writes the server's M message. It must run before the +// first body and before the S message alike: a stream that fails without +// sending a body is where leading metadata is most wanted, and there would be +// nothing else to carry it. +// +// It goes out even when there is no metadata, as []. Every stream opens with +// exactly one M in each direction, so a client can read its first message +// without a branch for the empty case — and can take that message as the +// signal that the server has accepted the stream, which is what the response +// header block gives it for free over HTTP. +func (c *websocketHandlerConn) flushLeadingMetadata(ctx context.Context) *connect.Error { + if c.leadingSent { + return nil + } + header := make(http.Header) + // Read at flush time rather than copied in: a handler sets its leading + // metadata during the call, so no earlier snapshot would be current. + if callInfo := c.callInfo; callInfo != nil { + for key, values := range callInfo.ResponseHeader().All() { + // §7.3.2: a server never sends a connect- key in its M. + if isConnectReserved(strings.ToLower(key)) { + continue + } + header[http.CanonicalHeaderKey(key)] = values + } + } + entries, encodeErr := encodeMetadata(header) + if encodeErr != nil { + // The handler set a header this server cannot send (§7.3.1). M still + // opens the stream, empty, and the header becomes the RPC's outcome. + entries = [][]string{} + c.headerErr = encodeErr + } + // Marked only once written, so that Close still opens with M after a + // failed Send. + if err := c.marshaler.writeJSON(ctx, markerMetadata, entries); err != nil { + return err + } + c.leadingSent = true + return c.headerErr +} + +// responseTrailer is what the handler set as trailing metadata. It is read here +// because Close runs once the handler has returned, when it is final. +func (c *websocketHandlerConn) responseTrailer() http.Header { + trailer := make(http.Header) + if callInfo := c.callInfo; callInfo != nil { + copyToHTTPHeader(trailer, callInfo.ResponseTrailer()) + } + return trailer +} diff --git a/internal/wstransport/handlererror_ext_test.go b/internal/wstransport/handlererror_ext_test.go new file mode 100644 index 00000000..84bfb97f --- /dev/null +++ b/internal/wstransport/handlererror_ext_test.go @@ -0,0 +1,132 @@ +// Copyright 2021-2026 The Connect Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package wstransport_test + +import ( + "context" + "errors" + "fmt" + "testing" + + "connectrpc.com/connect/v2" + "connectrpc.com/connect/v2/connecthttp" + "connectrpc.com/connect/v2/connectproto" + "connectrpc.com/connect/v2/internal/assert" + pingv1 "connectrpc.com/connect/v2/internal/gen/connect/ping/v1" + "connectrpc.com/connect/v2/internal/gen/connect/ping/v1/pingv1connect" + "google.golang.org/protobuf/types/known/wrapperspb" +) + +const handlerErrorCaseHeader = "X-Error-Case" + +// handlerErrorServer fails every RPC with the error named by the request's +// X-Error-Case header. +type handlerErrorServer struct { + pingv1connect.UnimplementedPingServiceHandler + + errorsByCase map[string]error +} + +func (s *handlerErrorServer) errorFor(ctx context.Context) error { + info, ok := connect.CallInfoForServerContext(ctx) + if !ok { + return connect.NewError(connect.CodeInternal, "no call info") + } + return s.errorsByCase[info.RequestHeader().Get(handlerErrorCaseHeader)] +} + +func (s *handlerErrorServer) Ping(ctx context.Context, _ *pingv1.PingRequest) (*pingv1.PingResponse, error) { + return nil, s.errorFor(ctx) +} + +func (s *handlerErrorServer) CountUp( + ctx context.Context, + _ *pingv1.CountUpRequest, + _ pingv1connect.PingServiceCountUpServerStream, +) error { + return s.errorFor(ctx) +} + +// A handler's error is scrubbed before it reaches the wire, as it is over +// HTTP: only a locally authored *connect.Error keeps its message and details. +func TestHandlerErrorIsScrubbed(t *testing.T) { + t.Parallel() + detail, detailErr := connectproto.NewErrorDetail(&wrapperspb.StringValue{Value: "upstream detail"}) + assert.Nil(t, detailErr) + remoteErr := connect.NewError(connect.CodePermissionDenied, "upstream secret"). + WithDetail(detail). + WithRemote() + localErr := connect.NewError(connect.CodeInvalidArgument, "bad number").WithDetail(detail) + server := &handlerErrorServer{errorsByCase: map[string]error{ + "plain": errors.New("disk full: /var/data"), + "wrapped": fmt.Errorf("query users: %w", errors.New("pq: connection refused")), + "canceled": fmt.Errorf("copy data: %w", context.Canceled), + "deadline": fmt.Errorf("copy data: %w", context.DeadlineExceeded), + // A handler returning a nil *connect.Error as error boxes a typed nil. + "typed_nil": (*connect.Error)(nil), + "remote": remoteErr, + "local": localErr, + }} + testCases := []struct { + name string + wantCode connect.Code + wantMessage string + wantDetails int + }{ + {name: "plain", wantCode: connect.CodeUnknown}, + {name: "wrapped", wantCode: connect.CodeUnknown}, + {name: "canceled", wantCode: connect.CodeCanceled}, + {name: "deadline", wantCode: connect.CodeDeadlineExceeded}, + {name: "typed_nil", wantCode: connect.CodeUnknown}, + {name: "remote", wantCode: connect.CodeInternal}, + {name: "local", wantCode: connect.CodeInvalidArgument, wantMessage: "bad number", wantDetails: 1}, + } + httpServer := newServerFor(t, server) + transport := connecthttp.NewTransport( + httpServer.Client(), + httpServer.URL, + connecthttp.WithWebSocket(connecthttp.SelectAll), + ) + client := pingv1connect.NewPingServiceClient(connect.NewClient(transport)) + assertError := func(t *testing.T, err error, wantCode connect.Code, wantMessage string, wantDetails int) { + t.Helper() + connectErr, ok := errors.AsType[*connect.Error](err) + if !assert.True(t, ok) { + return + } + assert.Equal(t, connectErr.Code(), wantCode) + assert.Equal(t, connectErr.Message(), wantMessage) + assert.Equal(t, len(connectErr.Details()), wantDetails) + } + for _, testCase := range testCases { + t.Run(testCase.name+"/unary", func(t *testing.T) { + t.Parallel() + ctx, info := connect.NewClientContext(t.Context()) + info.RequestHeader().Set(handlerErrorCaseHeader, testCase.name) + _, err := client.Ping(ctx, &pingv1.PingRequest{}) + assertError(t, err, testCase.wantCode, testCase.wantMessage, testCase.wantDetails) + }) + t.Run(testCase.name+"/server_stream", func(t *testing.T) { + t.Parallel() + ctx, info := connect.NewClientContext(t.Context()) + info.RequestHeader().Set(handlerErrorCaseHeader, testCase.name) + stream, err := client.CountUp(ctx, &pingv1.CountUpRequest{Number: 1}) + assert.Nil(t, err) + _, err = stream.Receive() + assertError(t, err, testCase.wantCode, testCase.wantMessage, testCase.wantDetails) + assert.Nil(t, stream.Close()) + }) + } +} diff --git a/internal/wstransport/handshakeerrors_ext_test.go b/internal/wstransport/handshakeerrors_ext_test.go new file mode 100644 index 00000000..25440cfb --- /dev/null +++ b/internal/wstransport/handshakeerrors_ext_test.go @@ -0,0 +1,184 @@ +// Copyright 2021-2026 The Connect Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package wstransport_test + +import ( + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "connectrpc.com/connect/v2" + "connectrpc.com/connect/v2/connecthttp" + "connectrpc.com/connect/v2/internal/assert" + pingv1 "connectrpc.com/connect/v2/internal/gen/connect/ping/v1" + "connectrpc.com/connect/v2/internal/gen/connect/ping/v1/pingv1connect" + "github.com/coder/websocket" +) + +// pingOverWebSocket makes one unary call to baseURL with everything upgraded, +// and returns its error. +func pingOverWebSocket(tb testing.TB, httpServer *httptest.Server) error { + tb.Helper() + transport := connecthttp.NewTransport( + httpServer.Client(), + httpServer.URL, + connecthttp.WithWebSocket(connecthttp.SelectAll), + ) + client := pingv1connect.NewPingServiceClient(connect.NewClient(transport)) + _, err := client.Ping(tb.Context(), &pingv1.PingRequest{Number: 1}) + return err +} + +// §4.5: a non-browser client that is refused reads the response. A Connect +// error in the body wins; otherwise the status maps as over HTTP. +func TestRejectedHandshakeReportsTheServersError(t *testing.T) { + t.Parallel() + for _, test := range []struct { + name string + status int + contentType string + body string + code connect.Code + mention string + }{ + { + // 400 alone would map to internal, so the body is what decided. + name: "Connect error in the body", + status: http.StatusBadRequest, + contentType: "application/json", + body: `{"code":"unauthenticated","message":"token expired"}`, + code: connect.CodeUnauthenticated, + mention: "token expired", + }, + { + name: "plain body", + status: http.StatusForbidden, + contentType: "text/plain", + body: "origin not allowed", + code: connect.CodePermissionDenied, + }, + { + name: "JSON that is not a Connect error", + status: http.StatusNotFound, + contentType: "application/json", + body: `{"detail":"nope"}`, + code: connect.CodeUnimplemented, + }, + } { + t.Run(test.name, func(t *testing.T) { + t.Parallel() + httpServer := httptest.NewServer(http.HandlerFunc( + func(responseWriter http.ResponseWriter, _ *http.Request) { + responseWriter.Header().Set("Content-Type", test.contentType) + responseWriter.WriteHeader(test.status) + _, _ = responseWriter.Write([]byte(test.body)) + }, + )) + t.Cleanup(httpServer.Close) + + err := pingOverWebSocket(t, httpServer) + if !assert.NotNil(t, err) { + return + } + assert.Equal(t, connect.CodeOf(err), test.code) + if test.mention != "" { + assert.True(t, strings.Contains(err.Error(), test.mention)) + } + }) + } +} + +// §4.3: a server that echoes no subprotocol has failed the handshake, as one +// that echoes a token the client did not offer has. The client drops the +// connection without a Close frame and reports internal. +func TestHandshakeWithoutSubprotocolEchoIsInternal(t *testing.T) { + t.Parallel() + codes := make(chan websocket.CloseError, 1) + httpServer := httptest.NewServer(http.HandlerFunc( + func(responseWriter http.ResponseWriter, request *http.Request) { + // No Subprotocols, so the library echoes none. + conn, err := websocket.Accept(responseWriter, request, nil) + if err != nil { + return + } + defer func() { _ = conn.CloseNow() }() + _, _, readErr := conn.Read(request.Context()) + codes <- closeErrorOf(readErr) + }, + )) + t.Cleanup(httpServer.Close) + + err := pingOverWebSocket(t, httpServer) + if !assert.NotNil(t, err) { + return + } + assert.Equal(t, connect.CodeOf(err), connect.CodeInternal) + assert.True(t, strings.Contains(err.Error(), "echoed no Sec-WebSocket-Protocol")) + select { + case closeErr := <-codes: + // -1: the connection ended without a Close frame. + assert.Equal(t, closeErr.Code, websocket.StatusCode(-1)) + case <-time.After(10 * time.Second): + t.Fatal("the client never closed") + } +} + +// §13.1: a connection that ends without S is a failed RPC, reported as +// Unavailable, whether the server closed it cleanly or dropped it without a +// Close frame. +func TestConnectionEndingWithoutEndStreamIsUnavailable(t *testing.T) { + t.Parallel() + for _, test := range []struct { + name string + end func(*websocket.Conn) error + }{ + {name: "close 1000", end: func(conn *websocket.Conn) error { + return conn.Close(websocket.StatusNormalClosure, "") + }}, + {name: "no Close frame", end: func(conn *websocket.Conn) error { + return conn.CloseNow() + }}, + } { + t.Run(test.name, func(t *testing.T) { + t.Parallel() + httpServer := httptest.NewServer(http.HandlerFunc( + func(responseWriter http.ResponseWriter, request *http.Request) { + conn, err := websocket.Accept(responseWriter, request, &websocket.AcceptOptions{ + Subprotocols: []string{"connectrpc.1+proto"}, + }) + if err != nil { + return + } + // Wait for the client's M, then answer with M and no S. + if _, _, err := conn.Read(request.Context()); err != nil { + _ = conn.CloseNow() + return + } + _ = conn.Write(request.Context(), websocket.MessageText, []byte("M[]")) + _ = test.end(conn) + }, + )) + t.Cleanup(httpServer.Close) + + err := pingOverWebSocket(t, httpServer) + if !assert.NotNil(t, err) { + return + } + assert.Equal(t, connect.CodeOf(err), connect.CodeUnavailable) + }) + } +} diff --git a/internal/wstransport/handshakespec_ext_test.go b/internal/wstransport/handshakespec_ext_test.go new file mode 100644 index 00000000..75d8de9b --- /dev/null +++ b/internal/wstransport/handshakespec_ext_test.go @@ -0,0 +1,126 @@ +// Copyright 2021-2026 The Connect Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package wstransport_test + +import ( + "context" + "net/http" + "net/http/httptest" + "testing" + "time" + + "connectrpc.com/connect/v2" + "connectrpc.com/connect/v2/connecthttp" + "connectrpc.com/connect/v2/internal/assert" + "connectrpc.com/connect/v2/internal/gen/connect/ping/v1/pingv1connect" + "connectrpc.com/connect/v2/internal/wstransport" +) + +// upgradeStatus sends a handshake by hand and returns the response status. +func upgradeStatus(tb testing.TB, url string, header http.Header) int { + tb.Helper() + request, err := http.NewRequestWithContext(tb.Context(), http.MethodGet, url, http.NoBody) + assert.Nil(tb, err) + request.Header = header.Clone() + request.Header.Set("Connection", "Upgrade") + request.Header.Set("Upgrade", "websocket") + request.Header.Set("Sec-WebSocket-Version", "13") + request.Header.Set("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==") + response, err := http.DefaultClient.Do(request) + assert.Nil(tb, err) + _ = response.Body.Close() + return response.StatusCode +} + +func newMountedServer(tb testing.TB, options ...connecthttp.Option) *httptest.Server { + tb.Helper() + server := connect.NewServer() + pingv1connect.RegisterPingServiceHandler(server, pingServer{}) + mux := http.NewServeMux() + connecthttp.Mount(mux, server, options...) + httpServer := httptest.NewServer(mux) + tb.Cleanup(httpServer.Close) + return httpServer +} + +// §4.2: an endpoint restricted to Connect over HTTP rejects a handshake with +// 400, whatever the handshake offered. +func TestHTTPOnlyEndpointRejectsUpgradeWithBadRequest(t *testing.T) { + t.Parallel() + httpServer := newMountedServer(t, connecthttp.WithoutWebSocket()) + for _, offer := range []string{"connectrpc.1+json", "unknown", ""} { + header := http.Header{} + if offer != "" { + header.Set("Sec-WebSocket-Protocol", offer) + } + status := upgradeStatus(t, httpServer.URL+pingv1connect.PingServicePingProcedure, header) + assert.Equal(t, status, http.StatusBadRequest, assert.Sprintf("offer %q", offer)) + } +} + +// §4.4: a browser attaches cookies to a WebSocket handshake and no CORS +// preflight stands in the way, so a cross-origin one is refused with 403. That +// happens before the subprotocol is looked at, whatever it offered. +func TestCrossOriginIsRefusedBeforeNegotiation(t *testing.T) { + t.Parallel() + httpServer := newMountedServer(t) + for _, offer := range []string{"connectrpc.1+json", "unknown"} { + header := http.Header{} + header.Set("Origin", "http://evil.example") + header.Set("Sec-WebSocket-Protocol", offer) + status := upgradeStatus(t, httpServer.URL+pingv1connect.PingServicePingProcedure, header) + assert.Equal(t, status, http.StatusForbidden, assert.Sprintf("offer %q", offer)) + } +} + +// §4.6: any frame from the peer is a sign of life, its own PINGs included. A +// client that pings but never answers the server's PINGs is not hung up on +// while its PINGs keep coming, and is once they stop. +func TestPeerPingsCountAsActivity(t *testing.T) { + t.Parallel() + httpServer := newKeepAliveServer(t, + wstransport.WithKeepAlive(sparedInterval), + wstransport.WithKeepAliveTimeout(sparedTimeout), + ) + conn := openRawCumSum(t, httpServer) + closed := make(chan int, 1) + go func() { + _, closeCode, _ := watchFrames(conn, nil) + closed <- closeCode + }() + + ctx, stopPinging := context.WithTimeout(t.Context(), 5*sparedTimeout) + defer stopPinging() + ticker := time.NewTicker(sparedInterval / 2) + defer ticker.Stop() +pinging: + for { + select { + case <-ctx.Done(): + break pinging + case closeCode := <-closed: + t.Fatalf("server closed with %d while the client was pinging", closeCode) + case <-ticker.C: + assert.Nil(t, writeClientFragment(conn, nil, true, opcodePing)) + } + } + + select { + case closeCode := <-closed: + assert.Equal(t, closeCode, int(1011)) + case <-time.After(wsTestReadTimeout): + t.Fatal("server never hung up on a silent client") + } +} diff --git a/internal/wstransport/header.go b/internal/wstransport/header.go new file mode 100644 index 00000000..6810d169 --- /dev/null +++ b/internal/wstransport/header.go @@ -0,0 +1,29 @@ +// Copyright 2021-2026 The Connect Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package wstransport + +import "net/http" + +// mergeHeaders appends every value in from onto into. +// +// Keys carrying no values are skipped: net/http pre-populates trailer keys +// from the Trailer header, and those placeholders must not become entries. +func mergeHeaders(into, from http.Header) { + for key, values := range from { + for _, value := range values { + into.Add(key, value) + } + } +} diff --git a/internal/wstransport/keepalive.go b/internal/wstransport/keepalive.go new file mode 100644 index 00000000..7f6982cd --- /dev/null +++ b/internal/wstransport/keepalive.go @@ -0,0 +1,152 @@ +// Copyright 2021-2026 The Connect Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package wstransport + +import ( + "context" + "sync" + "sync/atomic" + "time" + + "github.com/coder/websocket" +) + +// keepAliveMisses is the fewest intervals of silence that condemn a peer, +// whatever the timeout. One would hang up on a peer whose Pong was merely slow. +const keepAliveMisses = 2 + +// keepAlive pings the peer on a fixed interval, so that a proxy which drops +// idle connections sees traffic, and hangs up on a peer that has been silent +// for the timeout. +// +// Silence is judged by the frameReader: any message or Pong is a sign of +// life, and time spent with read-ahead full of messages this end has not yet +// taken does not count against the peer. +// +// stop and timedOut are no-ops on a nil keepAlive, which is what a disabled one +// is. +type keepAlive struct { + conn *websocket.Conn + reader *frameReader + interval time.Duration + silentFor time.Duration + closeCode websocket.StatusCode + cancel context.CancelFunc + done chan struct{} + pings sync.WaitGroup + // expired is set before the connection is closed, so the read that fails + // as a result can say why. + expired atomic.Bool + // firstPing is when the first Ping went out, in Unix nanoseconds, or zero. + firstPing atomic.Int64 +} + +// startKeepAlive returns nil when interval is not positive. A timeout shorter +// than keepAliveMisses intervals is raised to that. closeCode is what this side +// sends a silent peer: 1011 from a server, 3102 from a client (§13). +// The pinging ends when ctx is done, when stop is called, or when the +// connection closes. +func startKeepAlive( + ctx context.Context, + conn *websocket.Conn, + reader *frameReader, + interval time.Duration, + timeout time.Duration, + closeCode websocket.StatusCode, +) *keepAlive { + if interval <= 0 { + return nil + } + timeout = max(timeout, keepAliveMisses*interval) + ctx, cancel := context.WithCancel(ctx) + keeper := &keepAlive{ + conn: conn, + reader: reader, + interval: interval, + silentFor: timeout, + closeCode: closeCode, + cancel: cancel, + done: make(chan struct{}), + } + go keeper.run(ctx) + return keeper +} + +// stop ends the pinging and waits for it, so that nothing writes to the +// connection once its owner has let go of it. +func (k *keepAlive) stop() { + if k == nil { + return + } + k.cancel() + <-k.done +} + +// timedOut reports that this end hung up because the peer went silent. +func (k *keepAlive) timedOut() bool { + return k != nil && k.expired.Load() +} + +// timeout is how long a peer may stay silent. +func (k *keepAlive) timeout() time.Duration { + return k.silentFor +} + +func (k *keepAlive) run(ctx context.Context) { + defer close(k.done) + defer k.pings.Wait() + // Runs before the Wait above, so a Ping in flight on a dead connection + // ends now rather than at its timeout. + defer k.cancel() + ticker := time.NewTicker(k.interval) + defer ticker.Stop() + for { + select { + case <-ctx.Done(): + return + case <-k.reader.ended: + // Nothing left to keep alive, and a caller that read to io.EOF + // will never call stop. + return + case now := <-ticker.C: + if k.couldHaveAnswered(now) && k.reader.silence(now) >= k.timeout() { + k.expired.Store(true) + _ = k.conn.Close(k.closeCode, "keep-alive timeout") + return + } + } + k.pings.Go(func() { k.ping(ctx) }) + } +} + +// couldHaveAnswered reports whether a Ping went out an interval or more before +// now. Judged from the send, not the tick: a ping goroutine can start late. +func (k *keepAlive) couldHaveAnswered(now time.Time) bool { + sent := k.firstPing.Load() + return sent != 0 && now.Sub(time.Unix(0, sent)) >= k.interval +} + +// ping sends one Ping and records its Pong. It runs apart from the ticker, and +// waits as long as the peer may stay silent, so that a Pong slower than one +// interval still counts. A missing one is judged by silence rather than here, +// because a peer that sent a message has answered too. +func (k *keepAlive) ping(ctx context.Context) { + pingCtx, cancel := context.WithTimeout(ctx, k.timeout()) + defer cancel() + k.firstPing.CompareAndSwap(0, time.Now().UnixNano()) + if k.conn.Ping(pingCtx) == nil { + k.reader.heard() + } +} diff --git a/internal/wstransport/keepalive_ext_test.go b/internal/wstransport/keepalive_ext_test.go new file mode 100644 index 00000000..8c65d600 --- /dev/null +++ b/internal/wstransport/keepalive_ext_test.go @@ -0,0 +1,454 @@ +// Copyright 2021-2026 The Connect Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package wstransport_test + +import ( + "bufio" + "context" + "crypto/sha1" + "encoding/base64" + "encoding/binary" + "errors" + "io" + "net" + "net/http" + "net/http/httptest" + "os" + "strings" + "sync" + "testing" + "time" + + "connectrpc.com/connect/v2" + "connectrpc.com/connect/v2/connecthttp" + "connectrpc.com/connect/v2/internal/assert" + pingv1 "connectrpc.com/connect/v2/internal/gen/connect/ping/v1" + "connectrpc.com/connect/v2/internal/gen/connect/ping/v1/pingv1connect" + "connectrpc.com/connect/v2/internal/wstransport" +) + +const ( + opcodePing = 0x09 + opcodePong = 0x0A + + // keepAliveInterval is short, for tests that wait for a hang-up. + keepAliveInterval = 20 * time.Millisecond + // sparedInterval leaves room for scheduling delays under -race, for tests + // that a peer must survive: a slow Pong there reads as a dead peer. + sparedInterval = 100 * time.Millisecond + // keepAliveTimeout and sparedTimeout are the shortest the transport allows, + // so the tests still catch a peer wrongly taken for dead. + keepAliveTimeout = 2 * keepAliveInterval + sparedTimeout = 2 * sparedInterval + + // noCloseFrame is what watchFrames reports when the connection ended, or + // its deadline passed, without a close frame. + noCloseFrame = -1 +) + +// nextFrame reads one frame in either direction, unmasking it if needed. The +// library answers control frames itself, so reading the bytes is the only way +// to see a Ping. +func nextFrame(reader io.Reader) (opcode byte, payload []byte, err error) { + header := make([]byte, 2) + if _, err := io.ReadFull(reader, header); err != nil { + return 0, nil, err + } + opcode = header[0] & 0x0F + masked := header[1]&0x80 != 0 + size := uint64(header[1] & 0x7F) + switch size { + case 126: + extended := make([]byte, 2) + if _, err := io.ReadFull(reader, extended); err != nil { + return 0, nil, err + } + size = uint64(binary.BigEndian.Uint16(extended)) + case 127: + extended := make([]byte, 8) + if _, err := io.ReadFull(reader, extended); err != nil { + return 0, nil, err + } + size = binary.BigEndian.Uint64(extended) + } + var mask [4]byte + if masked { + if _, err := io.ReadFull(reader, mask[:]); err != nil { + return 0, nil, err + } + } + payload = make([]byte, size) + if _, err := io.ReadFull(reader, payload); err != nil { + return 0, nil, err + } + if masked { + for index := range payload { + payload[index] ^= mask[index%4] + } + } + return opcode, payload, nil +} + +// watchFrames reads until a close frame arrives or reading fails, counting +// Pings and passing each to answer when it is non-nil. It reports the close +// code and reason, or noCloseFrame. The caller bounds it with a deadline on the +// conn. +func watchFrames(reader io.Reader, answer func(payload []byte)) (pings, closeCode int, reason string) { + for { + opcode, payload, err := nextFrame(reader) + if err != nil { + return pings, noCloseFrame, "" + } + switch opcode { + case opcodePing: + pings++ + if answer != nil { + answer(payload) + } + case opcodeClose: + if len(payload) < 2 { + return pings, noCloseFrame, "" + } + return pings, int(binary.BigEndian.Uint16(payload)), string(payload[2:]) + } + } +} + +// newKeepAliveServer serves the ping service with the given server options. +func newKeepAliveServer(tb testing.TB, options ...wstransport.ServerOption) *httptest.Server { + tb.Helper() + server := connect.NewServer() + pingv1connect.RegisterPingServiceHandler(server, pingServer{}) + mux := http.NewServeMux() + mountBoth(mux, server, options...) + httpServer := httptest.NewServer(mux) + tb.Cleanup(httpServer.Close) + return httpServer +} + +// openRawCumSum upgrades by hand and opens a CumSum stream, leaving the +// handler blocked in Receive so the server sends nothing of its own. +func openRawCumSum(tb testing.TB, httpServer *httptest.Server) net.Conn { + tb.Helper() + addr := httpServer.Listener.Addr().String() + conn, err := (&net.Dialer{}).DialContext(tb.Context(), "tcp", addr) + assert.Nil(tb, err) + tb.Cleanup(func() { _ = conn.Close() }) + _ = rawHandshake(tb, conn, addr, pingProcedure) + assert.Nil(tb, writeClientFrame(conn, openMessage(), false, true)) + return conn +} + +// A client that goes silent is sent 1011 once the timeout passes with nothing +// from it, the Pings in between notwithstanding. The timeout is its own +// setting, not a count of intervals: a longer one means more Pings first. +func TestServerHangsUpOnSilentClient(t *testing.T) { + t.Parallel() + for _, test := range []struct { + name string + timeout time.Duration + minPings int + }{ + {name: "shortest timeout", timeout: keepAliveTimeout, minPings: 1}, + {name: "ten intervals", timeout: 10 * keepAliveInterval, minPings: 5}, + } { + t.Run(test.name, func(t *testing.T) { + t.Parallel() + httpServer := newKeepAliveServer(t, + wstransport.WithKeepAlive(keepAliveInterval), + wstransport.WithKeepAliveTimeout(test.timeout), + ) + conn := openRawCumSum(t, httpServer) + + assert.Nil(t, conn.SetReadDeadline(time.Now().Add(10*time.Second))) + pings, closeCode, _ := watchFrames(conn, nil) + assert.True(t, pings >= test.minPings, assert.Sprintf("%d pings", pings)) + assert.Equal(t, closeCode, 1011) + }) + } +} + +// A Pong is a sign of life on its own: a client that sends no messages but +// answers every Ping outlives many timeouts. +func TestServerSparesClientThatAnswersPings(t *testing.T) { + t.Parallel() + httpServer := newKeepAliveServer(t, + wstransport.WithKeepAlive(sparedInterval), + wstransport.WithKeepAliveTimeout(sparedTimeout), + ) + conn := openRawCumSum(t, httpServer) + + assert.Nil(t, conn.SetReadDeadline(time.Now().Add(6*sparedInterval))) + pings, closeCode, _ := watchFrames(conn, func(payload []byte) { + _ = writeClientFragment(conn, payload, true, opcodePong) + }) + assert.Equal(t, closeCode, noCloseFrame) + assert.True(t, pings >= 3) +} + +func TestZeroKeepAliveSendsNoPings(t *testing.T) { + t.Parallel() + httpServer := newKeepAliveServer(t, wstransport.WithKeepAlive(0)) + conn := openRawCumSum(t, httpServer) + + assert.Nil(t, conn.SetReadDeadline(time.Now().Add(10*keepAliveInterval))) + _, err := conn.Read(make([]byte, 1)) + assert.True(t, errors.Is(err, os.ErrDeadlineExceeded)) +} + +// acceptRawUpgrade completes one WebSocket handshake by hand, so the test can +// see the client's frames before any library interprets them. The returned +// reader holds whatever the client sent after the request. +func acceptRawUpgrade(tb testing.TB, listener net.Listener) (net.Conn, *bufio.Reader) { + tb.Helper() + conn, err := listener.Accept() + assert.Nil(tb, err) + tb.Cleanup(func() { _ = conn.Close() }) + assert.Nil(tb, conn.SetDeadline(time.Now().Add(10*time.Second))) + reader := bufio.NewReader(conn) + request, err := http.ReadRequest(reader) + assert.Nil(tb, err) + digest := sha1.Sum([]byte(request.Header.Get("Sec-WebSocket-Key") + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11")) + _, err = conn.Write([]byte("HTTP/1.1 101 Switching Protocols\r\n" + + "Upgrade: websocket\r\nConnection: Upgrade\r\n" + + "Sec-WebSocket-Accept: " + base64.StdEncoding.EncodeToString(digest[:]) + "\r\n" + + "Sec-WebSocket-Protocol: connectrpc.1+proto\r\n\r\n")) + assert.Nil(tb, err) + return conn, reader +} + +// silentServer accepts one upgrade and then never writes, so a client's +// keep-alive has nothing to hear. It returns the base URL and the reader for +// what the client sends. +func silentServer(tb testing.TB) (string, <-chan *bufio.Reader) { + tb.Helper() + listener, err := (&net.ListenConfig{}).Listen(tb.Context(), "tcp", "127.0.0.1:0") + assert.Nil(tb, err) + tb.Cleanup(func() { _ = listener.Close() }) + accepted := make(chan *bufio.Reader, 1) + go func() { + _, reader := acceptRawUpgrade(tb, listener) + accepted <- reader + }() + return "http://" + listener.Addr().String(), accepted +} + +// The client pings too, and hangs up on a silent server with 3102, the only +// error code a client has (§13), and a reason saying why. The RPC fails as Unavailable, which +// invites the retry a dead connection deserves. +func TestClientHangsUpOnSilentServer(t *testing.T) { + t.Parallel() + baseURL, accepted := silentServer(t) + transport, err := wstransport.NewTransport(baseURL, + wstransport.WithKeepAlive(keepAliveInterval), + wstransport.WithKeepAliveTimeout(keepAliveTimeout), + ) + assert.Nil(t, err) + client := pingv1connect.NewPingServiceClient(connect.NewClient(transport)) + ctx, cancel := context.WithTimeout(t.Context(), 10*time.Second) + defer cancel() + stream, err := client.CumSum(ctx) + assert.Nil(t, err) + t.Cleanup(func() { _ = stream.Close() }) + assert.Nil(t, stream.Send(&pingv1.CumSumRequest{Number: 1})) + + pings, closeCode, reason := watchFrames(<-accepted, nil) + assert.True(t, pings >= 1) + assert.Equal(t, closeCode, 3102) + assert.Equal(t, reason, "keep-alive timeout") + _, err = stream.Receive() + assert.Equal(t, connect.CodeOf(err), connect.CodeUnavailable) + assert.True(t, strings.Contains(err.Error(), "keep-alive timeout")) +} + +// Pings interleave with the stream's own messages without disturbing them, +// and a stream idle for many timeouts carries on: each side's reader answers +// Pings whether or not its caller is receiving. +func TestKeepAliveLeavesIdleStreamIntact(t *testing.T) { + t.Parallel() + spared := []wstransport.Option{ + wstransport.WithKeepAlive(sparedInterval), + wstransport.WithKeepAliveTimeout(sparedTimeout), + } + httpServer := newKeepAliveServer(t, spared[0], spared[1]) + transport, err := wstransport.NewTransport(httpServer.URL, spared[0], spared[1]) + assert.Nil(t, err) + client := pingv1connect.NewPingServiceClient(connect.NewClient(transport)) + ctx, cancel := context.WithTimeout(t.Context(), 10*time.Second) + defer cancel() + stream, err := client.CumSum(ctx) + assert.Nil(t, err) + t.Cleanup(func() { _ = stream.Close() }) + + for _, number := range []int64{1, 2, 3} { + assert.Nil(t, stream.Send(&pingv1.CumSumRequest{Number: number})) + response, err := stream.Receive() + assert.Nil(t, err) + assert.True(t, response.GetSum() > 0) + time.Sleep(3 * sparedInterval) + } + assert.Nil(t, stream.CloseSend()) + _, err = stream.Receive() + assert.True(t, errors.Is(err, io.EOF)) +} + +// A client that leaves a message untaken goes on reading the socket while its +// read-ahead has room, so it goes on answering Pings and is not hung up on. +func TestClientNotReceivingStillAnswersPings(t *testing.T) { + t.Parallel() + httpServer := newKeepAliveServer(t, + wstransport.WithKeepAlive(sparedInterval), + wstransport.WithKeepAliveTimeout(sparedTimeout), + ) + transport, err := wstransport.NewTransport(httpServer.URL, wstransport.WithKeepAlive(0)) + assert.Nil(t, err) + client := pingv1connect.NewPingServiceClient(connect.NewClient(transport)) + ctx, cancel := context.WithTimeout(t.Context(), 10*time.Second) + defer cancel() + stream, err := client.CumSum(ctx) + assert.Nil(t, err) + t.Cleanup(func() { _ = stream.Close() }) + + assert.Nil(t, stream.Send(&pingv1.CumSumRequest{Number: 1})) + time.Sleep(5 * sparedTimeout) + response, err := stream.Receive() + assert.Nil(t, err) + assert.Equal(t, response.GetSum(), int64(1)) + assert.Nil(t, stream.Send(&pingv1.CumSumRequest{Number: 2})) + response, err = stream.Receive() + assert.Nil(t, err) + assert.Equal(t, response.GetSum(), int64(3)) +} + +// The cost of keeping backpressure: once a client's read-ahead is full it +// stops reading the socket, so it stops answering Pings too, and the server +// hangs up once the timeout passes. Python's websockets makes the same call. +func TestServerHangsUpOnClientWhoseReadAheadIsFull(t *testing.T) { + t.Parallel() + server := connect.NewServer() + pingv1connect.RegisterPingServiceHandler(server, pingServer{}) + mux := http.NewServeMux() + mountBoth(mux, server, + wstransport.WithKeepAlive(keepAliveInterval), + wstransport.WithKeepAliveTimeout(keepAliveTimeout), + ) + httpServer := httptest.NewUnstartedServer(mux) + watcher := &closeFrameListener{Listener: httpServer.Listener, closed: make(chan struct{})} + httpServer.Listener = watcher + httpServer.Start() + t.Cleanup(httpServer.Close) + transport, err := wstransport.NewTransport(httpServer.URL, wstransport.WithKeepAlive(0)) + assert.Nil(t, err) + client := pingv1connect.NewPingServiceClient(connect.NewClient(transport)) + ctx, cancel := context.WithTimeout(t.Context(), 10*time.Second) + defer cancel() + stream, err := client.CumSum(ctx) + assert.Nil(t, err) + t.Cleanup(func() { _ = stream.Close() }) + + // Each response is a few bytes, so this many is well past 64 KiB of + // read-ahead once its per-message overhead is counted. + for range 3000 { + // A stall here is silence too once read-ahead is full, so the server + // may hang up before the last Send. + if err := stream.Send(&pingv1.CumSumRequest{Number: 1}); err != nil { + assert.True(t, errors.Is(err, io.EOF), assert.Sprintf("%v", err)) + break + } + } + // The server cannot judge the client silent while its own read-ahead is + // full, so reading before it hangs up would answer its Pings in time. + select { + case <-watcher.closed: + case <-ctx.Done(): + t.Fatal("server never hung up") + } + for { + if _, err = stream.Receive(); err != nil { + break + } + } + assert.Equal(t, connect.CodeOf(err), connect.CodeUnavailable) +} + +// closeFrameListener reports the server's Close frame, which starts a write +// because frames are flushed whole. The handler returns 5s later. +type closeFrameListener struct { + net.Listener + + closed chan struct{} + once sync.Once +} + +func (l *closeFrameListener) Accept() (net.Conn, error) { + conn, err := l.Listener.Accept() + if err != nil { + return nil, err + } + return &closeFrameConn{Conn: conn, listener: l}, nil +} + +type closeFrameConn struct { + net.Conn + + listener *closeFrameListener +} + +func (c *closeFrameConn) Write(p []byte) (int, error) { + if len(p) > 0 && p[0] == 0x80|opcodeClose { + c.listener.once.Do(func() { close(c.listener.closed) }) + } + return c.Conn.Write(p) +} + +// The public options reach both halves: Mount's server and NewTransport's +// client each ping at the interval named and hang up after the timeout. +func TestConnectHTTPKeepAliveReachesBothSides(t *testing.T) { + t.Parallel() + keepAlive := connecthttp.WithWebSocketKeepAlive(keepAliveInterval) + timeout := connecthttp.WithWebSocketKeepAliveTimeout(keepAliveTimeout) + + server := connect.NewServer() + pingv1connect.RegisterPingServiceHandler(server, pingServer{}) + mux := http.NewServeMux() + connecthttp.Mount(mux, server, keepAlive, timeout) + httpServer := httptest.NewServer(mux) + t.Cleanup(httpServer.Close) + conn := openRawCumSum(t, httpServer) + assert.Nil(t, conn.SetReadDeadline(time.Now().Add(10*time.Second))) + pings, closeCode, _ := watchFrames(conn, nil) + assert.True(t, pings >= 1) + assert.Equal(t, closeCode, 1011) + + baseURL, accepted := silentServer(t) + transport := connecthttp.NewTransport( + http.DefaultClient, + baseURL, + connecthttp.WithWebSocket(connecthttp.SelectStreaming), + keepAlive, + timeout, + ) + client := pingv1connect.NewPingServiceClient(connect.NewClient(transport)) + ctx, cancel := context.WithTimeout(t.Context(), 10*time.Second) + defer cancel() + stream, err := client.CumSum(ctx) + assert.Nil(t, err) + t.Cleanup(func() { _ = stream.Close() }) + assert.Nil(t, stream.Send(&pingv1.CumSumRequest{Number: 1})) + pings, closeCode, reason := watchFrames(<-accepted, nil) + assert.True(t, pings >= 1) + assert.Equal(t, closeCode, 3102) + assert.Equal(t, reason, "keep-alive timeout") +} diff --git a/internal/wstransport/keepalive_test.go b/internal/wstransport/keepalive_test.go new file mode 100644 index 00000000..a2a10385 --- /dev/null +++ b/internal/wstransport/keepalive_test.go @@ -0,0 +1,31 @@ +// Copyright 2021-2026 The Connect Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package wstransport + +import ( + "testing" + "time" + + "connectrpc.com/connect/v2/internal/assert" +) + +// Pinned because a proxy severs a quiet stream silently: nothing fails until +// a deployment runs long enough to hit its idle timeout. +func TestKeepAliveIsOnByDefault(t *testing.T) { + t.Parallel() + opts := defaultOptions() + assert.Equal(t, opts.keepAliveInterval, 30*time.Second) + assert.Equal(t, opts.keepAliveTimeout, 5*time.Minute) +} diff --git a/internal/wstransport/lifecycle_ext_test.go b/internal/wstransport/lifecycle_ext_test.go new file mode 100644 index 00000000..1de6a25c --- /dev/null +++ b/internal/wstransport/lifecycle_ext_test.go @@ -0,0 +1,324 @@ +// Copyright 2021-2026 The Connect Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package wstransport_test + +import ( + "context" + "errors" + "io" + "log/slog" + "testing" + "time" + + "connectrpc.com/connect/v2" + "connectrpc.com/connect/v2/connecthttp" + "connectrpc.com/connect/v2/internal/assert" + pingv1 "connectrpc.com/connect/v2/internal/gen/connect/ping/v1" + "connectrpc.com/connect/v2/internal/gen/connect/ping/v1/pingv1connect" + "github.com/coder/websocket" +) + +// openBlockedStream leaves a stream where the next Receive blocks: the client +// has had its reply and the server is waiting for more input that never comes. +// That is the state a mid-stream cancellation has to interrupt. +func openBlockedStream(ctx context.Context, tb testing.TB) interface { + Receive() (*pingv1.CumSumResponse, error) + Close() error +} { + tb.Helper() + client := newBidiClient(tb) + stream, err := client.CumSum(ctx) + assert.Nil(tb, err) + assert.Nil(tb, stream.Send(&pingv1.CumSumRequest{Number: 1})) + _, err = stream.Receive() + assert.Nil(tb, err) + return stream +} + +// Cancelling mid-stream must surface as Canceled, not as a transport failure a +// caller might retry. +func TestCancelDuringBlockedReceive(t *testing.T) { + t.Parallel() + ctx, cancel := context.WithCancel(t.Context()) + stream := openBlockedStream(ctx, t) + t.Cleanup(func() { _ = stream.Close() }) + + received := make(chan error, 1) + go func() { + _, err := stream.Receive() + received <- err + }() + time.Sleep(50 * time.Millisecond) // let the read block + cancel() + + select { + case err := <-received: + assert.NotNil(t, err) + assert.Equal(t, connect.CodeOf(err), connect.CodeCanceled) + case <-time.After(10 * time.Second): + t.Fatal("Receive did not unblock when the context was canceled") + } +} + +// The same for a deadline, which must not be reported as cancellation. +func TestDeadlineDuringBlockedReceive(t *testing.T) { + t.Parallel() + ctx, cancel := context.WithTimeout(t.Context(), 300*time.Millisecond) + defer cancel() + stream := openBlockedStream(ctx, t) + t.Cleanup(func() { _ = stream.Close() }) + + received := make(chan error, 1) + go func() { + _, err := stream.Receive() + received <- err + }() + + select { + case err := <-received: + assert.NotNil(t, err) + assert.Equal(t, connect.CodeOf(err), connect.CodeDeadlineExceeded) + case <-time.After(10 * time.Second): + t.Fatal("Receive did not unblock when the deadline passed") + } +} + +// panicServer models the handler nobody means to write. +type panicServer struct { + pingv1connect.UnimplementedPingServiceHandler +} + +func (panicServer) CumSum(_ context.Context, stream pingv1connect.PingServiceCumSumServerStream) error { + if _, err := stream.Receive(); err != nil { + return err + } + panic("handler exploded") +} + +// A panicking handler must not strand the caller. net/http recovers the panic +// but deliberately leaves a hijacked connection open — "if !c.hijacked()" — so +// unlike an HTTP handler, nothing closes the socket on the way out. +func TestHandlerPanicDoesNotStrandTheClient(t *testing.T) { + t.Parallel() + httpServer := newHybridServer2(t, panicServer{}) + // The panic trace net/http prints is expected here, so discard it. + httpServer.Config.ErrorLog = slog.NewLogLogger(slog.DiscardHandler, slog.LevelError) + transport := connecthttp.NewTransport( + httpServer.Client(), + httpServer.URL, + connecthttp.WithWebSocket(connecthttp.SelectStreaming), + ) + client := pingv1connect.NewPingServiceClient(connect.NewClient(transport)) + + stream, err := client.CumSum(t.Context()) + assert.Nil(t, err) + t.Cleanup(func() { _ = stream.Close() }) + assert.Nil(t, stream.Send(&pingv1.CumSumRequest{Number: 1})) + + received := make(chan error, 1) + go func() { + _, err = stream.Receive() + received <- err + }() + select { + case err := <-received: + t.Logf("client saw: %v", err) + assert.NotNil(t, err) + case <-time.After(10 * time.Second): + t.Fatal("client hung: the panicking handler left the connection open") + } +} + +// Once the client has said it is done sending, a further Send has nowhere to +// go: the peer has stopped reading body messages. Reporting it keeps the +// caller from believing the message was delivered, and matches connecthttp. +func TestSendAfterCloseSendFails(t *testing.T) { + t.Parallel() + httpServer := newHybridServer(t, pingServer{}) + transport := connecthttp.NewTransport( + httpServer.Client(), + httpServer.URL, + connecthttp.WithWebSocket(connecthttp.SelectStreaming), + ) + client := pingv1connect.NewPingServiceClient(connect.NewClient(transport)) + + stream, err := client.CumSum(t.Context()) + assert.Nil(t, err) + t.Cleanup(func() { _ = stream.Close() }) + assert.Nil(t, stream.Send(&pingv1.CumSumRequest{Number: 1})) + _, err = stream.Receive() + assert.Nil(t, err) + assert.Nil(t, stream.CloseSend()) + + assert.NotNil(t, stream.Send(&pingv1.CumSumRequest{Number: 2})) + // CloseSend stays idempotent: only Send is affected. + assert.Nil(t, stream.CloseSend()) +} + +// endOfStreamReporter reports how its Receive loop ended: the code, and +// whether the error reads as a clean end of stream. +type endOfStreamReporter struct { + pingv1connect.UnimplementedPingServiceHandler + + outcome chan endOfStreamOutcome +} + +type endOfStreamOutcome struct { + code connect.Code + sawEOF bool + message string +} + +func (s endOfStreamReporter) CumSum( + _ context.Context, + stream pingv1connect.PingServiceCumSumServerStream, +) error { + for { + _, err := stream.Receive() + if err == nil { + continue + } + s.outcome <- endOfStreamOutcome{ + code: connect.CodeOf(err), + sawEOF: errors.Is(err, io.EOF), + message: err.Error(), + } + return nil + } +} + +// A client that finished and a client that died are different outcomes, and a +// handler has to be able to tell them apart. Both stop the read at the same +// call site, so only the record of a C message separates them. +// +// The io.EOF assertion is the load-bearing one: `errors.Is(err, io.EOF)` is +// how every handler in this repo — and in connecthttp — learns that a stream +// ended cleanly. A cancellation that wrapped the transport's own error would +// satisfy it too, since a read on a closed connection reports io.EOF at the +// bottom of its chain, and a truncated stream would look finished. +// watchingServer reads to EOF, then waits on the call's own context and +// reports what ended it. +type watchingServer struct { + pingv1connect.UnimplementedPingServiceHandler + + ended chan error +} + +func (s watchingServer) CumSum( + ctx context.Context, + stream pingv1connect.PingServiceCumSumServerStream, +) error { + for { + request, err := stream.Receive() + if err != nil { + break // io.EOF once C has arrived + } + // Answered, so the test can tell that the handler is past its reads and + // into the wait below. + if sendErr := stream.Send(&pingv1.CumSumResponse{Sum: request.Number}); sendErr != nil { + s.ended <- sendErr + return sendErr + } + } + select { + case <-ctx.Done(): + s.ended <- ctx.Err() + case <-time.After(20 * time.Second): + s.ended <- nil + } + return ctx.Err() +} + +// §8: the RPC is canceled once the connection ends before S, whether or not C +// arrived. A handler that has had its io.EOF is no longer reading, so without +// the drain reporting the connection's end it would compute a whole response +// for a peer that left — and the server would then try to send it, which §8 +// forbids. +func TestConnectionEndingAfterEndOfClientStreamCancelsTheCall(t *testing.T) { + t.Parallel() + ended := make(chan error, 1) + httpServer := newHybridServer2(t, watchingServer{ended: ended}) + conn := dialCumSum(t, httpServer, "") + sendProtoBody(t, conn, &pingv1.CumSumRequest{Number: 1}) + sendJSONMessage(t, conn, wireClientEndStream, nil) + + // Read the reply, so the handler is past its Receive loop and waiting. + reply := readServerOpening(t, conn) + assert.Equal(t, reply[0], wireBody) + + // Now vanish, without a closing handshake. + assert.Nil(t, conn.CloseNow()) + + select { + case err := <-ended: + assert.NotNil(t, err) + assert.True(t, errors.Is(err, context.Canceled)) + case <-time.After(20 * time.Second): + t.Fatal("the handler never learned the connection had ended") + } +} + +func TestEndOfClientStreamIsDistinguishableFromADeadClient(t *testing.T) { + t.Parallel() + for _, test := range []struct { + name string + finish func(testing.TB, *websocket.Conn) + wantCode connect.Code + wantEOF bool + }{ + { + name: "client sends C", + finish: func(tb testing.TB, conn *websocket.Conn) { + tb.Helper() + sendJSONMessage(tb, conn, wireClientEndStream, nil) + }, + wantCode: connect.CodeUnknown, + wantEOF: true, + }, + { + name: "client closes cleanly without C", + finish: func(_ testing.TB, conn *websocket.Conn) { + _ = conn.Close(websocket.StatusNormalClosure, "") + }, + wantCode: connect.CodeCanceled, + wantEOF: false, + }, + { + name: "client vanishes without C", + finish: func(_ testing.TB, conn *websocket.Conn) { + _ = conn.CloseNow() + }, + wantCode: connect.CodeCanceled, + wantEOF: false, + }, + } { + t.Run(test.name, func(t *testing.T) { + t.Parallel() + outcome := make(chan endOfStreamOutcome, 1) + httpServer := newHybridServer2(t, endOfStreamReporter{outcome: outcome}) + conn := dialCumSum(t, httpServer, "") + sendProtoBody(t, conn, &pingv1.CumSumRequest{Number: 1}) + test.finish(t, conn) + + select { + case got := <-outcome: + assert.Equal(t, got.code, test.wantCode) + assert.Equal(t, got.sawEOF, test.wantEOF) + case <-time.After(5 * time.Second): + t.Fatal("the handler never finished its receive loop") + } + }) + } +} diff --git a/internal/wstransport/limits_ext_test.go b/internal/wstransport/limits_ext_test.go new file mode 100644 index 00000000..75c4ce68 --- /dev/null +++ b/internal/wstransport/limits_ext_test.go @@ -0,0 +1,193 @@ +// Copyright 2021-2026 The Connect Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package wstransport_test + +import ( + "context" + "errors" + "net" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "connectrpc.com/connect/v2" + "connectrpc.com/connect/v2/connecthttp" + "connectrpc.com/connect/v2/internal/assert" + pingv1 "connectrpc.com/connect/v2/internal/gen/connect/ping/v1" + "connectrpc.com/connect/v2/internal/gen/connect/ping/v1/pingv1connect" + "connectrpc.com/connect/v2/internal/wstransport" + "google.golang.org/protobuf/proto" +) + +// echoSizeServer answers with a response of a fixed size, so a test can put +// the limit on the client's receiving side. +type echoSizeServer struct { + pingv1connect.UnimplementedPingServiceHandler + + responseBytes int +} + +func (s echoSizeServer) Ping(_ context.Context, req *pingv1.PingRequest) (*pingv1.PingResponse, error) { + return &pingv1.PingResponse{ + Number: req.Number, + Text: strings.Repeat("x", s.responseBytes), + }, nil +} + +// A server that rejects an oversized request explains itself in an S message +// rather than hanging up with a bare 1009. Asserted through IsRemote: a close +// status the client mapped locally would carry the same code, and only the +// origin tells the two apart. +func TestOversizeRequestIsExplainedInBand(t *testing.T) { + t.Parallel() + server := connect.NewServer() + pingv1connect.RegisterPingServiceHandler(server, echoSizeServer{}) + mux := http.NewServeMux() + connecthttp.Mount(mux, server, connecthttp.WithReadMaxBytes(1024)) + httpServer := httptest.NewServer(mux) + t.Cleanup(httpServer.Close) + + transport := connecthttp.NewTransport( + httpServer.Client(), + httpServer.URL, + connecthttp.WithWebSocket(connecthttp.SelectAll), + ) + client := pingv1connect.NewPingServiceClient(connect.NewClient(transport)) + + _, err := client.Ping(t.Context(), &pingv1.PingRequest{Text: strings.Repeat("x", 8192)}) + assert.NotNil(t, err) + assert.Equal(t, connect.CodeOf(err), connect.CodeResourceExhausted) + + var connectErr *connect.Error + assert.True(t, errors.As(err, &connectErr)) + assert.True(t, connectErr.IsRemote()) + // The configured limit, not the wire limit that carries the marker margin. + assert.True(t, strings.Contains(err.Error(), "configured max of 1024 bytes")) +} + +// The read limit bounds a whole WebSocket message, not a frame. A sender that +// fragments past the limit must still be refused, or the limit is decorative. +func TestReadLimitSpansFragments(t *testing.T) { + t.Parallel() + server := connect.NewServer() + pingv1connect.RegisterPingServiceHandler(server, pingServer{}) + mux := http.NewServeMux() + connecthttp.Mount(mux, server, connecthttp.WithReadMaxBytes(1024)) + httpServer := httptest.NewServer(mux) + t.Cleanup(httpServer.Close) + + addr := httpServer.Listener.Addr().String() + conn, err := (&net.Dialer{}).DialContext(t.Context(), "tcp", addr) + assert.Nil(t, err) + t.Cleanup(func() { _ = conn.Close() }) + _ = rawHandshake(t, conn, addr, pingv1connect.PingServiceCumSumProcedure) + assert.Nil(t, conn.SetDeadline(time.Now().Add(20*time.Second))) + assert.Nil(t, writeClientFragment(conn, []byte("M[]"), true, opcodeText)) + + // 4 KiB in 64-byte pieces: every frame is far under the limit, and the + // message they reassemble into is four times over it. + const fragmentBytes = 64 + chunk := make([]byte, fragmentBytes) + assert.Nil(t, writeClientFragment(conn, append([]byte("B"), chunk...), false, opcodeBinary)) + for range 64 { + if err := writeClientFragment(conn, chunk, false, opcodeContinuation); err != nil { + break // the server stopped reading, which is the point + } + } + + _, opening := readServerFrame(t, conn) + assert.Equal(t, opening[0], wireMetadata) + _, payload := readServerFrame(t, conn) + assert.Equal(t, payload[0], wireServerEndStream) + assert.True(t, strings.Contains(string(payload), "resource_exhausted")) + assert.True(t, strings.Contains(string(payload), "configured max of 1024 bytes")) +} + +// A client enforces its limit per reassembled message too, and classifies the +// overrun the same way a server does so one monitor sees both directions. +// A response the client never asked to be this large is refused, not buffered. +func TestClientReportsSizeLimitFaults(t *testing.T) { + t.Parallel() + httpServer := newServerFor(t, echoSizeServer{responseBytes: 64 * 1024}) + recorder := &clientFaultRecorder{} + transport := connecthttp.NewTransport( + httpServer.Client(), + httpServer.URL, + connecthttp.WithWebSocket(connecthttp.SelectAll), + connecthttp.WithReadMaxBytes(1024), + connecthttp.WithWebSocketClientProtocolErrorHandler(recorder.handle), + ) + client := pingv1connect.NewPingServiceClient(connect.NewClient(transport)) + + _, err := client.Ping(t.Context(), &pingv1.PingRequest{Number: 1}) + assert.NotNil(t, err) + assert.Equal(t, connect.CodeOf(err), connect.CodeResourceExhausted) + // The number a caller configured, not the WebSocket library's wire limit, + // which is four bytes larger to leave room for the marker. + assert.True(t, strings.Contains(err.Error(), "configured max of 1024 bytes")) + + faults, _ := recorder.seen() + assert.Equal(t, faults, []wstransport.ProtocolFault{wstransport.FaultSizeLimit}) +} + +// §12: the limit covers the payload, not the marker, as Connect over HTTP +// leaves out its envelope. A message exactly at the limit fits on both the +// sending and the receiving side; one byte more does not. +func TestSizeLimitsExcludeTheMarker(t *testing.T) { + t.Parallel() + const limit = 100 + // A Text of n bytes encodes to n+2: its tag, its length, then the bytes. + atLimit := &pingv1.PingRequest{Text: strings.Repeat("x", limit-2)} + overLimit := &pingv1.PingRequest{Text: strings.Repeat("x", limit-1)} + assert.Equal(t, proto.Size(atLimit), limit) + + for _, test := range []struct { + name string + serverOptions []wstransport.ServerOption + clientOptions []connecthttp.Option + want string + }{ + { + name: "read limit", + serverOptions: []wstransport.ServerOption{wstransport.WithReadMaxBytes(limit)}, + want: "configured max of 100 bytes", + }, + { + // Refused before the message reaches the socket. + name: "send limit", + clientOptions: []connecthttp.Option{connecthttp.WithSendMaxBytes(limit)}, + want: "sendMaxBytes", + }, + } { + t.Run(test.name, func(t *testing.T) { + t.Parallel() + httpServer := newServerFor(t, echoSizeServer{}, test.serverOptions...) + transport := connecthttp.NewTransport( + httpServer.Client(), + httpServer.URL, + append([]connecthttp.Option{connecthttp.WithWebSocket(connecthttp.SelectAll)}, test.clientOptions...)..., + ) + client := pingv1connect.NewPingServiceClient(connect.NewClient(transport)) + + _, err := client.Ping(t.Context(), atLimit) + assert.Nil(t, err) + _, err = client.Ping(t.Context(), overLimit) + assert.Equal(t, connect.CodeOf(err), connect.CodeResourceExhausted) + assert.True(t, strings.Contains(err.Error(), test.want), assert.Sprintf("error %v", err)) + }) + } +} diff --git a/internal/wstransport/message.go b/internal/wstransport/message.go new file mode 100644 index 00000000..18b7c010 --- /dev/null +++ b/internal/wstransport/message.go @@ -0,0 +1,438 @@ +// Copyright 2021-2026 The Connect Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// This transport's framing: one marker and one payload per WebSocket message, +// with no length field. The frame already delimits the message, so a length +// could only restate it — or disagree with it, which is a class of protocol +// error that cannot exist once the field is gone. +// +// The frame type carries the payload encoding: text is JSON, binary is +// Protobuf. A receiver therefore knows how to parse a payload before it has +// looked at anything but the frame. + +package wstransport + +import ( + "bytes" + "context" + "encoding/base64" + "encoding/json" + "maps" + "net/http" + "slices" + "strconv" + "strings" + "unicode/utf8" + + "connectrpc.com/connect/v2" + "connectrpc.com/connect/v2/internal/bufferpool" + "connectrpc.com/connect/v2/internal/connecterr" + "connectrpc.com/connect/v2/internal/connectwire" +) + +// Message markers: one byte each, printable on purpose. A text frame then +// reads as its marker followed by its JSON in a browser's network panel, which +// is where a JS client gets debugged. +const ( + markerBody byte = 'B' // an RPC message, either direction + markerMetadata byte = 'M' // JSON metadata entries, either direction + markerServerEndStream byte = 'S' // EndStreamMessage JSON, server -> client + markerClientEndStream byte = 'C' // end of the request stream, client -> server +) + +// markerName renders a marker for a diagnostic, printably where it can. +func markerName(marker byte) string { + if marker >= 0x20 && marker < 0x7F { + return string(rune(marker)) + } + return "0x" + strconv.FormatUint(uint64(marker), 16) +} + +// encodeMessage writes marker and payload into dst as one message. +// +// Both go into a single buffer rather than two writes, because the WebSocket +// library decides whether to compress from the size of the first write it +// sees. Writing the marker alone would offer one byte, fall under any sane +// threshold, and silently disable compression for every message. +func encodeMessage(dst *bytes.Buffer, marker byte, payload []byte) { + dst.Grow(1 + len(payload)) + dst.WriteByte(marker) + dst.Write(payload) +} + +// wireMessage is one message as it arrived: the marker that names its kind, +// the payload behind it, and the frame type that says how that payload is +// encoded. +// +// The three travel together from the read all the way to the codec, because +// none of them means anything without the others: a payload without its frame +// type has no encoding, and a marker without its payload has no content. +type wireMessage struct { + marker byte + payload []byte + // text reports a text frame, whose payload is JSON. + text bool +} + +// decodeMessage splits a frame into the message it carries. text is the frame +// type it arrived in, which the caller reads from the transport. An unknown +// marker is the dispatcher's to report; §5.1 reserves nothing else. +func decodeMessage(frame []byte, text bool) (wireMessage, *connect.Error) { + if len(frame) == 0 { + return wireMessage{}, errorf(connect.CodeInternal, "protocol error: empty message carries no marker") + } + return wireMessage{marker: frame[0], payload: frame[1:], text: text}, nil +} + +// textEncodingError reports a text message that is not valid UTF-8, which +// RFC 6455 §8.1 forbids. §6.1 has the receiver check it before reading the +// marker and fail the connection with 1007, without an S message. +// +// Neither this package's WebSocket library nor the layers under it check this, +// so a peer that emits invalid UTF-8 would otherwise have its bytes handed to +// a codec here while a browser on the same wire severs the connection — the +// encoding bug reproducing everywhere except in these tests. +func textEncodingError(frame []byte, text bool) *connect.Error { + if !text || utf8.Valid(frame) { + return nil + } + return errorf( + connect.CodeInternal, + "protocol error: text message is not valid UTF-8", + ) +} + +// frameName names a frame type for a diagnostic, which §6.1 requires a +// frame-type error to state. +func frameName(text bool) string { + if text { + return "text" + } + return "binary" +} + +// messageSender writes one encoded message as one WebSocket frame. text says +// which frame type to use. +type messageSender interface { + send(ctx context.Context, text bool, data []byte) (int64, error) +} + +// messageWriter encodes messages and hands them to a sender. +type messageWriter struct { + sender messageSender + sendMaxBytes int + stats *connect.MessageStats +} + +// writeBody encodes message with the negotiated codec and sends it as a body. +func (w *messageWriter) writeBody(ctx context.Context, codec connect.Codec, message any) *connect.Error { + buffer := bufferpool.Get() + defer bufferpool.Put(buffer) + if err := codec.MarshalWrite(ctx, buffer, message); err != nil { + return errorf(connect.CodeInternal, "marshal message: %w", err) + } + // JSON is UTF-8 by construction; a custom text codec is checked, since + // the peer would otherwise fail the whole connection with 1007 (§6.1). + bodyIsText := codecIsText(codec) + if bodyIsText && codec.Name() != connect.CodecNameJSON && !utf8.Valid(buffer.Bytes()) { + return errorf( + connect.CodeInternal, + "marshal message: codec %q produced invalid UTF-8 for a text frame", codec.Name(), + ) + } + if err := w.send(ctx, markerBody, bodyIsText, buffer.Bytes()); err != nil { + return err + } + if w.stats != nil { + *w.stats = connect.MessageStats{Size: buffer.Len()} + } + return nil +} + +// writeJSON sends a control message, whose payload is always JSON and whose +// frame is therefore always text. +func (w *messageWriter) writeJSON(ctx context.Context, marker byte, value any) *connect.Error { + data, err := json.Marshal(value) + if err != nil { + return errorf(connect.CodeInternal, "marshal %s message: %w", markerName(marker), err) + } + return w.send(ctx, marker, true, data) +} + +// writeEndStream sends the terminal message. Its EndStreamMessage schema is +// shared with Connect over HTTP; only the framing around it differs. +func (w *messageWriter) writeEndStream(ctx context.Context, err error, trailer http.Header) *connect.Error { + encoded, trailerErr := encodeTrailer(trailer) + if trailerErr != nil { + // As with an unsendable header: the trailers are dropped, and the + // unsendable one is the outcome unless the handler reported its own. + encoded = nil + if err == nil { + err = trailerErr + } + } + end := &connectwire.EndStreamMessage{Trailer: encoded} + if err != nil { + end.Error = connectwire.NewWireError(err) + } + return w.writeJSON(ctx, markerServerEndStream, end) +} + +// send encodes one message and hands it to the sender. +func (w *messageWriter) send(ctx context.Context, marker byte, text bool, payload []byte) *connect.Error { + // §12 leaves the marker out of the limit, as Connect over HTTP leaves out + // its envelope, so one configured size means the same on both transports. + // Only an RPC message is limited: an M or S over it would leave the stream + // without its opening or its verdict, which §9 requires. + if marker == markerBody && w.sendMaxBytes > 0 && len(payload) > w.sendMaxBytes { + return errorf( + connect.CodeResourceExhausted, + "message size %d exceeds sendMaxBytes %d", len(payload), w.sendMaxBytes, + ) + } + buffer := bufferpool.Get() + defer bufferpool.Put(buffer) + encodeMessage(buffer, marker, payload) + if _, sendErr := w.sender.send(ctx, text, buffer.Bytes()); sendErr != nil { + wrapped := connecterr.WrapIfContextDone(ctx, sendErr) + if connectErr, ok := connecterr.AsError(wrapped); ok { + return connectErr + } + return errorf(connect.CodeUnknown, "write message: %w", wrapped) + } + return nil +} + +// An M message's metadata is a JSON array of entries, each a key followed by +// all of that key's values: [["acme-tenant","42"],["accept","a","b"]]. An +// array is used instead of an object because some JSON parsers automatically +// swallow duplicate keys and won't report if a key repeats. A repeated key is +// a protocol error. +// +// Keys are lower-case on the wire, matching HTTP/2 and HTTP/3. A key ending in +// -bin carries base64, because JSON strings are Unicode and arbitrary bytes +// are not. As over HTTP, the application holds that base64 form: +// connect.EncodeBinaryHeader and connect.DecodeBinaryHeader convert it, and +// this package passes it through. + +// metadataBinarySuffix marks a key whose values are base64-encoded bytes. +const metadataBinarySuffix = "-bin" + +// encodeMetadata renders headers as M message entries, in key order so the +// wire form is deterministic. Keys must be canonical, so no two collide. A key +// with no values is left out: §7.3.1 gives every entry at least one value. +// +// §7.3.1 binds the sender too, so a header that breaks its rules is refused +// rather than sent for the peer to reject. Values are trimmed of surrounding +// space and tab, which a sender should not send, and -bin values are sent +// unpadded. +func encodeMetadata(header http.Header) ([][]string, *connect.Error) { + entries := make([][]string, 0, len(header)) + for _, key := range slices.Sorted(maps.Keys(header)) { + if len(header[key]) == 0 { + continue + } + lower := strings.ToLower(key) + if !validHeaderFieldName(lower) { + return nil, errorf(connect.CodeInternal, "metadata key %q is not a valid HTTP field name", key) + } + binary := strings.HasSuffix(lower, metadataBinarySuffix) + entry := make([]string, 0, 1+len(header[key])) + entry = append(entry, lower) + for _, value := range header[key] { + value = strings.Trim(value, " \t") + if binary { + value = strings.TrimRight(value, "=") + if _, err := base64.RawStdEncoding.DecodeString(value); err != nil { + return nil, errorf( + connect.CodeInternal, "metadata %q has a value that is not base64: %w", key, err, + ) + } + } else if !validHeaderFieldValue(value) { + return nil, errorf( + connect.CodeInternal, + "metadata %q has a value that is not a valid HTTP field value; values are visible "+ + "ASCII, space, and tab, and anything else goes base64-encoded under a -bin key", key, + ) + } + entry = append(entry, value) + } + entries = append(entries, entry) + } + return entries, nil +} + +// checkRequestMetadata refuses a header a client may not send in its M +// message (§7.3.2). The server's deny list is its own, so only the default +// one is known here. +func checkRequestMetadata(header http.Header) *connect.Error { + for _, key := range slices.Sorted(maps.Keys(header)) { + if reason, reserved := reservedHeaderReason(key, defaultInfrastructureHeaders()); reserved { + return errorf( + connect.CodeInternal, + "request header %q cannot be sent over WebSocket: %s", key, reason, + ) + } + } + return nil +} + +// encodeTrailer renders trailers for an S message, whose EndStreamMessage +// schema is shared with Connect over HTTP and so remains a JSON object. Only a +// server sends one, and §9 keeps connect- keys out of it. Names and values are +// held to the rules an M message's are, so a receiver never sees a trailer it +// would have to reject. +func encodeTrailer(trailer http.Header) (http.Header, *connect.Error) { + sendable := make(http.Header, len(trailer)) + for key, values := range trailer { + if !isConnectReserved(strings.ToLower(key)) { + sendable[key] = values + } + } + entries, err := encodeMetadata(sendable) + if err != nil { + return nil, err + } + encoded := make(http.Header, len(entries)) + for _, entry := range entries { + encoded[entry[0]] = entry[1:] + } + return encoded, nil +} + +// decodeTrailer reads an S message's trailers. They keep Connect-over-HTTP's +// object form and its rules (§9), so they are held to the shared rules for +// names and values but not to the M message's lower-case and non-empty ones. +func decodeTrailer(trailer http.Header) (http.Header, *connect.Error) { + entries := make([][]string, 0, len(trailer)) + for key, values := range trailer { + entries = append(entries, append([]string{key}, values...)) + } + return decodeEntries(entries, false) +} + +// decodeMetadata reads an M message's entries into an http.Header, enforcing +// §7.3.1: every key is lower-case and has at least one value, and no key +// appears twice. Keys are canonical MIME form in memory so that Go's own +// accessors work. +func decodeMetadata(entries [][]string) (http.Header, *connect.Error) { + return decodeEntries(entries, true) +} + +// decodeEntries holds entries to the rules every metadata key and value +// shares; strict adds the M message's own. A -bin value is passed through as +// base64 without being decoded: as over HTTP, a bad value surfaces when the +// application decodes it (§7.3.1). +func decodeEntries(entries [][]string, strict bool) (http.Header, *connect.Error) { + header := make(http.Header, len(entries)) + spelling := make(map[string]string, len(entries)) + for _, entry := range entries { + if len(entry) == 0 { + return nil, errorf( + connect.CodeInternal, + "metadata entry is empty; an entry is a key followed by its values", + ) + } + key, values := entry[0], entry[1:] + if strict && len(values) == 0 { + return nil, errorf( + connect.CodeInternal, + "metadata %q has no values; every key carries at least one, which may be empty", key, + ) + } + canonical := http.CanonicalHeaderKey(key) + if first, duplicate := spelling[canonical]; duplicate { + return nil, duplicateMetadataKeyError(first, key) + } + spelling[canonical] = key + if !validHeaderFieldName(key) { + return nil, errorf( + connect.CodeInternal, + "metadata key %q is not a valid HTTP field name", key, + ) + } + if strict && key != strings.ToLower(key) { + return nil, errorf( + connect.CodeInternal, + "metadata key %q is not lower-case; keys are lower-case on the wire", key, + ) + } + // §7.3.1: every value is trimmed before delivery, -bin ones included; + // only the character rules are for text values alone. + binary := strings.HasSuffix(strings.ToLower(key), metadataBinarySuffix) + trimmed := make([]string, len(values)) + for index, value := range values { + if !binary && !validHeaderFieldValue(value) { + return nil, errorf( + connect.CodeInternal, + "metadata %q has a value that is not a valid HTTP field value; "+ + "values are visible ASCII, space, and tab", key, + ) + } + trimmed[index] = strings.Trim(value, " \t") + } + header[canonical] = trimmed + } + return header, nil +} + +// validHeaderFieldName reports whether key is an RFC 9110 token. Metadata +// stands in for HTTP headers and may be forwarded as one, so a key that is not +// a field name has no way to survive the journey. +func validHeaderFieldName(key string) bool { + if key == "" { + return false + } + for index := range len(key) { + if !isTokenByte(key[index]) { + return false + } + } + return true +} + +func isTokenByte(char byte) bool { + switch { + case char >= 'a' && char <= 'z', char >= 'A' && char <= 'Z', char >= '0' && char <= '9': + return true + } + return strings.IndexByte("!#$%&'*+-.^_`|~", char) >= 0 +} + +// validHeaderFieldValue reports whether value holds only visible ASCII, space, +// and tab (§7.3.1). RFC 9110's obs-text is excluded because a JSON string has +// no byte form for it, and control bytes would end or split a forwarded header. +func validHeaderFieldValue(value string) bool { + for index := range len(value) { + char := value[index] + if char != '\t' && (char < ' ' || char > '~') { + return false + } + } + return true +} + +// duplicateMetadataKeyError names both spellings in a stable order, so the +// message does not depend on which one was reached first. Trailers arrive as +// a map, so for them that order is random. +func duplicateMetadataKeyError(one, other string) *connect.Error { + if one > other { + one, other = other, one + } + return errorf( + connect.CodeInternal, + "metadata keys %q and %q are the same key; a key carries all its values in one entry", + one, other, + ) +} diff --git a/internal/wstransport/metadata_ext_test.go b/internal/wstransport/metadata_ext_test.go new file mode 100644 index 00000000..b12a4db6 --- /dev/null +++ b/internal/wstransport/metadata_ext_test.go @@ -0,0 +1,272 @@ +// Copyright 2021-2026 The Connect Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package wstransport_test + +import ( + "context" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "connectrpc.com/connect/v2" + "connectrpc.com/connect/v2/connecthttp" + "connectrpc.com/connect/v2/internal/assert" + pingv1 "connectrpc.com/connect/v2/internal/gen/connect/ping/v1" + "connectrpc.com/connect/v2/internal/gen/connect/ping/v1/pingv1connect" + "connectrpc.com/connect/v2/internal/wstransport" + "github.com/coder/websocket" +) + +// newServerFor mounts an arbitrary handler on both transports, which +// newHybridServer cannot do because it takes the concrete pingServer. +func newServerFor( + tb testing.TB, + handler pingv1connect.PingServiceHandler, + options ...wstransport.ServerOption, +) *httptest.Server { + tb.Helper() + server := connect.NewServer() + pingv1connect.RegisterPingServiceHandler(server, handler) + mux := http.NewServeMux() + mountBoth(mux, server, options...) + httpServer := httptest.NewServer(mux) + tb.Cleanup(httpServer.Close) + return httpServer +} + +// trailerShapeServer sets leading and trailing metadata of every shape a caller +// can produce: repeated values, and a header alongside a trailer. +type trailerShapeServer struct { + pingv1connect.UnimplementedPingServiceHandler +} + +func (trailerShapeServer) CountUp( + ctx context.Context, + _ *pingv1.CountUpRequest, + stream pingv1connect.PingServiceCountUpServerStream, +) error { + if info, ok := connect.CallInfoForServerContext(ctx); ok { + info.ResponseHeader().Set("Lead", "header-value") + info.ResponseTrailer().Add("Multi", "one") + info.ResponseTrailer().Add("Multi", "two") + } + return stream.Send(&pingv1.CountUpResponse{Number: 1}) +} + +// drainCountUp runs the RPC to completion, which is what makes metadata +// available. +func drainCountUp(ctx context.Context, tb testing.TB, client pingv1connect.PingServiceClient) { + tb.Helper() + stream, err := client.CountUp(ctx, &pingv1.CountUpRequest{Number: 1}) + assert.Nil(tb, err) + for { + if _, err := stream.Receive(); err != nil { + break + } + } + assert.Nil(tb, stream.Close()) +} + +// A trailer set twice must arrive twice, in order. The end-stream metadata is +// JSON, where a repeated key is an array rather than a second entry. +func TestRepeatedTrailerValuesSurvive(t *testing.T) { + t.Parallel() + httpServer := newServerFor(t, trailerShapeServer{}) + transport := connecthttp.NewTransport( + httpServer.Client(), + httpServer.URL, + connecthttp.WithWebSocket(connecthttp.SelectStreaming), + ) + client := pingv1connect.NewPingServiceClient(connect.NewClient(transport)) + ctx, info := connect.NewClientContext(t.Context()) + drainCountUp(ctx, t, client) + assert.Equal(t, info.ResponseTrailer().Values("Multi"), []string{"one", "two"}) +} + +// Leading metadata a handler sets must reach the caller as a *header*, the +// same as it does over HTTP. The 101 is written before the handler runs, so +// there is no response header block to carry it; it travels in a +// Leading-Metadata message instead. Asserted against connecthttp rather than +// against a constant, so the two transports cannot drift apart. +func TestResponseHeadersArriveAsHeaders(t *testing.T) { + t.Parallel() + httpServer := newServerFor(t, trailerShapeServer{}) + + wsTransport := connecthttp.NewTransport( + httpServer.Client(), + httpServer.URL, + connecthttp.WithWebSocket(connecthttp.SelectStreaming), + ) + wsCtx, wsInfo := connect.NewClientContext(t.Context()) + drainCountUp(wsCtx, t, pingv1connect.NewPingServiceClient(connect.NewClient(wsTransport))) + + httpCtx, httpInfo := connect.NewClientContext(t.Context()) + drainCountUp(httpCtx, t, pingv1connect.NewPingServiceClient(connect.NewClient( + connecthttp.NewTransport(httpServer.Client(), httpServer.URL), + ))) + + assert.Equal(t, wsInfo.ResponseHeader().Values("Lead"), []string{"header-value"}) + assert.Equal(t, wsInfo.ResponseHeader().Values("Lead"), httpInfo.ResponseHeader().Values("Lead")) + // And it is not also delivered as a trailer: one bag on the wire, but the + // two halves stay distinct at the API. + assert.Equal(t, len(wsInfo.ResponseTrailer().Values("Lead")), 0) + assert.Equal(t, len(httpInfo.ResponseTrailer().Values("Lead")), 0) +} + +// Headers must be readable at the same point in the stream as they are over +// HTTP: not before the first Receive, and yes after it. +func TestLeadingMetadataIsReadableAfterFirstReceive(t *testing.T) { + t.Parallel() + httpServer := newServerFor(t, trailerShapeServer{}) + + readAfterFirstReceive := func(transport connect.Transport) (before, after []string) { + ctx, info := connect.NewClientContext(t.Context()) + client := pingv1connect.NewPingServiceClient(connect.NewClient(transport)) + stream, err := client.CountUp(ctx, &pingv1.CountUpRequest{Number: 1}) + assert.Nil(t, err) + t.Cleanup(func() { _ = stream.Close() }) + before = info.ResponseHeader().Values("Lead") + _, err = stream.Receive() + assert.Nil(t, err) + return before, info.ResponseHeader().Values("Lead") + } + + wsTransport := connecthttp.NewTransport( + httpServer.Client(), + httpServer.URL, + connecthttp.WithWebSocket(connecthttp.SelectStreaming), + ) + wsBefore, wsAfter := readAfterFirstReceive(wsTransport) + httpBefore, httpAfter := readAfterFirstReceive( + connecthttp.NewTransport(httpServer.Client(), httpServer.URL)) + + assert.Equal(t, len(wsBefore), len(httpBefore)) + assert.Equal(t, wsAfter, httpAfter) + assert.Equal(t, wsAfter, []string{"header-value"}) +} + +// failingMetadataServer sets leading metadata and then fails without sending a +// message: the case where the metadata has nothing to ride ahead of, and would +// be lost if the metadata only flushed on the first Send. +type failingMetadataServer struct { + pingv1connect.UnimplementedPingServiceHandler +} + +func (failingMetadataServer) CountUp( + ctx context.Context, + _ *pingv1.CountUpRequest, + _ pingv1connect.PingServiceCountUpServerStream, +) error { + if info, ok := connect.CallInfoForServerContext(ctx); ok { + info.ResponseHeader().Set("Lead", "header-value") + info.ResponseTrailer().Set("Trail", "trailer-value") + } + return connect.NewError(connect.CodeUnavailable, "no messages for you") +} + +// The flush point is "before the first body, or before the end-of-stream +// message if there is no body" — this is the second clause. +func TestLeadingMetadataSurvivesAStreamWithNoMessages(t *testing.T) { + t.Parallel() + httpServer := newServerFor(t, failingMetadataServer{}) + transport := connecthttp.NewTransport( + httpServer.Client(), + httpServer.URL, + connecthttp.WithWebSocket(connecthttp.SelectStreaming), + ) + client := pingv1connect.NewPingServiceClient(connect.NewClient(transport)) + + ctx, info := connect.NewClientContext(t.Context()) + stream, err := client.CountUp(ctx, &pingv1.CountUpRequest{Number: 1}) + assert.Nil(t, err) + t.Cleanup(func() { _ = stream.Close() }) + _, err = stream.Receive() + assert.NotNil(t, err) + assert.Equal(t, connect.CodeOf(err), connect.CodeUnavailable) + + assert.Equal(t, info.ResponseHeader().Values("Lead"), []string{"header-value"}) + assert.Equal(t, info.ResponseTrailer().Values("Trail"), []string{"trailer-value"}) +} + +// A stream carries exactly one M message and it opens the stream, so a later +// one is refused. It has to be: the opening message is +// consumed before the handler is dispatched, and a second would write the +// handler's own request metadata while it is running. +func TestLateLeadingMetadataIsRejected(t *testing.T) { + t.Parallel() + httpServer := newHybridServer(t, pingServer{}) + conn := dialCumSum(t, httpServer, "") + + // A body first, then metadata: the illegal order. + sendProtoBody(t, conn, &pingv1.CumSumRequest{Number: 1}) + reply := readServerOpening(t, conn) // past the server's own M, to the handler's reply + assert.Equal(t, reply[0], wireBody) + + sendJSONMessage(t, conn, wireMetadata, []byte(`[["Acme-Late","nope"]]`)) + readCtx, cancelRead := readContext(t) + defer cancelRead() + _, data, err := conn.Read(readCtx) + assert.Nil(t, err) + assert.True(t, strings.Contains(string(data), "internal")) + assert.True(t, strings.Contains(string(data), "second M message")) +} + +// Every response stream opens with exactly one M, even when the handler sets +// no metadata at all. The empty message is not waste: it is what tells a +// client the server has accepted the stream and begun, which the response +// header block does for free over HTTP. +func TestServerAlwaysOpensWithLeadingMetadata(t *testing.T) { + t.Parallel() + httpServer := newHybridServer(t, pingServer{}) + conn := dialCumSum(t, httpServer, "") + sendProtoBody(t, conn, &pingv1.CumSumRequest{Number: 1}) + + readCtx, cancelRead := readContext(t) + defer cancelRead() + messageType, opening, err := conn.Read(readCtx) + assert.Nil(t, err) + assert.Equal(t, messageType, websocket.MessageText) // JSON, so a text frame + assert.Equal(t, string(opening), "M[]") // empty, but present +} + +// A server that sent a second M would be rewriting headers the application may +// already have read — the race the request side refuses for the same reason. +func TestSecondServerLeadingMetadataIsRejected(t *testing.T) { + t.Parallel() + httpServer := misframingServer(t, func(conn *websocket.Conn) { + // misframingServer already sent the opening M; this is the second. + _ = conn.Write(context.Background(), websocket.MessageText, []byte(`M[["acme-late","nope"]]`)) + }) + recorder := &clientFaultRecorder{} + transport := connecthttp.NewTransport( + httpServer.Client(), + httpServer.URL, + connecthttp.WithWebSocket(connecthttp.SelectStreaming), + connecthttp.WithWebSocketClientProtocolErrorHandler(recorder.handle), + ) + client := pingv1connect.NewPingServiceClient(connect.NewClient(transport)) + stream, err := client.CumSum(t.Context()) + assert.Nil(t, err) + t.Cleanup(func() { _ = stream.Close() }) + assert.Nil(t, stream.Send(&pingv1.CumSumRequest{Number: 1})) + + _, receiveErr := stream.Receive() + assert.NotNil(t, receiveErr) + assert.True(t, strings.Contains(receiveErr.Error(), "second M message")) + + faults, _ := recorder.seen() + assert.Equal(t, faults, []wstransport.ProtocolFault{wstransport.FaultMetadata}) +} diff --git a/internal/wstransport/metadatacodec_ext_test.go b/internal/wstransport/metadatacodec_ext_test.go new file mode 100644 index 00000000..e8b6091d --- /dev/null +++ b/internal/wstransport/metadatacodec_ext_test.go @@ -0,0 +1,480 @@ +// Copyright 2021-2026 The Connect Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package wstransport_test + +import ( + "context" + "encoding/base64" + "encoding/json" + "errors" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "connectrpc.com/connect/v2" + "connectrpc.com/connect/v2/connecthttp" + "connectrpc.com/connect/v2/internal/assert" + pingv1 "connectrpc.com/connect/v2/internal/gen/connect/ping/v1" + "connectrpc.com/connect/v2/internal/gen/connect/ping/v1/pingv1connect" +) + +// echoMetadataServer reports one request header back as a trailer, so a test +// can watch a value make the round trip. +type echoMetadataServer struct { + pingv1connect.UnimplementedPingServiceHandler + + readKey string + writeKey string +} + +func (s echoMetadataServer) CumSum( + ctx context.Context, + stream pingv1connect.PingServiceCumSumServerStream, +) error { + info, _ := connect.CallInfoForServerContext(ctx) + info.ResponseTrailer().SetValues(s.writeKey, info.RequestHeader().Values(s.readKey)) + for { + if _, err := stream.Receive(); err != nil { + if errors.Is(err, io.EOF) { + return nil + } + return err + } + } +} + +// A -bin value carries bytes that are not valid UTF-8, which JSON cannot hold +// unencoded. As over HTTP, the application holds the base64 form, and the +// transport carries it unchanged in both directions. +func TestBinaryMetadataSurvivesTheRoundTrip(t *testing.T) { + t.Parallel() + raw := []byte{0x00, 0xff, 0xfe, 0x80, 'h', 'i'} + encoded := connect.EncodeBinaryHeader(raw) + server := connect.NewServer() + pingv1connect.RegisterPingServiceHandler(server, echoMetadataServer{ + readKey: "Acme-Token-Bin", writeKey: "Acme-Echo-Bin", + }) + mux := http.NewServeMux() + connecthttp.Mount(mux, server) + httpServer := httptest.NewServer(mux) + t.Cleanup(httpServer.Close) + + transport := connecthttp.NewTransport( + httpServer.Client(), + httpServer.URL, + connecthttp.WithWebSocket(connecthttp.SelectStreaming), + ) + client := pingv1connect.NewPingServiceClient(connect.NewClient(transport)) + + ctx, info := connect.NewClientContext(t.Context()) + info.RequestHeader().SetValues("Acme-Token-Bin", []string{encoded}) + stream, err := client.CumSum(ctx) + assert.Nil(t, err) + assert.Nil(t, stream.Send(&pingv1.CumSumRequest{Number: 1})) + assert.Nil(t, stream.CloseSend()) + _, err = stream.Receive() + assert.True(t, errors.Is(err, io.EOF)) + assert.Nil(t, stream.Close()) + + echoed := info.ResponseTrailer().Get("Acme-Echo-Bin") + assert.Equal(t, echoed, encoded) + decoded, err := connect.DecodeBinaryHeader(echoed) + assert.Nil(t, err) + assert.Equal(t, decoded, raw) +} + +// The wire form is what a second implementation has to agree with: lower-case +// keys, and -bin values exactly as the application encoded them. +func TestMetadataWireForm(t *testing.T) { + t.Parallel() + raw := []byte{0x00, 0xff, 0xfe} + server := connect.NewServer() + pingv1connect.RegisterPingServiceHandler(server, trailerWritingServer{ + key: "Acme-Echo-Bin", value: connect.EncodeBinaryHeader(raw), + }) + mux := http.NewServeMux() + connecthttp.Mount(mux, server) + httpServer := httptest.NewServer(mux) + t.Cleanup(httpServer.Close) + + conn := dialRaw(t, httpServer, pingv1connect.PingServiceCumSumProcedure) + sendJSONMessage(t, conn, wireMetadata, []byte(`[]`)) + sendJSONMessage(t, conn, wireClientEndStream, nil) + + data := readServerOpening(t, conn) + assert.Equal(t, data[0], wireServerEndStream) + + var end struct { + Metadata map[string][]string `json:"metadata"` + } + assert.Nil(t, json.Unmarshal(data[1:], &end)) + values, ok := end.Metadata["acme-echo-bin"] + assert.True(t, ok) // lower-case on the wire, not canonical MIME case + assert.Equal(t, len(values), 1) + assert.Equal(t, values[0], base64.RawStdEncoding.EncodeToString(raw)) +} + +// trailerWritingServer sets one trailer and returns. +type trailerWritingServer struct { + pingv1connect.UnimplementedPingServiceHandler + + key string + value string +} + +func (s trailerWritingServer) CumSum( + ctx context.Context, + _ pingv1connect.PingServiceCumSumServerStream, +) error { + info, _ := connect.CallInfoForServerContext(ctx) + info.ResponseTrailer().SetValues(s.key, []string{s.value}) + return nil +} + +// §7.3.1: keys are lower-case on the wire, as in HTTP/2, so a key with an +// upper-case character is a protocol error rather than a second spelling. +func TestUpperCaseMetadataKeyIsRejected(t *testing.T) { + t.Parallel() + for _, key := range []string{"Acme-Tenant", "ACME-TENANT", "acme-Tenant"} { + t.Run(key, func(t *testing.T) { + t.Parallel() + httpServer := newHybridServer(t, pingServer{}) + conn := dialRaw(t, httpServer, pingv1connect.PingServiceCumSumProcedure) + sendJSONMessage(t, conn, wireMetadata, []byte(`[["`+key+`","x"]]`)) + + data := readServerOpening(t, conn) + assert.Equal(t, data[0], wireServerEndStream) + assert.True(t, strings.Contains(string(data), "internal")) + assert.True(t, strings.Contains(string(data), "not lower-case")) + }) + } +} + +// §7.3.1: as over HTTP, a -bin value is not decoded on arrival. It reaches the +// application as sent, and fails, if at all, only when decoded there. +func TestBinaryMetadataPassesThroughUndecoded(t *testing.T) { + t.Parallel() + for _, test := range []struct { + name string + value string + }{ + { + // Senders must not pad, but the padding is unambiguous, and refusing + // it would fail an RPC over a value that decodes fine. + name: "padded", + value: base64.StdEncoding.EncodeToString([]byte{0x00, 0xff}), + }, + {name: "not base64", value: "not!base64"}, + { + // What a -bin value decodes to is not a field value, so the + // field-value rule cannot apply to it. + name: "decodes to bytes no field value may hold", + value: base64.RawStdEncoding.EncodeToString([]byte{'\r', '\n', 0x00, 0xff}), + }, + } { + t.Run(test.name, func(t *testing.T) { + t.Parallel() + server := connect.NewServer() + pingv1connect.RegisterPingServiceHandler(server, echoMetadataServer{ + readKey: "Acme-Token-Bin", writeKey: "Acme-Echo", + }) + mux := http.NewServeMux() + connecthttp.Mount(mux, server) + httpServer := httptest.NewServer(mux) + t.Cleanup(httpServer.Close) + + conn := dialRaw(t, httpServer, pingv1connect.PingServiceCumSumProcedure) + sendJSONMessage(t, conn, wireMetadata, []byte(`[["acme-token-bin","`+test.value+`"]]`)) + sendJSONMessage(t, conn, wireClientEndStream, nil) + + data := readServerOpening(t, conn) + assert.Equal(t, data[0], wireServerEndStream) + var end struct { + Error json.RawMessage `json:"error"` + Metadata map[string][]string `json:"metadata"` + } + assert.Nil(t, json.Unmarshal(data[1:], &end)) + assert.Equal(t, len(end.Error), 0) + assert.Equal(t, end.Metadata["acme-echo"], []string{test.value}) + }) + } +} + +// Two entries whose keys fold to one would leave the receiver to choose between +// them, a choice the sender cannot see. It is a protocol error instead. +func TestDuplicateMetadataKeysAreRejected(t *testing.T) { + t.Parallel() + for _, test := range []struct { + name string + payload string + }{ + {name: "differing only in case", payload: `[["acme-tenant","a"],["Acme-Tenant","b"]]`}, + {name: "spelled identically", payload: `[["acme-tenant","a"],["acme-tenant","b"]]`}, + } { + t.Run(test.name, func(t *testing.T) { + t.Parallel() + httpServer := newHybridServer(t, pingServer{}) + conn := dialRaw(t, httpServer, pingv1connect.PingServiceCumSumProcedure) + sendJSONMessage(t, conn, wireMetadata, []byte(test.payload)) + + data := readServerOpening(t, conn) + assert.Equal(t, data[0], wireServerEndStream) + assert.True(t, strings.Contains(string(data), "internal")) + assert.True(t, strings.Contains(string(data), "same key")) + }) + } +} + +// Metadata stands in for HTTP headers and may be forwarded as one, so a key +// that is not a field name, or a value carrying the bytes that end a header +// line, cannot be passed through. +func TestMalformedMetadataNamesAndValuesAreRejected(t *testing.T) { + t.Parallel() + for _, test := range []struct { + name string + payload string + mention string + }{ + { + name: "space in the key", + payload: `[["acme tenant","x"]]`, + mention: "field name", + }, + { + name: "separator in the key", + payload: `[["acme:tenant","x"]]`, + mention: "field name", + }, + { + name: "empty key", + payload: `[["","x"]]`, + mention: "field name", + }, + { + // A header injection wherever this is forwarded as HTTP. + name: "CRLF in the value", + payload: `[["acme-tenant","a\r\nX-Evil: 1"]]`, + mention: "field value", + }, + { + name: "NUL in the value", + payload: `[["acme-tenant","a\u0000b"]]`, + mention: "field value", + }, + { + // RFC 9110 allows obs-text, but a JSON string has no byte form for it. + name: "non-ASCII in the value", + payload: `[["acme-tenant","café"]]`, + mention: "field value", + }, + { + name: "DEL in the value", + payload: `[["acme-tenant","a\u007fb"]]`, + mention: "field value", + }, + } { + t.Run(test.name, func(t *testing.T) { + t.Parallel() + httpServer := newHybridServer(t, pingServer{}) + conn := dialRaw(t, httpServer, pingv1connect.PingServiceCumSumProcedure) + sendJSONMessage(t, conn, wireMetadata, []byte(test.payload)) + + data := readServerOpening(t, conn) + assert.Equal(t, data[0], wireServerEndStream) + assert.True(t, strings.Contains(string(data), "internal")) + assert.True(t, strings.Contains(string(data), test.mention)) + }) + } +} + +// An entry is an array of strings, the key first. Anything else, including the +// JSON object an earlier draft used, is a protocol error. +func TestMalformedMetadataEntriesAreRejected(t *testing.T) { + t.Parallel() + for _, test := range []struct { + name string + payload string + mention string + }{ + {name: "object, not array", payload: `{"acme-tenant":["a"]}`, mention: "unmarshal M message"}, + {name: "null, not array", payload: `null`, mention: "M message is null"}, + {name: "entry is not an array", payload: `["acme-tenant"]`, mention: "unmarshal M message"}, + {name: "entry has no key", payload: `[[]]`, mention: "metadata entry is empty"}, + {name: "value is not a string", payload: `[["acme-tenant",1]]`, mention: "unmarshal M message"}, + {name: "values nested in an array", payload: `[["acme-tenant",["a"]]]`, mention: "unmarshal M message"}, + } { + t.Run(test.name, func(t *testing.T) { + t.Parallel() + httpServer := newHybridServer(t, pingServer{}) + conn := dialRaw(t, httpServer, pingv1connect.PingServiceCumSumProcedure) + sendJSONMessage(t, conn, wireMetadata, []byte(test.payload)) + + data := readServerOpening(t, conn) + assert.Equal(t, data[0], wireServerEndStream) + assert.True(t, strings.Contains(string(data), test.mention)) + }) + } +} + +// One entry carries every value of its key. §7.3.1 gives every key at least +// one value, and an empty string is one. Leading and trailing whitespace is +// not part of a value, as in RFC 9110 §5.5. +func TestMetadataEntryCarriesAllItsValues(t *testing.T) { + t.Parallel() + for _, test := range []struct { + name string + payload string + want []string + }{ + {name: "several values", payload: `[["acme-tenant","a","b"]]`, want: []string{"a", "b"}}, + {name: "one empty value", payload: `[["acme-tenant",""]]`, want: []string{""}}, + {name: "tab inside a value", payload: `[["acme-tenant","a\tb"]]`, want: []string{"a\tb"}}, + {name: "surrounding whitespace", payload: `[["acme-tenant"," \ta b\t ","c "]]`, want: []string{"a b", "c"}}, + {name: "whitespace only", payload: `[["acme-tenant"," \t "]]`, want: []string{""}}, + } { + t.Run(test.name, func(t *testing.T) { + t.Parallel() + server := connect.NewServer() + pingv1connect.RegisterPingServiceHandler(server, echoMetadataServer{ + readKey: "Acme-Tenant", writeKey: "Acme-Echo", + }) + mux := http.NewServeMux() + connecthttp.Mount(mux, server) + httpServer := httptest.NewServer(mux) + t.Cleanup(httpServer.Close) + + conn := dialRaw(t, httpServer, pingv1connect.PingServiceCumSumProcedure) + sendJSONMessage(t, conn, wireMetadata, []byte(test.payload)) + sendJSONMessage(t, conn, wireClientEndStream, nil) + + data := readServerOpening(t, conn) + assert.Equal(t, data[0], wireServerEndStream) + var end struct { + Error json.RawMessage `json:"error"` + Metadata map[string][]string `json:"metadata"` + } + assert.Nil(t, json.Unmarshal(data[1:], &end)) + assert.Equal(t, len(end.Error), 0) + assert.Equal(t, len(end.Metadata["acme-echo"]), len(test.want)) + for index, value := range test.want { + assert.Equal(t, end.Metadata["acme-echo"][index], value) + } + }) + } +} + +// §7.3.1: an entry that holds only a key is a protocol error. A sender that +// means "present but empty" sends an empty string. +func TestMetadataKeyWithoutValuesIsRejected(t *testing.T) { + t.Parallel() + httpServer := newHybridServer(t, pingServer{}) + conn := dialRaw(t, httpServer, pingv1connect.PingServiceCumSumProcedure) + sendJSONMessage(t, conn, wireMetadata, []byte(`[["acme-tenant"]]`)) + + data := readServerOpening(t, conn) + assert.Equal(t, data[0], wireServerEndStream) + assert.True(t, strings.Contains(string(data), "internal")) + assert.True(t, strings.Contains(string(data), "has no values")) +} + +// A sender puts every value of a key in one entry, with the key lower-case. +func TestLeadingMetadataWireForm(t *testing.T) { + t.Parallel() + server := connect.NewServer() + pingv1connect.RegisterPingServiceHandler(server, leadingHeaderServer{}) + mux := http.NewServeMux() + connecthttp.Mount(mux, server) + httpServer := httptest.NewServer(mux) + t.Cleanup(httpServer.Close) + + conn := dialRaw(t, httpServer, pingv1connect.PingServiceCumSumProcedure) + sendJSONMessage(t, conn, wireMetadata, []byte(`[]`)) + sendJSONMessage(t, conn, wireClientEndStream, nil) + + ctx, cancel := readContext(t) + defer cancel() + _, opening, err := conn.Read(ctx) + assert.Nil(t, err) + assert.Equal(t, string(opening), `M[["acme-tenant","a","b"],["acme-zone","z"]]`) +} + +// leadingHeaderServer sets response headers and returns. +type leadingHeaderServer struct { + pingv1connect.UnimplementedPingServiceHandler +} + +func (leadingHeaderServer) CumSum( + ctx context.Context, + _ pingv1connect.PingServiceCumSumServerStream, +) error { + info, _ := connect.CallInfoForServerContext(ctx) + info.ResponseHeader().SetValues("Acme-Zone", []string{"z"}) + info.ResponseHeader().SetValues("Acme-Tenant", []string{"a", "b"}) + return nil +} + +// An M with no payload is not an empty array; empty metadata is []. +func TestBareMetadataMarkerIsRejected(t *testing.T) { + t.Parallel() + httpServer := newHybridServer(t, pingServer{}) + conn := dialRaw(t, httpServer, pingv1connect.PingServiceCumSumProcedure) + sendJSONMessage(t, conn, wireMetadata, nil) + + data := readServerOpening(t, conn) + assert.Equal(t, data[0], wireServerEndStream) + assert.True(t, strings.Contains(string(data), "empty M message")) +} + +// Request metadata travels in the M message and nowhere else. A client that +// also put it on the handshake would shadow its own message, since the +// handshake wins on a key collision. +func TestRequestMetadataDoesNotRideTheHandshake(t *testing.T) { + t.Parallel() + handshake := make(chan http.Header, 1) + mux := http.NewServeMux() + mux.Handle("/", http.HandlerFunc(func(_ http.ResponseWriter, request *http.Request) { + select { + case handshake <- request.Header.Clone(): + default: + } + })) + httpServer := httptest.NewServer(mux) + t.Cleanup(httpServer.Close) + + transport := connecthttp.NewTransport( + httpServer.Client(), + httpServer.URL, + connecthttp.WithWebSocket(connecthttp.SelectAll), + ) + client := pingv1connect.NewPingServiceClient(connect.NewClient(transport)) + + ctx, info := connect.NewClientContext(t.Context()) + info.RequestHeader().SetValues("Acme-Tenant", []string{"t1"}) + // The handshake fails — this server never upgrades — but it is the request + // that matters here. + _, _ = client.Ping(ctx, &pingv1.PingRequest{Number: 1}) + + select { + case header := <-handshake: + assert.Equal(t, header.Get("Acme-Tenant"), "") + // The transport's own headers are still there. + assert.True(t, header.Get("Sec-WebSocket-Protocol") != "") + case <-time.After(5 * time.Second): + t.Fatal("the client never sent a handshake") + } +} diff --git a/internal/wstransport/metadataspec_ext_test.go b/internal/wstransport/metadataspec_ext_test.go new file mode 100644 index 00000000..88a4e1b6 --- /dev/null +++ b/internal/wstransport/metadataspec_ext_test.go @@ -0,0 +1,185 @@ +// Copyright 2021-2026 The Connect Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package wstransport_test + +import ( + "context" + "net/http" + "net/http/httptest" + "strings" + "sync/atomic" + "testing" + + "connectrpc.com/connect/v2" + "connectrpc.com/connect/v2/connecthttp" + "connectrpc.com/connect/v2/internal/assert" + pingv1 "connectrpc.com/connect/v2/internal/gen/connect/ping/v1" + "connectrpc.com/connect/v2/internal/gen/connect/ping/v1/pingv1connect" + "connectrpc.com/connect/v2/internal/wstransport" + "google.golang.org/protobuf/proto" +) + +// headerSettingServer sets the given response headers, optionally flushing +// them before setting one more, and answers with one message. +type headerSettingServer struct { + pingv1connect.UnimplementedPingServiceHandler + + headers http.Header + flush bool + lateKey string + requested chan http.Header +} + +func (s headerSettingServer) CountUp( + ctx context.Context, + _ *pingv1.CountUpRequest, + stream pingv1connect.PingServiceCountUpServerStream, +) error { + info, _ := connect.CallInfoForServerContext(ctx) + if s.requested != nil { + requested := make(http.Header) + for key, values := range info.RequestHeader().All() { + requested[http.CanonicalHeaderKey(key)] = values + } + s.requested <- requested + } + for key, values := range s.headers { + info.ResponseHeader().SetValues(key, values) + } + if s.flush { + if err := stream.SendHeaders(); err != nil { + return err + } + info.ResponseHeader().Set(s.lateKey, "late") + } + return stream.Send(&pingv1.CountUpResponse{Number: 1}) +} + +func openCountUp(tb testing.TB, httpServer *httptest.Server, metadata string) *browserClient { + tb.Helper() + client := dialBrowserClientOpening(tb, httpServer, pingv1connect.PingServiceCountUpProcedure, []byte(metadata)) + payload, err := proto.Marshal(&pingv1.CountUpRequest{Number: 1}) + assert.Nil(tb, err) + client.writeProto(tb, payload) + client.writeJSON(tb, wireClientEndStream, nil) + return client +} + +// §7.3.1 binds the sender: values are trimmed, and -bin values are unpadded. +func TestServerSendsTrimmedUnpaddedMetadata(t *testing.T) { + t.Parallel() + httpServer := newServerFor(t, headerSettingServer{headers: http.Header{ + "Acme-Bin": {"YQ=="}, + "Acme-Spaced": {" value \t"}, + }}) + client := openCountUp(t, httpServer, "[]") + marker, metadata, _ := client.readMessage(t) + assert.Equal(t, marker, wireMetadata) + assert.Equal(t, string(metadata), `[["acme-bin","YQ"],["acme-spaced","value"]]`) +} + +// §7.3.1: a header the server may not send is not sent. M still opens the +// stream, empty, and the RPC fails naming the header. +func TestServerRefusesToSendInvalidResponseHeader(t *testing.T) { + t.Parallel() + for name, value := range map[string]string{ + "control character": "a\nb", + "non-ASCII": "café", + } { + t.Run(name, func(t *testing.T) { + t.Parallel() + httpServer := newServerFor(t, headerSettingServer{headers: http.Header{"Acme-Bad": {value}}}) + client := openCountUp(t, httpServer, "[]") + marker, metadata, _ := client.readMessage(t) + assert.Equal(t, marker, wireMetadata) + assert.Equal(t, string(metadata), "[]") + marker, endStream, _ := client.readMessage(t) + assert.Equal(t, marker, wireServerEndStream) + assert.True(t, strings.Contains(string(endStream), `"code":"internal"`)) + assert.True(t, strings.Contains(string(endStream), "Acme-Bad")) + }) + } +} + +// §7.4: an explicit flush sends M then, and a header set after it is late and +// not sent. +func TestSendHeadersFlushesLeadingMetadata(t *testing.T) { + t.Parallel() + httpServer := newServerFor(t, headerSettingServer{ + headers: http.Header{"Acme-Early": {"early"}}, + flush: true, + lateKey: "Acme-Late", + }) + client := openCountUp(t, httpServer, "[]") + marker, metadata, _ := client.readMessage(t) + assert.Equal(t, marker, wireMetadata) + assert.Equal(t, string(metadata), `[["acme-early","early"]]`) + marker, _, _ = client.readMessage(t) + assert.Equal(t, marker, wireBody) + marker, endStream, _ := client.readMessage(t) + assert.Equal(t, marker, wireServerEndStream) + assert.False(t, strings.Contains(string(endStream), "late")) +} + +// §7.3.1: a receiver trims every value before delivering it, -bin ones too. +func TestReceiverTrimsBinaryValues(t *testing.T) { + t.Parallel() + requested := make(chan http.Header, 1) + httpServer := newServerFor(t, headerSettingServer{requested: requested}) + _ = openCountUp(t, httpServer, `[["acme-bin"," YQ \t"],["acme-text"," v "]]`) + header := <-requested + assert.Equal(t, header.Get("Acme-Bin"), "YQ") + assert.Equal(t, header.Get("Acme-Text"), "v") +} + +// §7.3.2 and §7.3.1 bind a client's M too. A header the client may not send +// fails the call before it dials, rather than as the server's protocol error. +func TestClientRefusesRequestHeadersItMayNotSend(t *testing.T) { + t.Parallel() + server := connect.NewServer() + pingv1connect.RegisterPingServiceHandler(server, pingServer{}) + mux := http.NewServeMux() + mountBoth(mux, server) + var upgrades atomic.Int32 + httpServer := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) { + if wstransport.IsUpgrade(request) { + upgrades.Add(1) + } + mux.ServeHTTP(writer, request) + })) + t.Cleanup(httpServer.Close) + transport := connecthttp.NewTransport( + httpServer.Client(), + httpServer.URL, + connecthttp.WithWebSocket(connecthttp.SelectAll), + ) + client := pingv1connect.NewPingServiceClient(connect.NewClient(transport)) + for _, test := range []struct { + key, value, mention string + }{ + {key: "Cookie", value: "session=1", mention: "Fetch"}, + {key: "Connect-Acme", value: "1", mention: "protocol"}, + {key: "X-Forwarded-For", value: "10.0.0.1", mention: "deny list"}, + {key: "Acme-Bad", value: "a\nb", mention: "valid HTTP field value"}, + {key: "Acme-Bin", value: "not base64!", mention: "base64"}, + } { + ctx, info := connect.NewClientContext(t.Context()) + info.RequestHeader().Set(test.key, test.value) + _, err := client.Ping(ctx, &pingv1.PingRequest{Number: 1}) + assert.Equal(t, connect.CodeOf(err), connect.CodeInternal, assert.Sprintf("header %s", test.key)) + assert.True(t, err != nil && strings.Contains(err.Error(), test.mention), assert.Sprintf("%v", err)) + } + assert.Equal(t, upgrades.Load(), int32(0)) +} diff --git a/internal/wstransport/mountoptions_ext_test.go b/internal/wstransport/mountoptions_ext_test.go new file mode 100644 index 00000000..df64bc28 --- /dev/null +++ b/internal/wstransport/mountoptions_ext_test.go @@ -0,0 +1,242 @@ +// Copyright 2021-2026 The Connect Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package wstransport_test + +import ( + "context" + "errors" + "io" + "net/http" + "net/http/httptest" + "strings" + "sync/atomic" + "testing" + + "connectrpc.com/connect/v2" + "connectrpc.com/connect/v2/connecthttp" + "connectrpc.com/connect/v2/internal/assert" + pingv1 "connectrpc.com/connect/v2/internal/gen/connect/ping/v1" + "connectrpc.com/connect/v2/internal/gen/connect/ping/v1/pingv1connect" +) + +func newWebSocketClient(tb testing.TB, httpClient connecthttp.HTTPClient, baseURL string) pingv1connect.PingServiceClient { + tb.Helper() + transport := connecthttp.NewTransport(httpClient, baseURL, connecthttp.WithWebSocket(connecthttp.SelectAll)) + return pingv1connect.NewPingServiceClient(connect.NewClient(transport)) +} + +// Per-procedure options configure a procedure whichever transport carries it. +func TestConditionalOptionsReachWebSocketRoutes(t *testing.T) { + t.Parallel() + httpServer := newMountedServer(t, connecthttp.WithConditionalOptions(func(spec connect.Spec) []connecthttp.Option { + if spec.Procedure == pingv1connect.PingServiceCumSumProcedure { + return []connecthttp.Option{connecthttp.WithReadMaxBytes(1)} + } + return nil + })) + client := newWebSocketClient(t, httpServer.Client(), httpServer.URL) + + ctx, info := connect.NewClientContext(t.Context()) + _, err := client.Ping(ctx, &pingv1.PingRequest{Text: strings.Repeat("x", 64)}) + assert.Nil(t, err) + assert.Equal(t, info.Protocol, connecthttp.ProtocolNameConnectWebSocket) + + stream, err := client.CumSum(t.Context()) + assert.Nil(t, err) + // A one-byte limit rejects even the opening M, so the verdict can beat the + // first body to the wire; Send then reports io.EOF, as over HTTP. + if err := stream.Send(&pingv1.CumSumRequest{Number: 1000}); err != nil { + assert.True(t, errors.Is(err, io.EOF), assert.Sprintf("%v", err)) + } + _, err = stream.Receive() + assert.Equal(t, connect.CodeOf(err), connect.CodeResourceExhausted) + assert.Nil(t, stream.Close()) +} + +func TestConditionalOptionsReachWebSocketClients(t *testing.T) { + t.Parallel() + httpServer := newMountedServer(t) + transport := connecthttp.NewTransport( + httpServer.Client(), + httpServer.URL, + connecthttp.WithConditionalOptions(func(spec connect.Spec) []connecthttp.Option { + if spec.Procedure == pingv1connect.PingServicePingProcedure { + return []connecthttp.Option{connecthttp.WithWebSocket(connecthttp.SelectAll)} + } + return nil + }), + ) + client := pingv1connect.NewPingServiceClient(connect.NewClient(transport)) + + ctx, info := connect.NewClientContext(t.Context()) + _, err := client.Ping(ctx, &pingv1.PingRequest{Number: 1}) + assert.Nil(t, err) + assert.Equal(t, info.Protocol, connecthttp.ProtocolNameConnectWebSocket) + + ctx, info = connect.NewClientContext(t.Context()) + _, err = client.Fail(ctx, &pingv1.FailRequest{}) + assert.NotNil(t, err) + assert.Equal(t, info.Protocol, connect.ProtocolNameConnect) +} + +// prefixMux serves every route under a prefix it does not strip, as a router +// mounting a sub-router might. +type prefixMux struct { + mux *http.ServeMux + prefix string +} + +func (m prefixMux) Handle(pattern string, handler http.Handler) { + m.mux.Handle(m.prefix+pattern, handler) +} + +// A route registered for a procedure serves that procedure, whatever path the +// mux reached it by, as it does over HTTP. +func TestWebSocketRouteServesItsRegisteredProcedure(t *testing.T) { + t.Parallel() + server := connect.NewServer() + pingv1connect.RegisterPingServiceHandler(server, pingServer{}) + mux := http.NewServeMux() + connecthttp.Mount(prefixMux{mux: mux, prefix: "/api"}, server) + httpServer := httptest.NewServer(mux) + t.Cleanup(httpServer.Close) + client := newWebSocketClient(t, httpServer.Client(), httpServer.URL+"/api") + + response, err := client.Ping(t.Context(), &pingv1.PingRequest{Number: 7}) + assert.Nil(t, err) + assert.Equal(t, response.GetNumber(), int64(7)) +} + +type serverInfoServer struct { + pingv1connect.UnimplementedPingServiceHandler + + infos chan *connecthttp.ServerInfo + hosts chan string +} + +func (s serverInfoServer) Ping(ctx context.Context, _ *pingv1.PingRequest) (*pingv1.PingResponse, error) { + info, _ := connecthttp.ServerInfoForContext(ctx) + s.infos <- info + callInfo, _ := connect.CallInfoForServerContext(ctx) + s.hosts <- callInfo.RequestHeader().Get("Host") + return &pingv1.PingResponse{}, nil +} + +// A handler reads the same transport details whichever transport ran it. +func TestWebSocketRPCCarriesServerInfo(t *testing.T) { + t.Parallel() + handler := serverInfoServer{infos: make(chan *connecthttp.ServerInfo, 1), hosts: make(chan string, 1)} + server := connect.NewServer() + pingv1connect.RegisterPingServiceHandler(server, handler) + mux := http.NewServeMux() + connecthttp.Mount(mux, server) + httpServer := httptest.NewServer(mux) + t.Cleanup(httpServer.Close) + client := newWebSocketClient(t, httpServer.Client(), httpServer.URL) + + _, err := client.Ping(t.Context(), &pingv1.PingRequest{}) + assert.Nil(t, err) + info := <-handler.infos + assert.NotNil(t, info) + assert.Equal(t, info.HTTPMethod(), http.MethodGet) + requestURL := info.RequestURL() + assert.Equal(t, requestURL.Path, pingv1connect.PingServicePingProcedure) + assert.Equal(t, <-handler.hosts, strings.TrimPrefix(httpServer.URL, "http://")) +} + +type countingHTTPClient struct { + client *http.Client + calls atomic.Int32 +} + +func (c *countingHTTPClient) Do(request *http.Request) (*http.Response, error) { + c.calls.Add(1) + return c.client.Do(request) +} + +// An HTTPClient that is not an *http.Client still carries the handshake, so +// whatever it adds (auth, tracing, a proxy) applies to both transports. +func TestHandshakeGoesThroughACustomHTTPClient(t *testing.T) { + t.Parallel() + httpServer := newMountedServer(t) + httpClient := &countingHTTPClient{client: httpServer.Client()} + client := newWebSocketClient(t, httpClient, httpServer.URL) + + ctx, info := connect.NewClientContext(t.Context()) + _, err := client.Ping(ctx, &pingv1.PingRequest{Number: 1}) + assert.Nil(t, err) + assert.Equal(t, info.Protocol, connecthttp.ProtocolNameConnectWebSocket) + assert.Equal(t, httpClient.calls.Load(), int32(1)) +} + +type requestHeaderServer struct { + pingv1connect.UnimplementedPingServiceHandler + + seen chan string +} + +func (s requestHeaderServer) CumSum(ctx context.Context, _ pingv1connect.PingServiceCumSumServerStream) error { + info, _ := connect.CallInfoForServerContext(ctx) + s.seen <- info.RequestHeader().Get("Acme-Late") + return nil +} + +// Request headers may be set until the first Send, as over HTTP. +func TestRequestHeadersAreReadAtFirstSend(t *testing.T) { + t.Parallel() + handler := requestHeaderServer{seen: make(chan string, 1)} + server := connect.NewServer() + pingv1connect.RegisterPingServiceHandler(server, handler) + mux := http.NewServeMux() + connecthttp.Mount(mux, server) + httpServer := httptest.NewServer(mux) + t.Cleanup(httpServer.Close) + client := newWebSocketClient(t, httpServer.Client(), httpServer.URL) + + ctx, info := connect.NewClientContext(t.Context()) + stream, err := client.CumSum(ctx) + assert.Nil(t, err) + info.RequestHeader().Set("Acme-Late", "set after the stream opened") + // The handler returns without reading, so its verdict can beat the body to + // the wire; Send then reports io.EOF, as over HTTP. + if err := stream.Send(&pingv1.CumSumRequest{Number: 1}); err != nil { + assert.True(t, errors.Is(err, io.EOF), assert.Sprintf("%v", err)) + } + assert.Equal(t, <-handler.seen, "set after the stream opened") + assert.Nil(t, stream.CloseSend()) + _, err = stream.Receive() + assert.True(t, errors.Is(err, io.EOF)) + assert.Nil(t, stream.Close()) +} + +// The client's CallInfo is as complete as over HTTP: the spec, the message +// sizes, and the HTTP exchange, which for WebSocket is the handshake. +func TestClientCallInfoDescribesTheCall(t *testing.T) { + t.Parallel() + httpServer := newMountedServer(t) + client := newWebSocketClient(t, httpServer.Client(), httpServer.URL) + + ctx, info := connect.NewClientContext(t.Context()) + _, err := client.Ping(ctx, &pingv1.PingRequest{Number: 1, Text: "hello"}) + assert.Nil(t, err) + assert.Equal(t, info.Spec.Procedure, pingv1connect.PingServicePingProcedure) + assert.Equal(t, info.Spec.StreamType, connect.StreamTypeUnary) + assert.True(t, info.SendStats.Size > 0) + assert.True(t, info.ReceiveStats.Size > 0) + clientInfo, ok := connecthttp.ClientInfoForContext(ctx) + assert.True(t, ok) + assert.Equal(t, clientInfo.HTTPMethod(), http.MethodGet) + assert.Equal(t, clientInfo.ResponseStatus(), http.StatusSwitchingProtocols) +} diff --git a/internal/wstransport/origin_ext_test.go b/internal/wstransport/origin_ext_test.go new file mode 100644 index 00000000..41d7bce8 --- /dev/null +++ b/internal/wstransport/origin_ext_test.go @@ -0,0 +1,99 @@ +// Copyright 2021-2026 The Connect Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package wstransport_test + +import ( + "net/http" + "net/http/httptest" + "testing" + + "connectrpc.com/connect/v2" + "connectrpc.com/connect/v2/connecthttp" + "connectrpc.com/connect/v2/internal/assert" + "connectrpc.com/connect/v2/internal/gen/connect/ping/v1/pingv1connect" +) + +// §4.4: a request with no Origin is not from a browser, and one whose origin +// names the request's own host is the ordinary same-origin call. Behind a +// TLS-terminating proxy the page's origin is https on a plaintext connection, +// so the scheme is not compared, whether it comes from there or from a header. +func TestSameOriginAndOriginlessUpgradesAreAllowed(t *testing.T) { + t.Parallel() + for _, test := range []struct { + name string + scheme string + forwardedProto string + }{ + {name: "no Origin"}, + {name: "same origin", scheme: "http"}, + {name: "https origin on plaintext", scheme: "https"}, + {name: "https origin, proxy says http", scheme: "https", forwardedProto: "http"}, + } { + t.Run(test.name, func(t *testing.T) { + t.Parallel() + httpServer := newHybridServer(t, pingServer{}) + request := newUpgradeRequest(t, httpServer.URL) + if test.scheme != "" { + request.Header.Set("Origin", test.scheme+"://"+request.URL.Host) + } + if test.forwardedProto != "" { + request.Header.Set("X-Forwarded-Proto", test.forwardedProto) + } + res, err := httpServer.Client().Do(request) + assert.Nil(t, err) + t.Cleanup(func() { _ = res.Body.Close() }) + assert.Equal(t, res.StatusCode, http.StatusSwitchingProtocols) + }) + } +} + +// WithCheckOrigin must still be able to open the endpoint up. +func TestWithCheckOriginCanAllowCrossOrigin(t *testing.T) { + t.Parallel() + server := connect.NewServer() + pingv1connect.RegisterPingServiceHandler(server, pingServer{}) + mux := http.NewServeMux() + connecthttp.Mount(mux, server, + connecthttp.WithWebSocketCheckOrigin(func(*http.Request) bool { return true }), + ) + httpServer := httptest.NewServer(mux) + t.Cleanup(httpServer.Close) + + request := newUpgradeRequest(t, httpServer.URL) + request.Header.Set("Origin", "https://evil.example.com") + res, err := httpServer.Client().Do(request) + assert.Nil(t, err) + t.Cleanup(func() { _ = res.Body.Close() }) + assert.Equal(t, res.StatusCode, http.StatusSwitchingProtocols) +} + +// newUpgradeRequest builds a handshake by hand so that a test can set headers +// the WebSocket client would not let it set. +func newUpgradeRequest(tb testing.TB, baseURL string) *http.Request { + tb.Helper() + request, err := http.NewRequestWithContext( + tb.Context(), + http.MethodGet, + baseURL+pingv1connect.PingServiceCumSumProcedure, + nil, + ) + assert.Nil(tb, err) + request.Header.Set("Connection", "Upgrade") + request.Header.Set("Upgrade", "websocket") + request.Header.Set("Sec-WebSocket-Version", "13") + request.Header.Set("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==") + request.Header.Set("Sec-WebSocket-Protocol", "connectrpc.1+proto") + return request +} diff --git a/internal/wstransport/protocol_websocket.go b/internal/wstransport/protocol_websocket.go new file mode 100644 index 00000000..d1b9fe93 --- /dev/null +++ b/internal/wstransport/protocol_websocket.go @@ -0,0 +1,212 @@ +// Copyright 2021-2026 The Connect Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package wstransport + +import ( + "bytes" + "context" + "errors" + "io" + "time" + "unicode/utf8" + + "connectrpc.com/connect/v2" + "github.com/coder/websocket" +) + +// Marker framing over WebSocket frames, for both directions. +// +// Each WebSocket frame carries exactly one message: a single marker byte +// naming its kind, then the payload. There is no length prefix — the frame is +// the boundary — and the frame type says how the payload is encoded, binary +// for Protobuf and text for JSON. +// +// Two markers are client-only, because WebSocket lacks two things HTTP +// provides: +// +// - C (End-Of-Client-Stream) stands in for request-body EOF, which a +// WebSocket cannot half-close. +// - M (Leading-Metadata) carries metadata as a JSON array of entries, each a +// key followed by its values, for browsers, whose WebSocket API cannot set +// headers on the upgrade. Every stream opens with exactly one, in either +// direction. +// +// The server answers with zero or more B messages and then one S message, +// whose payload is the EndStreamMessage JSON that Connect's HTTP streaming +// protocol also uses. + +const ( + // ProtocolConnectWebSocket identifies the WebSocket transport for the + // Connect protocol on the [connect.CallInfo].Protocol field. + ProtocolConnectWebSocket = "connect+ws" + + wsHeaderUpgrade = "Upgrade" + wsHeaderConnection = "Connection" + wsHeaderProtocol = "Sec-WebSocket-Protocol" + wsHeaderExtensions = "Sec-WebSocket-Extensions" + + wsQueryTimeoutMs = "connect-timeout-ms" + + // wsCloseWriteTimeout bounds the terminal write, which runs detached from + // the RPC's deadline so that an expired deadline can still be reported. + wsCloseWriteTimeout = 5 * time.Second +) + +// peerFault reports whether err says the peer sent something malformed or +// oversized, rather than reporting its own RPC failure. +// +// Only the read path produces these, so a handler's own error never reaches +// it: a service legitimately returning ResourceExhausted still gets a polite +// close. A remote error is the peer reporting its own failure, not malforming +// the stream. +func peerFault(err *connect.Error) bool { + if err == nil || err.IsRemote() { + return false + } + code := err.Code() + return code == connect.CodeResourceExhausted || code == connect.CodeInvalidArgument +} + +// closeReason truncates to the 123 bytes a WebSocket close frame allows: RFC +// 6455 caps a control payload at 125, and the status code takes two of them. An +// over-long reason is not truncated by the WebSocket library but rejected, so +// getting this wrong sends no close frame at all. +func closeReason(reason string) string { + const maxCloseReasonBytes = 123 + if len(reason) <= maxCloseReasonBytes { + return reason + } + truncated := reason[:maxCloseReasonBytes] + // A close reason must be valid UTF-8, so back off a cut that landed inside + // a multi-byte rune. At most three bytes go. + for len(truncated) > 0 && !utf8.ValidString(truncated) { + truncated = truncated[:len(truncated)-1] + } + return truncated +} + +// writeFrame sends one already-encoded message as a single WebSocket frame. +// +// The caller assembles marker and payload into one buffer rather than writing +// them separately, because the library decides whether to compress from the +// size of the *first* write: offering the marker alone would fall under any +// threshold and silently disable compression for every message. +func writeFrame( + ctx context.Context, + conn *websocket.Conn, + text bool, + data []byte, +) (int64, error) { + messageType := websocket.MessageBinary + if text { + messageType = websocket.MessageText + } + return int64(len(data)), conn.Write(ctx, messageType, data) +} + +// Helpers. + +// messageReadLimit turns a payload limit into a wire limit by allowing for the +// marker that precedes it, which §12 leaves out of the limit. +// +// The bound is per WebSocket message, not per frame: a message may be +// fragmented across continuation frames, and both this package's reader and +// coder's SetReadLimit count the reassembled whole. A per-frame bound would be +// defeated by fragmenting. +// +// Zero is never passed through: coder's default is 32KiB, and a zero would cap +// messages at a single byte. Unlimited is -1. +func messageReadLimit(readMaxBytes int) int64 { + if readMaxBytes <= 0 { + return -1 + } + return int64(readMaxBytes) + 1 +} + +// errMessageTooBig reports a message that overran the limit this side +// enforces. The reader knows the wire limit; only the caller knows the +// configured one worth naming, so the sentinel carries no number. +var errMessageTooBig = errors.New("message exceeds read limit") + +// readBoundedMessage reads one WebSocket message, abandoning it as soon as it +// passes limit rather than consuming it. Stopping early is what leaves the +// connection usable enough to tell the peer why it was rejected; coder's own +// SetReadLimit closes with 1009 before this layer can say anything. +// +// The reader spans continuation frames, so the bound is on the reassembled +// message and fragmenting does not evade it. A limit below zero means +// unlimited. +func readBoundedMessage( + ctx context.Context, + conn *websocket.Conn, + limit int64, + wire *drainLimiter, +) (websocket.MessageType, []byte, error) { + messageType, reader, err := conn.Reader(ctx) + if err != nil { + return 0, nil, err + } + if limit < 0 { + data, err := io.ReadAll(reader) + return messageType, data, err + } + // §12: the compressed bytes are bounded too. Counting starts once the + // message has begun, so the control frames of an idle connection do not + // count against the next message. + wire.beginMessage(limit) + defer wire.endMessage() + // One byte past the limit is all it takes to know the message overran, and + // reading more is what the limit exists to prevent. + var message bytes.Buffer + switch _, err := io.CopyN(&message, reader, limit+1); { + case err == nil: + return messageType, nil, errMessageTooBig + case errors.Is(err, io.EOF): + return messageType, message.Bytes(), nil + case errors.Is(err, errWireLimit): + return messageType, nil, errMessageTooBig + default: + return messageType, nil, err + } +} + +// peerRejectedAsTooBig recognizes a peer that closed the connection because a +// message from this side blew its read limit. The peer's limit is its own +// business, so the close reason is the only account of it there is. +func peerRejectedAsTooBig(err error) *connect.Error { + if websocket.CloseStatus(err) == websocket.StatusMessageTooBig { + return errorf(connect.CodeResourceExhausted, "peer rejected message as too big: %w", err) + } + return nil +} + +// exceedsReadLimit reports a message abandoned before its size was known, so +// it names the configured limit rather than a size it never measured. The +// limit on the wire carries a marker margin that no caller configured. +func exceedsReadLimit(readMaxBytes int) *connect.Error { + return errorf( + connect.CodeResourceExhausted, + "message exceeds the configured max of %d bytes", readMaxBytes, + ) +} + +// wsContextError maps a done context's error to the matching Connect code, +// preserving the original error via %w. +func wsContextError(ctxErr error) *connect.Error { + if errors.Is(ctxErr, context.Canceled) { + return errorf(connect.CodeCanceled, "%w", ctxErr) + } + return errorf(connect.CodeDeadlineExceeded, "%w", ctxErr) +} diff --git a/internal/wstransport/release_test.go b/internal/wstransport/release_test.go new file mode 100644 index 00000000..66519820 --- /dev/null +++ b/internal/wstransport/release_test.go @@ -0,0 +1,133 @@ +// Copyright 2021-2026 The Connect Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package wstransport + +import ( + "context" + "errors" + "io" + "net/http" + "net/http/httptest" + "testing" + "time" + + "connectrpc.com/connect/v2" + "connectrpc.com/connect/v2/internal/assert" + pingv1 "connectrpc.com/connect/v2/internal/gen/connect/ping/v1" + "connectrpc.com/connect/v2/internal/gen/connect/ping/v1/pingv1connect" +) + +type countUpServer struct { + pingv1connect.UnimplementedPingServiceHandler +} + +func (countUpServer) CountUp( + _ context.Context, + request *pingv1.CountUpRequest, + stream pingv1connect.PingServiceCountUpServerStream, +) error { + for number := range request.Number { + if err := stream.Send(&pingv1.CountUpResponse{Number: number + 1}); err != nil { + return err + } + } + return nil +} + +// The ClientStream contract says reading to io.EOF releases the stream's +// resources, and generated server-streaming code relies on it: it never calls +// Close. The reader and keep-alive goroutines must end without one, even under +// a context that is never canceled. +func TestReadingToEndOfStreamReleasesGoroutines(t *testing.T) { + t.Parallel() + server := connect.NewServer() + pingv1connect.RegisterPingServiceHandler(server, countUpServer{}) + mux := http.NewServeMux() + mux.Handle( + pingv1connect.PingServiceCountUpProcedure, + Upgrade(server, http.NotFoundHandler()), + ) + httpServer := httptest.NewServer(mux) + t.Cleanup(httpServer.Close) + + transport, err := NewTransport( + httpServer.URL, + WithHTTPClient(httpServer.Client()), + WithKeepAlive(time.Hour), + ) + assert.Nil(t, err) + spec := connect.Spec{ + Procedure: pingv1connect.PingServiceCountUpProcedure, + StreamType: connect.StreamTypeServer, + } + connectStream, err := transport.NewClientStream(context.Background(), spec) + assert.Nil(t, err) + assert.Nil(t, connectStream.Send(&pingv1.CountUpRequest{Number: 3})) + assert.Nil(t, connectStream.CloseSend()) + for { + receiveErr := connectStream.Receive(&pingv1.CountUpResponse{}) + if receiveErr != nil { + assert.True(t, errors.Is(receiveErr, io.EOF)) + break + } + } + + stream, ok := connectStream.(*clientStream) + assert.True(t, ok) + call := stream.conn.call + assert.NotNil(t, call.keeper) + for name, done := range map[string]chan struct{}{ + "reader": call.reader.done, + "keep-alive": call.keeper.done, + } { + select { + case <-done: + case <-time.After(wsTestReadTimeout): + t.Fatalf("%s goroutine still running after the stream was read to io.EOF", name) + } + } +} + +// Close publishes the response metadata while Receive may still be merging it, +// which the ClientStream contract allows. Run under -race, which is how make +// shorttest runs it; the two goroutines share no other synchronization. +func TestResponseMetadataIsSafeDuringReceive(t *testing.T) { + t.Parallel() + call := &wsClientCall{} + call.preventDial() + conn := &websocketClientConn{ + ctx: t.Context(), + call: call, + trailer: http.Header{"Trail": {"value"}}, + responseHeader: make(http.Header), + responseTrailer: make(http.Header), + } + receiveDone := make(chan struct{}) + go func() { + defer close(receiveDone) + assert.Nil(t, conn.mergeLeadingMetadata([]byte(`[["lead","value"]]`))) + conn.endStreamSeen.Store(true) + _ = conn.Receive(nil) + }() + for key := range conn.ResponseHeader() { + _ = key + } + for key := range conn.ResponseTrailer() { + _ = key + } + <-receiveDone + assert.Equal(t, conn.ResponseHeader().Get("Lead"), "value") + assert.Equal(t, conn.ResponseTrailer().Get("Trail"), "value") +} diff --git a/internal/wstransport/requestmetadata_ext_test.go b/internal/wstransport/requestmetadata_ext_test.go new file mode 100644 index 00000000..34f37fcf --- /dev/null +++ b/internal/wstransport/requestmetadata_ext_test.go @@ -0,0 +1,360 @@ +// Copyright 2021-2026 The Connect Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package wstransport_test + +import ( + "context" + "encoding/json" + "errors" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "connectrpc.com/connect/v2" + "connectrpc.com/connect/v2/connecthttp" + "connectrpc.com/connect/v2/internal/assert" + pingv1 "connectrpc.com/connect/v2/internal/gen/connect/ping/v1" + "connectrpc.com/connect/v2/internal/gen/connect/ping/v1/pingv1connect" + "github.com/coder/websocket" + "google.golang.org/protobuf/proto" +) + +// observationServer reports the same header twice: once before it has received +// anything, once after. The pair is the whole point — a difference between them +// is a write to CallInfo that happened after the handler was already running. +type observationServer struct { + pingv1connect.UnimplementedPingServiceHandler + + observations chan string +} + +func (s observationServer) CumSum( + ctx context.Context, + stream pingv1connect.PingServiceCumSumServerStream, +) error { + info, _ := connect.CallInfoForServerContext(ctx) + s.observations <- info.RequestHeader().Get("Acme-Tenant") + for { + request, err := stream.Receive() + if errors.Is(err, io.EOF) { + return nil + } + if err != nil { + return err + } + s.observations <- info.RequestHeader().Get("Acme-Tenant") + if err := stream.Send(&pingv1.CumSumResponse{Sum: request.Number}); err != nil { + return err + } + } +} + +func newObservationServer(tb testing.TB, observations chan string) *httptest.Server { + tb.Helper() + server := connect.NewServer() + pingv1connect.RegisterPingServiceHandler(server, observationServer{observations: observations}) + mux := http.NewServeMux() + connecthttp.Mount(mux, server) + httpServer := httptest.NewServer(mux) + tb.Cleanup(httpServer.Close) + return httpServer +} + +// Leading-Metadata is drained before the handler is dispatched, so CallInfo is +// complete on the handler's very first line and never changes afterwards. +// +// That ordering is what interceptors depend on — an auth interceptor runs +// before the handler and must see the client's credentials — and it is what +// makes the header map safe to read from a second goroutine, since nothing +// writes it once the handler exists. +func TestLeadingMetadataIsCompleteBeforeTheHandlerStarts(t *testing.T) { + t.Parallel() + observations := make(chan string, 2) + httpServer := newObservationServer(t, observations) + + metadata, err := json.Marshal([][]string{{"acme-tenant", "tenant-42"}}) + assert.Nil(t, err) + client := dialBrowserClientOpening( + t, httpServer, pingv1connect.PingServiceCumSumProcedure, metadata) + payload, err := proto.Marshal(&pingv1.CumSumRequest{Number: 1}) + assert.Nil(t, err) + client.writeProto(t, payload) + client.readMessage(t) + + timeout := time.After(5 * time.Second) + read := func(what string) string { + t.Helper() + select { + case observed := <-observations: + return observed + case <-timeout: + t.Fatalf("handler never reported %s", what) + return "" + } + } + + // Present before the handler receives anything: the session drained the + // message while building the call. + assert.Equal(t, read("its first observation"), "tenant-42") + // And unchanged across a Receive, because nothing writes it any more. + assert.Equal(t, read("its second observation"), "tenant-42") +} + +// racingServer is the ordinary bidi shape: one goroutine receives while another +// reads request metadata. Before the opening message was drained ahead of +// dispatch, that pair raced — Receive merged metadata into the same CallInfo +// map the other goroutine was reading. +type racingServer struct { + pingv1connect.UnimplementedPingServiceHandler +} + +func (racingServer) CumSum( + ctx context.Context, + stream pingv1connect.PingServiceCumSumServerStream, +) error { + info, _ := connect.CallInfoForServerContext(ctx) + done := make(chan struct{}) + go func() { + defer close(done) + for range 100_000 { + _ = info.RequestHeader().Get("Acme-Tenant") + } + }() + defer func() { <-done }() + for { + request, err := stream.Receive() + if errors.Is(err, io.EOF) { + return nil + } + if err != nil { + return err + } + // Echo, so the test has a synchronization point and does not finish + // before the reading goroutine has had a chance to race anything. + if err := stream.Send(&pingv1.CumSumResponse{Sum: request.Number}); err != nil { + return err + } + } +} + +// Reading request metadata from one goroutine while another receives must be +// safe. It is only safe because nothing writes CallInfo once the handler +// exists: the opening message is consumed before dispatch, and a second one +// is a protocol error. Run under -race, where this fails if either half of +// that regresses. +func TestRequestMetadataIsSafeForConcurrentReaders(t *testing.T) { + t.Parallel() + server := connect.NewServer() + pingv1connect.RegisterPingServiceHandler(server, racingServer{}) + mux := http.NewServeMux() + connecthttp.Mount(mux, server) + httpServer := httptest.NewServer(mux) + t.Cleanup(httpServer.Close) + + metadata, err := json.Marshal([][]string{{"acme-tenant", "tenant-42"}}) + assert.Nil(t, err) + client := dialBrowserClientOpening( + t, httpServer, pingv1connect.PingServiceCumSumProcedure, metadata) + payload, err := proto.Marshal(&pingv1.CumSumRequest{Number: 1}) + assert.Nil(t, err) + client.writeProto(t, payload) + client.readMessage(t) + client.writeJSON(t, wireClientEndStream, nil) +} + +// A stream carries exactly one M message, and it must be the +// first message: the server consumes it before dispatching, so anything else +// arriving first means the peer is not speaking this protocol. +func TestStreamMustOpenWithLeadingMetadata(t *testing.T) { + t.Parallel() + server := connect.NewServer() + pingv1connect.RegisterPingServiceHandler(server, observationServer{ + observations: make(chan string, 4), + }) + mux := http.NewServeMux() + connecthttp.Mount(mux, server) + httpServer := httptest.NewServer(mux) + t.Cleanup(httpServer.Close) + + // A body message where the opening metadata belongs. + conn := dialRaw(t, httpServer, pingv1connect.PingServiceCumSumProcedure) + sendProtoBody(t, conn, &pingv1.CumSumRequest{Number: 1}) + + data := readServerOpening(t, conn) + assert.Equal(t, data[0], wireServerEndStream) // S carries the verdict + assert.True(t, strings.Contains(string(data), "internal")) + assert.True(t, strings.Contains(string(data), "first message must be M")) +} + +// dialRaw opens a connection without sending the opening message, so a test +// can put something else first. +func dialRaw(tb testing.TB, server *httptest.Server, procedure string) *websocket.Conn { + tb.Helper() + conn, response, err := websocket.Dial( + tb.Context(), + "ws"+strings.TrimPrefix(server.URL, "http")+procedure, + &websocket.DialOptions{ + HTTPClient: server.Client(), + Subprotocols: []string{"connectrpc.1+proto"}, + }, + ) + if response != nil && response.Body != nil { + _ = response.Body.Close() + } + assert.Nil(tb, err) + tb.Cleanup(func() { _ = conn.CloseNow() }) + return conn +} + +// An ordinary key from an M message replaces what the handshake carried. The +// result is the effective headers: what the handler and its interceptors see. +// +// Protecting what the connection established is the reserved list's job, not +// this rule's — see TestReservedHeadersEndTheRPC. +func TestLeadingMetadataReplacesHandshakeHeaders(t *testing.T) { + t.Parallel() + observations := make(chan string, 4) + httpServer := newObservationServer(t, observations) + + url := "ws" + strings.TrimPrefix(httpServer.URL, "http") + + pingv1connect.PingServiceCumSumProcedure + conn, response, err := websocket.Dial(t.Context(), url, &websocket.DialOptions{ + HTTPClient: httpServer.Client(), + Subprotocols: []string{"connectrpc.1+proto"}, + HTTPHeader: http.Header{"Acme-Tenant": []string{"from-the-handshake"}}, + }) + if response != nil && response.Body != nil { + _ = response.Body.Close() + } + assert.Nil(t, err) + t.Cleanup(func() { _ = conn.CloseNow() }) + + sendJSONMessage(t, conn, wireMetadata, []byte(`[["acme-tenant","from-the-message"]]`)) + sendProtoBody(t, conn, &pingv1.CumSumRequest{Number: 1}) + + assert.Equal(t, <-observations, "from-the-message") + readCtx, cancelRead := readContext(t) + defer cancelRead() + _, _, err = conn.Read(readCtx) + assert.Nil(t, err) + assert.Equal(t, <-observations, "from-the-message") +} + +// A reserved name ends the RPC rather than being dropped. Dropping it would +// leave the client believing it had set something the server does not have — +// and for an identity header, believing it while the server authorizes on a +// different value. +func TestReservedHeadersEndTheRPC(t *testing.T) { + t.Parallel() + for _, test := range []struct { + name string + key string + reason string + }{ + {name: "Fetch forbids it", key: "cookie", reason: "Fetch standard"}, + {name: "Fetch forbids the prefix", key: "sec-websocket-key", reason: "Fetch standard"}, + {name: "proxy- prefix", key: "proxy-authorization", reason: "Fetch standard"}, + {name: "method override", key: "x-http-method-override", reason: "Fetch standard"}, + {name: "this protocol controls it", key: "connect-protocol-version", reason: "controlled by this protocol"}, + {name: "the deadline has its own channel", key: "connect-timeout-ms", reason: "controlled by this protocol"}, + {name: "the frame type says the encoding", key: "content-type", reason: "controlled by this protocol"}, + {name: "content encoding", key: "content-encoding", reason: "controlled by this protocol"}, + {name: "connect content encoding", key: "connect-content-encoding", reason: "controlled by this protocol"}, + {name: "connect accept encoding", key: "connect-accept-encoding", reason: "controlled by this protocol"}, + // Matching is case-insensitive, so casing is not a way past the list. + {name: "mixed case is the same name", key: "Connect-Timeout-Ms", reason: "controlled by this protocol"}, + {name: "infrastructure sets it", key: "x-forwarded-for", reason: "infrastructure deny list"}, + {name: "any connect- name", key: "connect-anything", reason: "controlled by this protocol"}, + {name: "infrastructure, exact name", key: "x-real-ip", reason: "infrastructure deny list"}, + } { + t.Run(test.name, func(t *testing.T) { + t.Parallel() + httpServer := newHybridServer(t, pingServer{}) + conn := dialRaw(t, httpServer, pingv1connect.PingServiceCumSumProcedure) + sendJSONMessage(t, conn, wireMetadata, + []byte(`[["`+test.key+`","forged"]]`)) + + data := readServerOpening(t, conn) + assert.Equal(t, data[0], wireServerEndStream) + assert.True(t, strings.Contains(string(data), "internal")) + // The key as the client spelled it, not an internal form of it. + assert.True(t, strings.Contains(string(data), test.key)) + assert.True(t, strings.Contains(string(data), test.reason)) + }) + } +} + +// §7.1: a non-browser client can put Connect- headers on the handshake, where +// no Leading-Metadata check reaches them. This binding carries their +// information elsewhere, so the server drops every one of them rather than +// letting it masquerade as application metadata. +func TestProtocolHandshakeHeadersAreStripped(t *testing.T) { + t.Parallel() + for _, key := range []string{"Connect-Protocol-Version", "Connect-Timeout-Ms", "Connect-Anything"} { + t.Run(key, func(t *testing.T) { + t.Parallel() + seen := make(chan http.Header, 1) + httpServer := newMetadataServer(t, seen) + url := "ws" + strings.TrimPrefix(httpServer.URL, "http") + + pingv1connect.PingServiceCumSumProcedure + conn, response, err := websocket.Dial(t.Context(), url, &websocket.DialOptions{ + HTTPClient: httpServer.Client(), + Subprotocols: []string{"connectrpc.1+proto"}, + HTTPHeader: map[string][]string{key: {"9000"}}, + }) + if response != nil && response.Body != nil { + _ = response.Body.Close() + } + assert.Nil(t, err) + t.Cleanup(func() { _ = conn.CloseNow() }) + sendJSONMessage(t, conn, wireMetadata, []byte("[]")) + sendProtoBody(t, conn, &pingv1.CumSumRequest{Number: 1}) + + header := <-seen + assert.Equal(t, header.Get(key), "") + // §7.1: the headers that establish the WebSocket are not + // metadata either. + for _, handshakeKey := range []string{"Connection", "Upgrade", "Sec-WebSocket-Version", "Sec-WebSocket-Key"} { + assert.Equal(t, header.Get(handshakeKey), "") + } + }) + } +} + +// The deny list is the deployment's to set, because which names its own +// infrastructure controls is a property of that deployment. +func TestInfrastructureHeadersAreConfigurable(t *testing.T) { + t.Parallel() + observations := make(chan string, 4) + server := connect.NewServer() + pingv1connect.RegisterPingServiceHandler(server, observationServer{observations: observations}) + mux := http.NewServeMux() + // X-Forwarded-For is no longer reserved here; Acme-Tenant now is. + connecthttp.Mount(mux, server, + connecthttp.WithWebSocketInfrastructureHeaders("Acme-*"), + ) + httpServer := httptest.NewServer(mux) + t.Cleanup(httpServer.Close) + + conn := dialRaw(t, httpServer, pingv1connect.PingServiceCumSumProcedure) + sendJSONMessage(t, conn, wireMetadata, []byte(`[["acme-tenant","forged"]]`)) + + data := readServerOpening(t, conn) + assert.Equal(t, data[0], wireServerEndStream) + assert.True(t, strings.Contains(string(data), "infrastructure deny list")) +} diff --git a/internal/wstransport/reserved.go b/internal/wstransport/reserved.go new file mode 100644 index 00000000..750870d7 --- /dev/null +++ b/internal/wstransport/reserved.go @@ -0,0 +1,129 @@ +// Copyright 2021-2026 The Connect Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package wstransport + +import "strings" + +// Reserved request-header names: the keys a client may not set from a +// Leading-Metadata message. A Leading-Metadata key otherwise replaces the +// upgrade request's value for that key, so this list is what keeps a peer from +// rewriting what the connection itself established. + +// isFetchForbidden reports whether a lower-cased name is a forbidden +// request-header under the Fetch standard. +// +// The three method-override names are conditional there — forbidden only when +// the value names a forbidden method — and unconditional here, because the +// method they would override has no meaning on this transport. +func isFetchForbidden(lower string) bool { + switch lower { + case "accept-charset", + "accept-encoding", + "access-control-request-headers", + "access-control-request-method", + "connection", + "content-length", + "cookie", + "cookie2", + "date", + "dnt", + "expect", + "host", + "keep-alive", + "origin", + "referer", + "set-cookie", + "te", + "trailer", + "transfer-encoding", + "upgrade", + "via", + "x-http-method", + "x-http-method-override", + "x-method-override": + return true + } + return strings.HasPrefix(lower, "proxy-") || strings.HasPrefix(lower, "sec-") +} + +// isProtocolControlled reports whether this binding owns the name itself: +// every connect- name (§7.3.2), and the two encoding names. The sec- prefix +// above already covers the WebSocket handshake's own headers. +// +// The encoding names are here because the frame type and the subprotocol carry +// that decision; a client resetting them would describe a body it is not +// sending. +func isProtocolControlled(lower string) bool { + switch lower { + case "content-type", "content-encoding": + return true + } + return isConnectReserved(lower) +} + +// isConnectReserved reports whether a lower-cased name is in the connect- +// namespace, which Connect reserves for itself. A server never sends one in +// an M or S message either (§7.3.2, §9). +func isConnectReserved(lower string) bool { + return strings.HasPrefix(lower, "connect-") +} + +// isStrippedHandshakeHeader reports whether a handshake header is kept out of +// the effective headers (§7.1): the ones that establish the WebSocket itself, +// and every Connect- header, whose information this binding carries elsewhere +// — the version in the subprotocol, the deadline in the query string. +func isStrippedHandshakeHeader(key string) bool { + lower := strings.ToLower(key) + switch lower { + case "connection", "upgrade": + return true + } + return strings.HasPrefix(lower, "sec-websocket-") || isConnectReserved(lower) +} + +// defaultInfrastructureHeaders is what a proxy in front of the server sets and +// a client must not be able to forge. A deployment replaces this list with +// WithInfrastructureHeaders, because which names its own infrastructure +// controls is a property of that deployment. +func defaultInfrastructureHeaders() []string { + return []string{"Forwarded", "X-Forwarded-*", "X-Real-IP"} +} + +// reservedHeaderReason names why a key may not appear in a Leading-Metadata +// message, or returns false if it may. +func reservedHeaderReason(key string, infrastructure []string) (string, bool) { + lower := strings.ToLower(key) + if isFetchForbidden(lower) { + return "forbidden as a request header by the Fetch standard", true + } + if isProtocolControlled(lower) { + return "controlled by this protocol", true + } + for _, pattern := range infrastructure { + if matchHeaderPattern(lower, strings.ToLower(pattern)) { + return "on this server's infrastructure deny list", true + } + } + return "", false +} + +// matchHeaderPattern matches a lower-cased name against a lower-cased pattern, +// where a trailing * matches any suffix. Both are already lower-cased. +func matchHeaderPattern(name, pattern string) bool { + if prefix, found := strings.CutSuffix(pattern, "*"); found { + return strings.HasPrefix(name, prefix) + } + return name == pattern +} diff --git a/internal/wstransport/reservedresponse_ext_test.go b/internal/wstransport/reservedresponse_ext_test.go new file mode 100644 index 00000000..2d415a4b --- /dev/null +++ b/internal/wstransport/reservedresponse_ext_test.go @@ -0,0 +1,68 @@ +// Copyright 2021-2026 The Connect Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package wstransport_test + +import ( + "context" + "strings" + "testing" + + "connectrpc.com/connect/v2" + "connectrpc.com/connect/v2/internal/assert" + pingv1 "connectrpc.com/connect/v2/internal/gen/connect/ping/v1" + "connectrpc.com/connect/v2/internal/gen/connect/ping/v1/pingv1connect" + "google.golang.org/protobuf/proto" +) + +// connectKeyServer sets a connect- key alongside an ordinary one in both its +// headers and its trailers. +type connectKeyServer struct { + pingv1connect.UnimplementedPingServiceHandler +} + +func (connectKeyServer) Ping(ctx context.Context, request *pingv1.PingRequest) (*pingv1.PingResponse, error) { + if info, ok := connect.CallInfoForServerContext(ctx); ok { + info.ResponseHeader().Set("acme-header", "kept") + info.ResponseHeader().Set("connect-sneaky-header", "dropped") + info.ResponseTrailer().Set("acme-trailer", "kept") + info.ResponseTrailer().Set("connect-sneaky-trailer", "dropped") + } + return &pingv1.PingResponse{Number: request.Number}, nil +} + +// §7.3.2: connect- names belong to the protocol, so a server leaves any its +// handler set out of M and out of the trailers in S. +func TestServerOmitsConnectKeysFromResponseMetadata(t *testing.T) { + t.Parallel() + httpServer := newServerFor(t, connectKeyServer{}) + client := dialBrowserClient(t, httpServer, pingv1connect.PingServicePingProcedure) + payload, err := proto.Marshal(&pingv1.PingRequest{Number: 7}) + assert.Nil(t, err) + client.writeProto(t, payload) + client.writeJSON(t, wireClientEndStream, nil) + + marker, metadata, _ := client.readMessage(t) + assert.Equal(t, marker, wireMetadata) + assert.True(t, strings.Contains(string(metadata), "acme-header")) + assert.False(t, strings.Contains(string(metadata), "connect-")) + + marker, _, _ = client.readMessage(t) + assert.Equal(t, marker, wireBody) + + marker, endStream, _ := client.readMessage(t) + assert.Equal(t, marker, wireServerEndStream) + assert.True(t, strings.Contains(string(endStream), "acme-trailer")) + assert.False(t, strings.Contains(string(endStream), "connect-")) +} diff --git a/internal/wstransport/responsecount_ext_test.go b/internal/wstransport/responsecount_ext_test.go new file mode 100644 index 00000000..19a04019 --- /dev/null +++ b/internal/wstransport/responsecount_ext_test.go @@ -0,0 +1,125 @@ +// Copyright 2021-2026 The Connect Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package wstransport_test + +import ( + "context" + "errors" + "io" + "net" + "strings" + "testing" + "time" + + "connectrpc.com/connect/v2" + "connectrpc.com/connect/v2/internal/assert" + pingv1 "connectrpc.com/connect/v2/internal/gen/connect/ping/v1" + "connectrpc.com/connect/v2/internal/gen/connect/ping/v1/pingv1connect" + "connectrpc.com/connect/v2/internal/wstransport" + "google.golang.org/protobuf/proto" +) + +// serverFrame is one unmasked, unfragmented server frame. It covers payloads +// under 126 bytes, which is all these scripts send. +func serverFrame(text bool, data []byte) []byte { + opcode := byte(0x82) + if text { + opcode = 0x81 + } + return append([]byte{opcode, byte(len(data))}, data...) +} + +// scriptedResponseServer completes one handshake by hand and writes frames, +// then waits for the client to close. It returns the base URL. +func scriptedResponseServer(tb testing.TB, frames ...[]byte) string { + tb.Helper() + listener, err := (&net.ListenConfig{}).Listen(tb.Context(), "tcp", "127.0.0.1:0") + assert.Nil(tb, err) + tb.Cleanup(func() { _ = listener.Close() }) + go func() { + conn, reader := acceptRawUpgrade(tb, listener) + for _, frame := range frames { + if _, err := conn.Write(frame); err != nil { + return + } + } + _, _, _ = watchFrames(reader, nil) + }() + return "http://" + listener.Addr().String() +} + +// §6.2: a unary call returns exactly one message. A server that ends it with +// none, or sends two, has broken the RPC's cardinality, and the client reports +// unimplemented, as Connect over HTTP does. +func TestUnaryResponseCountIsEnforced(t *testing.T) { + t.Parallel() + body, err := proto.Marshal(&pingv1.PingResponse{Number: 1}) + assert.Nil(t, err) + bodyFrame := serverFrame(false, append([]byte{wireBody}, body...)) + opening := serverFrame(true, []byte("M[]")) + end := serverFrame(true, []byte("S{}")) + for _, test := range []struct { + name string + frames [][]byte + want string + }{ + {name: "zero messages", frames: [][]byte{opening, end}, want: "zero messages"}, + {name: "two messages", frames: [][]byte{opening, bodyFrame, bodyFrame, end}, want: "multiple messages"}, + } { + t.Run(test.name, func(t *testing.T) { + t.Parallel() + transport, err := wstransport.NewTransport(scriptedResponseServer(t, test.frames...)) + assert.Nil(t, err) + client := pingv1connect.NewPingServiceClient(connect.NewClient(transport)) + ctx, cancel := context.WithTimeout(t.Context(), 10*time.Second) + defer cancel() + _, err = client.Ping(ctx, &pingv1.PingRequest{Number: 1}) + if !assert.NotNil(t, err) { + return + } + assert.Equal(t, connect.CodeOf(err), connect.CodeUnimplemented) + assert.True(t, strings.Contains(err.Error(), test.want)) + }) + } +} + +// §13: a 1007 close is one of the two a client may take an outcome from. The +// server failed the connection over this client's text, so the RPC is +// Internal rather than the Unavailable of a connection that simply dropped. +func TestInvalidUTF8CloseFromServerIsInternal(t *testing.T) { + t.Parallel() + reason := "text message is not valid UTF-8" + closeFrame := append([]byte{0x88, byte(2 + len(reason)), 0x03, 0xEF}, reason...) + url := scriptedResponseServer(t, serverFrame(true, []byte("M[]")), closeFrame) + transport, err := wstransport.NewTransport(url) + assert.Nil(t, err) + client := pingv1connect.NewPingServiceClient(connect.NewClient(transport)) + ctx, cancel := context.WithTimeout(t.Context(), 10*time.Second) + defer cancel() + stream, err := client.CumSum(ctx) + assert.Nil(t, err) + // The server closes at once, so the write may find the connection gone. + // As over HTTP, that reads as io.EOF and the verdict comes from Receive. + if sendErr := stream.Send(&pingv1.CumSumRequest{Number: 1}); sendErr != nil { + assert.True(t, errors.Is(sendErr, io.EOF)) + } + _, err = stream.Receive() + if !assert.NotNil(t, err) { + return + } + assert.Equal(t, connect.CodeOf(err), connect.CodeInternal) + assert.True(t, strings.Contains(err.Error(), "invalid UTF-8")) + _ = stream.Close() +} diff --git a/internal/wstransport/responseheader_test.go b/internal/wstransport/responseheader_test.go new file mode 100644 index 00000000..0ae8cbc3 --- /dev/null +++ b/internal/wstransport/responseheader_test.go @@ -0,0 +1,80 @@ +// Copyright 2021-2026 The Connect Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package wstransport + +import ( + "context" + "net" + "testing" + "time" + + "connectrpc.com/connect/v2" + "connectrpc.com/connect/v2/internal/assert" + "connectrpc.com/connect/v2/internal/gen/connect/ping/v1/pingv1connect" +) + +// ResponseHeader dials a stream that has not dialed yet. The metadata lock it +// shares with Receive and ResponseTrailer must not be held for the handshake. +func TestResponseHeaderDoesNotLockDuringHandshake(t *testing.T) { + t.Parallel() + listener, err := (&net.ListenConfig{}).Listen(t.Context(), "tcp", "127.0.0.1:0") + assert.Nil(t, err) + t.Cleanup(func() { _ = listener.Close() }) + accepted := make(chan net.Conn, 1) + go func() { + // Accepts the connection and never answers the upgrade. + if conn, err := listener.Accept(); err == nil { + accepted <- conn + } + }() + + transport, err := NewTransport("http://" + listener.Addr().String()) + assert.Nil(t, err) + ctx, cancel := context.WithTimeout(t.Context(), 10*time.Second) + defer cancel() + stream, err := transport.NewClientStream(ctx, connect.Spec{ + Procedure: pingv1connect.PingServiceCumSumProcedure, + StreamType: connect.StreamTypeBidi, + }) + assert.Nil(t, err) + wsStream, ok := stream.(*clientStream) + assert.True(t, ok) + conn := wsStream.conn + headerDone := make(chan struct{}) + go func() { + defer close(headerDone) + _ = conn.ResponseHeader() + }() + select { + case serverConn := <-accepted: + t.Cleanup(func() { _ = serverConn.Close() }) + case <-time.After(5 * time.Second): + t.Fatal("client never dialed") + } + + trailerDone := make(chan struct{}) + go func() { + defer close(trailerDone) + _ = conn.ResponseTrailer() + }() + select { + case <-trailerDone: + case <-time.After(time.Second): + t.Error("ResponseTrailer waited for the handshake") + } + cancel() + <-headerDone + <-trailerDone +} diff --git a/internal/wstransport/selector_ext_test.go b/internal/wstransport/selector_ext_test.go new file mode 100644 index 00000000..5d245655 --- /dev/null +++ b/internal/wstransport/selector_ext_test.go @@ -0,0 +1,168 @@ +// Copyright 2021-2026 The Connect Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package wstransport_test + +import ( + "context" + "errors" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "connectrpc.com/connect/v2" + "connectrpc.com/connect/v2/connecthttp" + "connectrpc.com/connect/v2/internal/assert" + pingv1 "connectrpc.com/connect/v2/internal/gen/connect/ping/v1" + "connectrpc.com/connect/v2/internal/gen/connect/ping/v1/pingv1connect" + "connectrpc.com/connect/v2/internal/wstransport" +) + +// countUpServer answers the server-streaming procedure, which is the one that +// works over either transport: bidi needs HTTP/2, but a server stream is +// ordinary chunked HTTP. +type countUpServer struct { + pingv1connect.UnimplementedPingServiceHandler +} + +func (countUpServer) Ping(_ context.Context, req *pingv1.PingRequest) (*pingv1.PingResponse, error) { + return &pingv1.PingResponse{Number: req.Number}, nil +} + +func (countUpServer) CountUp( + _ context.Context, + req *pingv1.CountUpRequest, + stream pingv1connect.PingServiceCountUpServerStream, +) error { + for i := int64(1); i <= req.Number; i++ { + if err := stream.Send(&pingv1.CountUpResponse{Number: i}); err != nil { + return err + } + } + return nil +} + +func (countUpServer) CumSum(_ context.Context, stream pingv1connect.PingServiceCumSumServerStream) error { + var total int64 + for { + req, err := stream.Receive() + if errors.Is(err, io.EOF) { + return nil + } + if err != nil { + return err + } + total += req.Number + if err := stream.Send(&pingv1.CumSumResponse{Sum: total}); err != nil { + return err + } + } +} + +// newSelectorServer mounts one server for every selector test: both transports +// on every path, so the client is free to choose. +func newSelectorServer(tb testing.TB) *httptest.Server { + tb.Helper() + server := connect.NewServer() + pingv1connect.RegisterPingServiceHandler(server, countUpServer{}) + mux := http.NewServeMux() + connecthttp.Mount(mux, server) + httpServer := httptest.NewServer(mux) + tb.Cleanup(httpServer.Close) + return httpServer +} + +// The selector is the client's alone, and the same server answers whichever +// way it chooses. Each case runs a unary call and a server stream against one +// server and records the protocol that actually carried them. +func TestSelectorChoosesTheWirePerRPC(t *testing.T) { + t.Parallel() + const websocketProtocol = wstransport.ProtocolConnectWebSocket + httpProtocol := connect.ProtocolNameConnect + + for _, test := range []struct { + name string + selector connecthttp.Selector + wantUnary string + wantStreaming string + }{ + { + name: "default routes streaming to WebSocket", + wantUnary: httpProtocol, + wantStreaming: websocketProtocol, + }, + { + name: "SelectAll routes everything to WebSocket", + selector: connecthttp.SelectAll, + wantUnary: websocketProtocol, + wantStreaming: websocketProtocol, + }, + { + name: "SelectBidi leaves server streams on HTTP", + // Only full-duplex RPCs need the upgrade; a server stream is + // ordinary chunked HTTP and works without it. + selector: connecthttp.SelectBidi, + wantUnary: httpProtocol, + wantStreaming: httpProtocol, + }, + { + name: "a custom selector routes one procedure", + selector: func(spec connect.Spec) bool { + return strings.HasSuffix(spec.Procedure, "/CountUp") + }, + wantUnary: httpProtocol, + wantStreaming: websocketProtocol, + }, + } { + t.Run(test.name, func(t *testing.T) { + t.Parallel() + httpServer := newSelectorServer(t) + selector := test.selector + if selector == nil { + selector = connecthttp.SelectStreaming + } + transport := connecthttp.NewTransport( + httpServer.Client(), + httpServer.URL, + connecthttp.WithWebSocket(selector), + ) + + var protocol string + client := pingv1connect.NewPingServiceClient( + connect.NewClient(transport, recordProtocol(&protocol)), + ) + + response, err := client.Ping(t.Context(), &pingv1.PingRequest{Number: 7}) + assert.Nil(t, err) + assert.Equal(t, response.Number, int64(7)) + assert.Equal(t, protocol, test.wantUnary) + + stream, err := client.CountUp(t.Context(), &pingv1.CountUpRequest{Number: 3}) + assert.Nil(t, err) + var got []int64 + for { + message, err := stream.Receive() + if err != nil { + break + } + got = append(got, message.Number) + } + assert.Nil(t, stream.Close()) + assert.Equal(t, got, []int64{1, 2, 3}) + assert.Equal(t, protocol, test.wantStreaming) + }) + } +} diff --git a/internal/wstransport/server_stream.go b/internal/wstransport/server_stream.go new file mode 100644 index 00000000..73c2d11e --- /dev/null +++ b/internal/wstransport/server_stream.go @@ -0,0 +1,63 @@ +// Copyright 2021-2026 The Connect Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package wstransport + +import ( + "errors" + "io" + + "connectrpc.com/connect/v2" +) + +// serverStream adapts [websocketHandlerConn] to [connect.ServerStream]. +type serverStream struct { + conn *websocketHandlerConn + // singleRequest marks a unary or server-streaming call, whose one request + // Receive checks is followed by C, as connecthttp does. + singleRequest bool + received bool +} + +func (s *serverStream) Receive(msg any) error { + if !s.singleRequest { + return s.conn.Receive(msg) + } + if s.received { + return io.EOF + } + s.received = true + if err := s.conn.Receive(msg); err != nil { + if errors.Is(err, io.EOF) { + return connect.Errorf(connect.CodeUnimplemented, "unary request has zero messages") + } + return err + } + // Reading on to C is also what starts the post-C reads that §8.1 requires, + // since the handler never reads again. + if err := s.conn.Receive(msg); err == nil { + return connect.Errorf(connect.CodeUnimplemented, "unary request has multiple messages") + } else if !errors.Is(err, io.EOF) { + return err + } + return nil +} + +func (s *serverStream) SendHeaders() error { + return s.conn.SendHeaders() +} + +func (s *serverStream) Send(msg any) error { + return s.conn.Send(msg) +} diff --git a/internal/wstransport/serverended_ext_test.go b/internal/wstransport/serverended_ext_test.go new file mode 100644 index 00000000..e5a0d344 --- /dev/null +++ b/internal/wstransport/serverended_ext_test.go @@ -0,0 +1,267 @@ +// Copyright 2021-2026 The Connect Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package wstransport_test + +import ( + "context" + "io" + "net" + "net/http" + "net/http/httptest" + "sync/atomic" + "testing" + + "connectrpc.com/connect/v2" + "connectrpc.com/connect/v2/connecthttp" + "connectrpc.com/connect/v2/internal/assert" + pingv1 "connectrpc.com/connect/v2/internal/gen/connect/ping/v1" + "connectrpc.com/connect/v2/internal/gen/connect/ping/v1/pingv1connect" + "connectrpc.com/connect/v2/internal/wstransport" + "github.com/coder/websocket" +) + +// A server may end the RPC while the client is still writing. Whichever write +// discovers that must follow the ClientStream contract: Send reports io.EOF, +// CloseSend succeeds, and Receive reports the server's verdict. +func TestClientWriteAfterServerEndedReportsEOF(t *testing.T) { + t.Parallel() + for _, test := range []struct { + name string + // failFirstWrite closes the connection before the client's opening M, + // as when a server rejects the request as soon as it is upgraded. + failFirstWrite bool + }{ + {name: "after the client has read the verdict"}, + {name: "before the client's first write", failFirstWrite: true}, + } { + t.Run(test.name, func(t *testing.T) { + t.Parallel() + httpServer := endStreamServer(t, nil, "M[]", verdict) + wire := &closingRoundTripper{base: httpServer.Client().Transport} + wire.closed.Store(test.failFirstWrite) + transport := connecthttp.NewTransport( + &http.Client{Transport: wire}, + httpServer.URL, + connecthttp.WithWebSocket(connecthttp.SelectStreaming), + ) + client := pingv1connect.NewPingServiceClient(connect.NewClient(transport)) + stream, err := client.CumSum(t.Context()) + assert.Nil(t, err) + t.Cleanup(func() { _ = stream.Close() }) + + if !test.failFirstWrite { + assert.Nil(t, stream.Send(&pingv1.CumSumRequest{Number: 1})) + _, err = stream.Receive() + assert.Equal(t, connect.CodeOf(err), connect.CodeResourceExhausted) + wire.closed.Store(true) + } + assert.ErrorIs(t, stream.Send(&pingv1.CumSumRequest{Number: 2}), io.EOF) + assert.Nil(t, stream.CloseSend()) + _, err = stream.Receive() + assert.Equal(t, connect.CodeOf(err), connect.CodeResourceExhausted) + }) + } +} + +// As over HTTP, CloseSend after the call's context has ended closes the request +// side without error, and Receive reports why the call ended. +func TestClientCloseSendAfterContextEnded(t *testing.T) { + t.Parallel() + httpServer := endStreamServer(t, nil, "M[]") + wire := &closingRoundTripper{base: httpServer.Client().Transport} + transport := connecthttp.NewTransport( + &http.Client{Transport: wire}, + httpServer.URL, + connecthttp.WithWebSocket(connecthttp.SelectStreaming), + ) + client := pingv1connect.NewPingServiceClient(connect.NewClient(transport)) + ctx, cancel := context.WithCancel(t.Context()) + stream, err := client.CumSum(ctx) + assert.Nil(t, err) + t.Cleanup(func() { _ = stream.Close() }) + + assert.Nil(t, stream.Send(&pingv1.CumSumRequest{Number: 1})) + // The ended context tears the connection down, so the C write fails. + cancel() + wire.closed.Store(true) + assert.Nil(t, stream.CloseSend()) + _, err = stream.Receive() + assert.Equal(t, connect.CodeOf(err), connect.CodeCanceled) +} + +// Once Receive has returned the server's verdict, the client writes nothing +// more: §8 has it send no C, and a B would only be discarded. Writing either +// would race the client's own reply to the server's Close frame. +func TestClientWritesNothingAfterReceivingEndStream(t *testing.T) { + t.Parallel() + received := make(chan []byte, 1) + httpServer := endStreamServer(t, received, "M[]", verdict) + transport := connecthttp.NewTransport( + httpServer.Client(), + httpServer.URL, + connecthttp.WithWebSocket(connecthttp.SelectStreaming), + ) + client := pingv1connect.NewPingServiceClient(connect.NewClient(transport)) + stream, err := client.CumSum(t.Context()) + assert.Nil(t, err) + + assert.Nil(t, stream.Send(&pingv1.CumSumRequest{Number: 1})) + _, err = stream.Receive() + assert.Equal(t, connect.CodeOf(err), connect.CodeResourceExhausted) + assert.ErrorIs(t, stream.Send(&pingv1.CumSumRequest{Number: 2}), io.EOF) + assert.Nil(t, stream.CloseSend()) + assert.Nil(t, stream.Close()) + + assert.Equal(t, string(<-received), string([]byte{wireMetadata, wireBody})) +} + +// §13: once S has arrived the RPC is complete, so a server that then drops the +// connection without a Close frame (1006) does not fail it. +func TestClientCompletesWhenConnectionDropsAfterEndStream(t *testing.T) { + t.Parallel() + t.Run("unary", func(t *testing.T) { + t.Parallel() + client := pingv1connect.NewPingServiceClient(connect.NewClient(droppingServerTransport(t))) + response, err := client.Ping(t.Context(), &pingv1.PingRequest{Number: 1}) + assert.Nil(t, err) + assert.Equal(t, response.GetNumber(), 1) + }) + t.Run("stream", func(t *testing.T) { + t.Parallel() + client := pingv1connect.NewPingServiceClient(connect.NewClient(droppingServerTransport(t))) + stream, err := client.CumSum(t.Context()) + assert.Nil(t, err) + assert.Nil(t, stream.Send(&pingv1.CumSumRequest{Number: 1})) + assert.Nil(t, stream.CloseSend()) + response, err := stream.Receive() + assert.Nil(t, err) + assert.Equal(t, response.GetSum(), 1) + _, err = stream.Receive() + assert.ErrorIs(t, err, io.EOF) + assert.Nil(t, stream.Close()) + }) +} + +// droppingServerTransport dials a server that reads the request up to the +// client's C, answers with a response whose field 1 is 1, and then closes the +// TCP connection without a Close frame. +func droppingServerTransport(tb testing.TB) connect.Transport { + tb.Helper() + listener, err := (&net.ListenConfig{}).Listen(tb.Context(), "tcp", "127.0.0.1:0") + assert.Nil(tb, err) + tb.Cleanup(func() { _ = listener.Close() }) + go func() { + conn, reader := acceptRawUpgrade(tb, listener) + // Reading the whole request first keeps the close from resetting the + // connection, which could discard the response before the client reads it. + for { + _, payload, err := nextFrame(reader) + if err != nil || (len(payload) > 0 && payload[0] == 'C') { + break + } + } + _, _ = conn.Write([]byte{0x81, 3, 'M', '[', ']'}) + _, _ = conn.Write([]byte{0x82, 3, 'B', 0x08, 0x01}) + _, _ = conn.Write([]byte{0x81, 3, 'S', '{', '}'}) + _ = conn.Close() + }() + transport, err := wstransport.NewTransport("http://" + listener.Addr().String()) + assert.Nil(tb, err) + return transport +} + +const verdict = `S{"error":{"code":"resource_exhausted","message":"no more"}}` + +// endStreamServer accepts an upgrade, writes frames as text messages, and sends +// no Close frame, so nothing races the client's writes. It reads until the +// client closes or the test ends, then sends the markers it read to received. +func endStreamServer(tb testing.TB, received chan<- []byte, frames ...string) *httptest.Server { + tb.Helper() + // Closed before any cleanup runs, so the read below ends even while the + // client's Close waits for the server's Close frame. + testDone := tb.Context().Done() + httpServer := httptest.NewServer(http.HandlerFunc( + func(responseWriter http.ResponseWriter, request *http.Request) { + conn, err := websocket.Accept(responseWriter, request, &websocket.AcceptOptions{ + Subprotocols: []string{"connectrpc.1+proto"}, + InsecureSkipVerify: true, + }) + if err != nil { + return + } + defer func() { _ = conn.CloseNow() }() + for _, frame := range frames { + _ = conn.Write(request.Context(), websocket.MessageText, []byte(frame)) + } + // A client whose writes fail cannot send its Close frame, so the + // test's end is what stops this read. + readCtx, cancel := context.WithCancel(request.Context()) + defer cancel() + go func() { + select { + case <-testDone: + cancel() + case <-readCtx.Done(): + } + }() + var markers []byte + for { + _, frame, err := conn.Read(readCtx) + if err != nil { + break + } + if len(frame) > 0 { + markers = append(markers, frame[0]) + } + } + if received != nil { + received <- markers + } + }, + )) + tb.Cleanup(httpServer.Close) + return httpServer +} + +// closingRoundTripper makes writes on the upgraded connection fail once closed +// is set, as they do after the client has answered the server's Close frame. +type closingRoundTripper struct { + base http.RoundTripper + closed atomic.Bool +} + +func (r *closingRoundTripper) RoundTrip(request *http.Request) (*http.Response, error) { + response, err := r.base.RoundTrip(request) + if err != nil { + return nil, err + } + if body, ok := response.Body.(io.ReadWriteCloser); ok { + response.Body = &closingConn{ReadWriteCloser: body, closed: &r.closed} + } + return response, nil +} + +type closingConn struct { + io.ReadWriteCloser + + closed *atomic.Bool +} + +func (c *closingConn) Write(data []byte) (int, error) { + if c.closed.Load() { + return 0, net.ErrClosed + } + return c.ReadWriteCloser.Write(data) +} diff --git a/internal/wstransport/serverlifecycle_ext_test.go b/internal/wstransport/serverlifecycle_ext_test.go new file mode 100644 index 00000000..007943c8 --- /dev/null +++ b/internal/wstransport/serverlifecycle_ext_test.go @@ -0,0 +1,173 @@ +// Copyright 2021-2026 The Connect Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package wstransport_test + +import ( + "context" + "encoding/json" + "errors" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "connectrpc.com/connect/v2" + "connectrpc.com/connect/v2/connecthttp" + "connectrpc.com/connect/v2/internal/assert" + pingv1 "connectrpc.com/connect/v2/internal/gen/connect/ping/v1" + "connectrpc.com/connect/v2/internal/gen/connect/ping/v1/pingv1connect" + "github.com/coder/websocket" +) + +// §13: a server shutting down mid-RPC sends S with unavailable and closes with +// 1001, though http.Server.Shutdown cannot see a hijacked connection. +func TestShutdownEndsStreamsWithGoingAway(t *testing.T) { + t.Parallel() + httpServer := newMountedServer(t) + conn := dialCumSum(t, httpServer, "") + sendProtoBody(t, conn, &pingv1.CumSumRequest{Number: 1}) + data := readServerOpening(t, conn) + assert.Equal(t, data[0], wireBody) + + ctx, cancel := context.WithTimeout(t.Context(), wsTestReadTimeout) + defer cancel() + assert.Nil(t, httpServer.Config.Shutdown(ctx)) + + readCtx, cancelRead := readContext(t) + defer cancelRead() + _, endStream, err := conn.Read(readCtx) + assert.Nil(t, err) + assert.Equal(t, endStream[0], wireServerEndStream) + assert.True(t, strings.Contains(string(endStream), `"code":"unavailable"`), assert.Sprintf("%s", endStream)) + assert.Equal(t, readCloseStatus(t, conn), websocket.StatusGoingAway) +} + +// A client that upgrades and never sends its opening M is hung up on after the +// handshake timeout, not after the RPC's hour-long default. +func TestClientThatNeverOpensTheStreamIsHungUpOn(t *testing.T) { + t.Parallel() + httpServer := newMountedServer(t, connecthttp.WithWebSocketHandshakeTimeout(200*time.Millisecond)) + conn := dialRaw(t, httpServer, pingv1connect.PingServiceCumSumProcedure) + + data := readServerOpening(t, conn) + assert.Equal(t, data[0], wireServerEndStream) + assert.True(t, strings.Contains(string(data), `"code":"deadline_exceeded"`), assert.Sprintf("%s", data)) + assert.True(t, strings.Contains(string(data), "opening M")) + assert.Equal(t, readCloseStatus(t, conn), websocket.StatusNormalClosure) +} + +// §9 and §7.3.1: a trailer the server may not send is not sent, and it becomes +// the RPC's outcome, as an unsendable header does. +func TestServerRefusesToSendInvalidTrailer(t *testing.T) { + t.Parallel() + for name, test := range map[string]struct{ key, value string }{ + "control character": {key: "Acme-Bad", value: "a\nb"}, + "binary not base64": {key: "Acme-Bad-Bin", value: "not base64!"}, + } { + t.Run(name, func(t *testing.T) { + t.Parallel() + httpServer := newServerFor(t, trailerWritingServer{key: test.key, value: test.value}) + conn := dialCumSum(t, httpServer, "") + sendJSONMessage(t, conn, wireClientEndStream, nil) + + data := readServerOpening(t, conn) + assert.Equal(t, data[0], wireServerEndStream) + var end struct { + Error struct { + Code string `json:"code"` + Message string `json:"message"` + } `json:"error"` + Metadata map[string][]string `json:"metadata"` + } + assert.Nil(t, json.Unmarshal(data[1:], &end)) + assert.Equal(t, end.Error.Code, "internal") + assert.True(t, strings.Contains(end.Error.Message, test.key), assert.Sprintf("%s", end.Error.Message)) + assert.Equal(t, len(end.Metadata), 0) + }) + } +} + +// unwrappingWriter is middleware's response writer: it hides the Hijacker it +// wraps, and exposes it through Unwrap as http.ResponseController expects. +type unwrappingWriter struct { + responseWriter http.ResponseWriter +} + +func (w *unwrappingWriter) Header() http.Header { return w.responseWriter.Header() } +func (w *unwrappingWriter) Write(data []byte) (int, error) { return w.responseWriter.Write(data) } +func (w *unwrappingWriter) WriteHeader(statusCode int) { w.responseWriter.WriteHeader(statusCode) } +func (w *unwrappingWriter) Unwrap() http.ResponseWriter { return w.responseWriter } + +// Middleware that wraps the response writer does not break the upgrade. +func TestUpgradeFindsTheHijackerThroughUnwrap(t *testing.T) { + t.Parallel() + server := connect.NewServer() + pingv1connect.RegisterPingServiceHandler(server, pingServer{}) + mux := http.NewServeMux() + connecthttp.Mount(mux, server) + httpServer := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) { + mux.ServeHTTP(&unwrappingWriter{responseWriter: writer}, request) + })) + t.Cleanup(httpServer.Close) + client := newWebSocketClient(t, httpServer.Client(), httpServer.URL) + + // A failed hijack leaves the client waiting, so bound it. + deadlineCtx, cancel := context.WithTimeout(t.Context(), wsTestReadTimeout) + defer cancel() + ctx, info := connect.NewClientContext(deadlineCtx) + response, err := client.Ping(ctx, &pingv1.PingRequest{Number: 3}) + assert.Nil(t, err) + assert.Equal(t, response.GetNumber(), int64(3)) + assert.Equal(t, info.Protocol, connecthttp.ProtocolNameConnectWebSocket) +} + +// slowFinishServer finishes a stream only after wsCloseWriteTimeout (5s) has +// passed since the upgrade, then sets a trailer that only S can carry. +type slowFinishServer struct { + pingv1connect.UnimplementedPingServiceHandler +} + +func (slowFinishServer) CountUp( + ctx context.Context, + _ *pingv1.CountUpRequest, + _ pingv1connect.PingServiceCountUpServerStream, +) error { + select { + case <-time.After(6 * time.Second): + case <-ctx.Done(): + return ctx.Err() + } + info, _ := connect.CallInfoForServerContext(ctx) + info.ResponseTrailer().Set("Acme-Finished", "yes") + return nil +} + +// The bound on the closing write starts when the handler returns, not when +// the stream opened, so a stream that outlives it still delivers its verdict. +func TestLongRunningStreamStillSendsItsVerdict(t *testing.T) { + t.Parallel() + httpServer := newServerFor(t, slowFinishServer{}) + client := newWebSocketClient(t, httpServer.Client(), httpServer.URL) + ctx, info := connect.NewClientContext(t.Context()) + stream, err := client.CountUp(ctx, &pingv1.CountUpRequest{Number: 1}) + assert.Nil(t, err) + + _, err = stream.Receive() + assert.True(t, errors.Is(err, io.EOF), assert.Sprintf("%v", err)) + assert.Equal(t, info.ResponseTrailer().Get("Acme-Finished"), "yes") + assert.Nil(t, stream.Close()) +} diff --git a/internal/wstransport/session.go b/internal/wstransport/session.go new file mode 100644 index 00000000..1665d53f --- /dev/null +++ b/internal/wstransport/session.go @@ -0,0 +1,300 @@ +// Copyright 2021-2026 The Connect Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package wstransport + +import ( + "context" + "net/http" + "net/url" + "strings" + "time" + + "connectrpc.com/connect/v2" + "github.com/coder/websocket" +) + +// NewSession returns the [Session] that serves Connect RPCs on an upgraded +// connection. One connection carries one RPC: the procedure is the one given +// to [WithProcedure], or else the request path. +// +// [Upgrade] builds this itself. Call it only to wrap +// the default behavior in a [Session] of your own and pass the result to +// [WithSession]; it needs no configuring, because everything it uses arrives +// on [SessionInfo]. +func NewSession() Session { + return &session{} +} + +// session holds no configuration: everything it needs arrives on SessionInfo, +// so a Session cannot be configured differently from the handshake that +// produced it. +type session struct{} + +func (s *session) Serve( + ctx context.Context, + server *connect.Server, + conn *websocket.Conn, + info SessionInfo, +) error { + // Bounds both sides of permessage-deflate (§12): the inflated message is + // capped at the limit, and its compressed input at twice the limit plus a + // margin, which drainLimiter counts on the connection. A stream of + // zero-output DEFLATE blocks, which never inflates to anything, is cut off + // there. + // + // The bound only holds because the closing handshake's drain is capped + // too: it would otherwise read whatever the peer queued. See drainLimiter, + // and TestCompressionBombIsBoundedOnTheWire, which fails if either half + // regresses. + // + // The limit is enforced in readBoundedMessage rather than here: coder's own + // SetReadLimit closes with 1009 the moment it trips, leaving nothing to + // write the S message on. + conn.SetReadLimit(-1) + serveCtx := ctx + ctx, cancel, timeoutErr := timeoutFromRequest(ctx, info.Request, info.MaxTimeout) + if cancel != nil { + defer cancel() + } + // Cancelable in its own right, so that the reader can end the call when + // the connection dies under it (§8). timeoutFromRequest returns no cancel + // of its own when neither side set a deadline. + ctx, cancelCall := context.WithCancel(ctx) + defer cancelCall() + procedure, spec := sessionSpec(server, info) + callInfo := newCallInfo(spec, info) + + // Every return below has closed conn by the time these run, which is what + // lets the reader's read in flight return. + // + // The reader is detached from the RPC's deadline: the WebSocket library + // closes the connection when a read's context expires, which would leave + // no connection to send the deadline's S message on. + // + // §8: a connection that ends before S cancels the RPC, whether or not C + // arrived and whether or not the handler is reading. Once S is sent the + // handler has returned, so the cancellation reaches nobody. + readLimit := messageReadLimit(info.ReadMaxBytes) + reader := newFrameReader( + context.WithoutCancel(ctx), + func(readCtx context.Context) (websocket.MessageType, []byte, error) { + return readBoundedMessage(readCtx, conn, readLimit, info.drain) + }, + cancelCall, + ) + info.heartbeat.attach(reader) + defer reader.close() + // Detached, as the reader is: the library closes the connection when a + // Ping's context ends, so the RPC's end would cut off its own S. + keeper := startKeepAlive( + context.WithoutCancel(ctx), conn, reader, info.KeepAliveInterval, info.KeepAliveTimeout, + websocket.StatusInternalError, + ) + defer keeper.stop() + handlerConn := &websocketHandlerConn{ + frameDecoder: frameDecoder{ + readMaxBytes: info.ReadMaxBytes, + }, + ctx: ctx, + wsConn: conn, + marshaler: messageWriter{ + // No compression here: the WebSocket transport compresses whole + // messages itself, so a second pass would deflate gzip. + sender: &websocketBinarySender{conn: conn}, + sendMaxBytes: info.SendMaxBytes, + stats: &callInfo.SendStats, + }, + reader: reader, + keeper: keeper, + callInfo: callInfo, + cancelCall: cancelCall, + info: info, + shuttingDown: func() bool { return isShuttingDown(serveCtx) }, + } + + if timeoutErr != nil { + // The handshake already committed the HTTP response, so a malformed + // deadline can only be reported in the end-of-stream message. + return handlerConn.Close(ctx, timeoutErr) + } + + // net/http recovers a panicking handler but deliberately leaves a hijacked + // connection open ("if !c.hijacked()"), so unlike an HTTP handler nothing + // closes the socket on the way out: the server leaks it and the client + // blocks on a Receive that will never return. Tear it down, then let the + // panic continue to whatever recovers it — converting panics into RPC + // errors is an interceptor's job, not the transport's. + defer func() { + if recovered := recover(); recovered != nil { + _ = conn.CloseNow() + panic(recovered) + } + }() + + // Consume the client's Leading-Metadata before the handler exists, so + // CallInfo is complete for interceptors and frozen for the handler. See + // drainLeadingMetadata. + if drainErr := handlerConn.drainLeadingMetadata(ctx); drainErr != nil { + return handlerConn.Close(ctx, drainErr) + } + + stream := &serverStream{ + conn: handlerConn, + singleRequest: spec.StreamType&connect.StreamTypeClient == 0, + } + callErr := server.Call(ctx, procedure, callInfo, stream) + return handlerConn.Close(ctx, callErr) +} + +// sessionSpec names the procedure a session calls and finds its spec. +func sessionSpec(server *connect.Server, info SessionInfo) (string, connect.Spec) { + procedure := info.Procedure + if procedure == "" { + procedure = info.Request.URL.Path + } + spec, registered := registeredSpec(server, procedure) + if !registered { + // Server.Call reports the unknown procedure; until then, bidi is the + // permissive answer. + spec = connect.Spec{Procedure: procedure, StreamType: connect.StreamTypeBidi} + } + return procedure, spec +} + +// newCallInfo describes the RPC to the handler, starting from the upgrade +// request's headers. The client's M message adds to them later. +func newCallInfo(spec connect.Spec, info SessionInfo) *connect.CallInfo { + callInfo := &connect.CallInfo{ + Spec: spec, + PeerAddr: info.Request.RemoteAddr, + Protocol: ProtocolConnectWebSocket, + Codec: info.Codec.Name(), + // Identity at the Connect layer: the transport's permessage-deflate is + // below it and invisible to the protocol. + RequestEncoding: connect.CompressionNameIdentity, + ResponseEncoding: connect.CompressionNameIdentity, + TransportInfo: info.TransportInfo, + } + for key, values := range info.Request.Header { + if isStrippedHandshakeHeader(key) { + continue + } + callInfo.RequestHeader().SetValues(key, values) + } + // net/http moves Host out of the header map; over HTTP, connecthttp puts + // it back, and a handler should not have to know which transport ran it. + if info.Request.Host != "" { + callInfo.RequestHeader().Set("Host", info.Request.Host) + } + return callInfo +} + +// registeredSpec finds the spec server registered for procedure. +func registeredSpec(server *connect.Server, procedure string) (connect.Spec, bool) { + for spec := range server.Specs() { + if spec.Procedure == procedure { + return spec, true + } + } + return connect.Spec{}, false +} + +// rawQueryValues returns every value of name in a raw query string. Unlike +// URL.Query, it keeps a value that is not valid percent-encoding, or that a +// semicolon runs into, rather than dropping the pair: §11 makes such a +// deadline invalid, not absent. +func rawQueryValues(rawQuery, name string) []string { + var values []string + for pair := range strings.SplitSeq(rawQuery, "&") { + key, value, _ := strings.Cut(pair, "=") + if unescaped, err := url.QueryUnescape(key); err == nil { + key = unescaped + } + if key != name { + continue + } + if unescaped, err := url.QueryUnescape(value); err == nil { + value = unescaped + } + values = append(values, value) + } + return values +} + +// timeoutFromRequest applies the client's deadline to ctx. +// +// The query parameter is the only channel: a browser's WebSocket API cannot +// set a header on the upgrade, so a header would serve no client this +// transport has to interoperate with. A Connect-Timeout-Ms header that arrives +// anyway is ordinary request metadata, not a deadline. +func timeoutFromRequest( + ctx context.Context, + request *http.Request, + maxTimeout time.Duration, +) (context.Context, context.CancelFunc, *connect.Error) { + values := rawQueryValues(request.URL.RawQuery, wsQueryTimeoutMs) + if len(values) == 0 { + // No client deadline, so the server's bound is the whole of it. + if maxTimeout <= 0 { + return ctx, nil, nil + } + ctx, cancel := context.WithTimeout(ctx, maxTimeout) + return ctx, cancel, nil + } + // §11: a deadline stated twice is invalid, rather than a choice between + // the two that the client cannot see the server make. + if len(values) > 1 { + return ctx, nil, errorf( + connect.CodeInvalidArgument, "parse timeout: %s appears %d times", wsQueryTimeoutMs, len(values), + ) + } + timeout := values[0] + if timeout == "" { + return ctx, nil, errorf(connect.CodeInvalidArgument, "parse timeout: no value supplied") + } + if len(timeout) > 10 { + return ctx, nil, errorf(connect.CodeInvalidArgument, "parse timeout: %q has >10 digits", timeout) + } + // §11 allows digits alone, as Connect over HTTP does: no sign, so neither + // a negative deadline nor "+" gets through. + var millis int64 + for _, digit := range timeout { + if digit < '0' || digit > '9' { + return ctx, nil, errorf( + connect.CodeInvalidArgument, "parse timeout: %q has non-digit characters", timeout, + ) + } + millis = millis*10 + int64(digit-'0') + } + // §11: as over HTTP, a zero timeout means the RPC is not dispatched at all. + if millis == 0 { + return ctx, nil, errorf( + connect.CodeDeadlineExceeded, "%s is 0, so the deadline has already passed", wsQueryTimeoutMs, + ) + } + requested := time.Duration(millis) * time.Millisecond + // The effective deadline is the shorter of the client's and the server's. + if maxTimeout > 0 && requested > maxTimeout { + requested = maxTimeout + } + ctx, cancel := context.WithTimeout(ctx, requested) + return ctx, cancel, nil +} + +func copyToHTTPHeader(dst http.Header, src *connect.Header) { + for key, values := range src.All() { + dst[http.CanonicalHeaderKey(key)] = append(dst[http.CanonicalHeaderKey(key)], values...) + } +} diff --git a/internal/wstransport/shutdown.go b/internal/wstransport/shutdown.go new file mode 100644 index 00000000..61ef657c --- /dev/null +++ b/internal/wstransport/shutdown.go @@ -0,0 +1,88 @@ +// Copyright 2021-2026 The Connect Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package wstransport + +import ( + "context" + "errors" + "net/http" + "sync" +) + +// errServerShutdown is the cause a session's context carries once the +// [http.Server] serving it begins to shut down. +var errServerShutdown = errors.New("server is shutting down") + +// shutdownTracker ends sessions when their server shuts down. A hijacked +// connection is invisible to [http.Server.Shutdown], so without this a stream +// outlives its server with no S message (§13). +type shutdownTracker struct { + mu sync.Mutex + registered map[*http.Server]struct{} + sessions map[*trackedSession]struct{} +} + +type trackedSession struct { + server *http.Server + cancel context.CancelCauseFunc +} + +func newShutdownTracker() *shutdownTracker { + return &shutdownTracker{ + registered: make(map[*http.Server]struct{}), + sessions: make(map[*trackedSession]struct{}), + } +} + +// track returns the context to serve a session under, derived from the +// request's ctx and canceled with errServerShutdown when the server that +// accepted the request shuts down. The returned function stops tracking it. +func (t *shutdownTracker) track(ctx context.Context) (context.Context, func()) { + server, ok := ctx.Value(http.ServerContextKey).(*http.Server) + ctx, cancel := context.WithCancelCause(ctx) + if !ok || server == nil { + return ctx, func() { cancel(nil) } + } + session := &trackedSession{server: server, cancel: cancel} + t.mu.Lock() + if _, registered := t.registered[server]; !registered { + t.registered[server] = struct{}{} + server.RegisterOnShutdown(func() { t.shutdown(server) }) + } + t.sessions[session] = struct{}{} + t.mu.Unlock() + return ctx, func() { + t.mu.Lock() + delete(t.sessions, session) + t.mu.Unlock() + cancel(nil) + } +} + +func (t *shutdownTracker) shutdown(server *http.Server) { + t.mu.Lock() + defer t.mu.Unlock() + delete(t.registered, server) + for session := range t.sessions { + if session.server == server { + session.cancel(errServerShutdown) + } + } +} + +// isShuttingDown reports whether ctx was canceled by its server shutting down. +func isShuttingDown(ctx context.Context) bool { + return errors.Is(context.Cause(ctx), errServerShutdown) +} diff --git a/internal/wstransport/singlerequest_ext_test.go b/internal/wstransport/singlerequest_ext_test.go new file mode 100644 index 00000000..eeb3da75 --- /dev/null +++ b/internal/wstransport/singlerequest_ext_test.go @@ -0,0 +1,138 @@ +// Copyright 2021-2026 The Connect Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package wstransport_test + +import ( + "context" + "errors" + "io" + "strings" + "testing" + "time" + + "connectrpc.com/connect/v2/internal/assert" + pingv1 "connectrpc.com/connect/v2/internal/gen/connect/ping/v1" + "connectrpc.com/connect/v2/internal/gen/connect/ping/v1/pingv1connect" + "github.com/coder/websocket" + "google.golang.org/protobuf/proto" +) + +// §8.1 and §5: a message after C is a protocol error, and it ends the stream +// whatever the RPC's shape. The handler ignores its context and answers late, +// so a server that only noticed once the handler returned would send that +// answer first. +func TestMessageAfterEndOfClientStreamEndsTheStream(t *testing.T) { + t.Parallel() + for _, test := range []struct { + name string + procedure string + request proto.Message + }{ + {name: "unary", procedure: pingv1connect.PingServicePingProcedure, request: &pingv1.PingRequest{Number: 1}}, + { + name: "server streaming", + procedure: pingv1connect.PingServiceCountUpProcedure, + request: &pingv1.CountUpRequest{Number: 1}, + }, + {name: "bidi", procedure: pingv1connect.PingServiceCumSumProcedure, request: &pingv1.CumSumRequest{Number: 1}}, + } { + t.Run(test.name, func(t *testing.T) { + t.Parallel() + httpServer := newHybridServer2(t, lateAnswerServer{delay: 300 * time.Millisecond}) + conn := dialRaw(t, httpServer, test.procedure) + sendJSONMessage(t, conn, wireMetadata, []byte("[]")) + sendProtoBody(t, conn, test.request) + sendJSONMessage(t, conn, wireClientEndStream, nil) + sendProtoBody(t, conn, test.request) + + data := readServerOpening(t, conn) + assert.Equal(t, data[0], wireServerEndStream) + assert.True(t, strings.Contains(string(data), "internal")) + assert.True(t, strings.Contains(string(data), "after its C message")) + ctx, cancel := readContext(t) + defer cancel() + _, _, err := conn.Read(ctx) + assert.Equal(t, websocket.CloseStatus(err), websocket.StatusProtocolError) + }) + } +} + +// A unary or server-streaming call has exactly one request, which the server +// checks as Connect over HTTP does. +func TestSingleRequestCallsCheckTheRequestCount(t *testing.T) { + t.Parallel() + for _, test := range []struct { + name string + requests int + want string + }{ + {name: "no request", requests: 0, want: "zero messages"}, + {name: "two requests", requests: 2, want: "multiple messages"}, + } { + t.Run(test.name, func(t *testing.T) { + t.Parallel() + httpServer := newHybridServer2(t, lateAnswerServer{}) + conn := dialRaw(t, httpServer, pingv1connect.PingServicePingProcedure) + sendJSONMessage(t, conn, wireMetadata, []byte("[]")) + for range test.requests { + sendProtoBody(t, conn, &pingv1.PingRequest{Number: 1}) + } + sendJSONMessage(t, conn, wireClientEndStream, nil) + + data := readServerOpening(t, conn) + assert.Equal(t, data[0], wireServerEndStream) + assert.True(t, strings.Contains(string(data), "unimplemented")) + assert.True(t, strings.Contains(string(data), test.want)) + }) + } +} + +// lateAnswerServer answers each request after delay, ignoring its context as a +// handler busy with slow work does. +type lateAnswerServer struct { + pingv1connect.UnimplementedPingServiceHandler + + delay time.Duration +} + +func (s lateAnswerServer) Ping(_ context.Context, request *pingv1.PingRequest) (*pingv1.PingResponse, error) { + time.Sleep(s.delay) + return &pingv1.PingResponse{Number: request.GetNumber()}, nil +} + +func (s lateAnswerServer) CountUp( + _ context.Context, + request *pingv1.CountUpRequest, + stream pingv1connect.PingServiceCountUpServerStream, +) error { + time.Sleep(s.delay) + return stream.Send(&pingv1.CountUpResponse{Number: request.GetNumber()}) +} + +func (s lateAnswerServer) CumSum(_ context.Context, stream pingv1connect.PingServiceCumSumServerStream) error { + var sum int64 + for { + request, err := stream.Receive() + if errors.Is(err, io.EOF) { + break + } + if err != nil { + return err + } + sum += request.GetNumber() + } + time.Sleep(s.delay) + return stream.Send(&pingv1.CumSumResponse{Sum: sum}) +} diff --git a/internal/wstransport/streamlifecycle_ext_test.go b/internal/wstransport/streamlifecycle_ext_test.go new file mode 100644 index 00000000..374648fe --- /dev/null +++ b/internal/wstransport/streamlifecycle_ext_test.go @@ -0,0 +1,217 @@ +// Copyright 2021-2026 The Connect Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package wstransport_test + +import ( + "context" + "errors" + "io" + "net/http" + "net/http/httptest" + "sync/atomic" + "testing" + "time" + + "connectrpc.com/connect/v2" + "connectrpc.com/connect/v2/connecthttp" + "connectrpc.com/connect/v2/internal/assert" + pingv1 "connectrpc.com/connect/v2/internal/gen/connect/ping/v1" + "connectrpc.com/connect/v2/internal/gen/connect/ping/v1/pingv1connect" + "connectrpc.com/connect/v2/internal/wstransport" +) + +// lifecycleWait bounds how long a test waits for the server to notice that a +// client left. Well under the 5s closing-handshake timeout, so a stall fails. +const lifecycleWait = 3 * time.Second + +// idleAfterOneServer receives one message, then stops reading and waits on its +// context, which is where a handler that computes or sends spends its time. +// Once the context ends it reads whatever the server had already read for it, +// and reports how the context and the request stream each ended. +type idleAfterOneServer struct { + pingv1connect.UnimplementedPingServiceHandler + + received chan struct{} + ended chan idleOutcome +} + +type idleOutcome struct { + contextErr error + receiveErr error +} + +func (s *idleAfterOneServer) CumSum( + ctx context.Context, + stream pingv1connect.PingServiceCumSumServerStream, +) error { + if _, err := stream.Receive(); err != nil { + s.ended <- idleOutcome{receiveErr: err} + return err + } + close(s.received) + select { + case <-ctx.Done(): + case <-time.After(wsTestReadTimeout): + s.ended <- idleOutcome{} + return nil + } + outcome := idleOutcome{contextErr: ctx.Err()} + for { + if _, err := stream.Receive(); err != nil { + outcome.receiveErr = err + break + } + } + s.ended <- outcome + return outcome.receiveErr +} + +func newIdleAfterOneClient(tb testing.TB) (pingv1connect.PingServiceClient, *idleAfterOneServer) { + tb.Helper() + handler := &idleAfterOneServer{ + received: make(chan struct{}), + ended: make(chan idleOutcome, 1), + } + httpServer := newServerFor(tb, handler) + transport := connecthttp.NewTransport( + httpServer.Client(), + httpServer.URL, + connecthttp.WithWebSocket(connecthttp.SelectAll), + ) + return pingv1connect.NewPingServiceClient(connect.NewClient(transport)), handler +} + +func awaitHandlerEnd(tb testing.TB, handler *idleAfterOneServer) idleOutcome { + tb.Helper() + select { + case outcome := <-handler.ended: + assert.True(tb, errors.Is(outcome.contextErr, context.Canceled)) + return outcome + case <-time.After(lifecycleWait): + tb.Fatal("handler context was not canceled after the client left") + return idleOutcome{} + } +} + +// §8: a server whose connection ends before it sends S treats the RPC as +// canceled, whether or not it received C. The handler is not reading, so the +// server has to keep reading on its behalf to see the end at all, and the +// client's closing handshake must not wait out its timeout. The messages read +// on the handler's behalf are still delivered, and C still ends the stream. +func TestConnectionEndCancelsHandlerThatIsNotReading(t *testing.T) { + t.Parallel() + client, handler := newIdleAfterOneClient(t) + stream, err := client.CumSum(t.Context()) + assert.Nil(t, err) + assert.Nil(t, stream.Send(&pingv1.CumSumRequest{Number: 1})) + assert.Nil(t, stream.Send(&pingv1.CumSumRequest{Number: 2})) + assert.Nil(t, stream.CloseSend()) + <-handler.received + + start := time.Now() + _ = stream.Close() + assert.True(t, time.Since(start) < lifecycleWait, assert.Sprintf("Close took %v", time.Since(start))) + outcome := awaitHandlerEnd(t, handler) + assert.True(t, errors.Is(outcome.receiveErr, io.EOF)) +} + +// The same when the client's context is canceled mid-stream, without C. +func TestClientCancelCancelsHandlerThatIsNotReading(t *testing.T) { + t.Parallel() + client, handler := newIdleAfterOneClient(t) + ctx, cancel := context.WithCancel(t.Context()) + stream, err := client.CumSum(ctx) + assert.Nil(t, err) + assert.Nil(t, stream.Send(&pingv1.CumSumRequest{Number: 1})) + <-handler.received + cancel() + outcome := awaitHandlerEnd(t, handler) + assert.Equal(t, connect.CodeOf(outcome.receiveErr), connect.CodeCanceled) + _ = stream.Close() +} + +// §8: a client that closes before S without sending C cancels the RPC. Close +// must not send C first, or the handler reads a clean io.EOF and may commit a +// stream the caller abandoned. +func TestCloseBeforeEndOfStreamCancelsInsteadOfFinishing(t *testing.T) { + t.Parallel() + client, handler := newIdleAfterOneClient(t) + stream, err := client.CumSum(t.Context()) + assert.Nil(t, err) + assert.Nil(t, stream.Send(&pingv1.CumSumRequest{Number: 1})) + <-handler.received + _ = stream.Close() + outcome := awaitHandlerEnd(t, handler) + assert.False(t, errors.Is(outcome.receiveErr, io.EOF)) + assert.Equal(t, connect.CodeOf(outcome.receiveErr), connect.CodeCanceled) +} + +// Closing a stream that was never used costs nothing: no dial, and no handler +// run for an RPC nobody asked for. connecthttp behaves the same way. +func TestClosingUnusedStreamDoesNotDial(t *testing.T) { + t.Parallel() + server := connect.NewServer() + pingv1connect.RegisterPingServiceHandler(server, countUpServer{}) + mux := http.NewServeMux() + mountBoth(mux, server) + var upgrades atomic.Int32 + httpServer := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) { + if wstransport.IsUpgrade(request) { + upgrades.Add(1) + } + mux.ServeHTTP(writer, request) + })) + t.Cleanup(httpServer.Close) + transport := connecthttp.NewTransport( + httpServer.Client(), + httpServer.URL, + connecthttp.WithWebSocket(connecthttp.SelectAll), + ) + client := pingv1connect.NewPingServiceClient(connect.NewClient(transport)) + + stream, err := client.CumSum(t.Context()) + assert.Nil(t, err) + assert.Nil(t, stream.Close()) + assert.Equal(t, upgrades.Load(), int32(0)) +} + +// Close may run concurrently with Receive, and both touch the response +// metadata. Run under -race, which is how make shorttest runs it. +func TestCloseConcurrentWithReceive(t *testing.T) { + t.Parallel() + httpServer := newServerFor(t, countUpServer{}) + transport := connecthttp.NewTransport( + httpServer.Client(), + httpServer.URL, + connecthttp.WithWebSocket(connecthttp.SelectAll), + ) + client := pingv1connect.NewPingServiceClient(connect.NewClient(transport)) + for attempt := range 20 { + stream, err := client.CountUp(t.Context(), &pingv1.CountUpRequest{Number: 100}) + assert.Nil(t, err) + received := make(chan struct{}) + go func() { + defer close(received) + for { + if _, receiveErr := stream.Receive(); receiveErr != nil { + return + } + } + }() + time.Sleep(time.Duration(attempt%3) * time.Millisecond) + _ = stream.Close() + <-received + } +} diff --git a/internal/wstransport/timeout_ext_test.go b/internal/wstransport/timeout_ext_test.go new file mode 100644 index 00000000..80db1739 --- /dev/null +++ b/internal/wstransport/timeout_ext_test.go @@ -0,0 +1,482 @@ +// Copyright 2021-2026 The Connect Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package wstransport_test + +import ( + "context" + "errors" + "io" + "net/http" + "net/http/httptest" + "net/url" + "strconv" + "strings" + "testing" + "time" + + "connectrpc.com/connect/v2" + "connectrpc.com/connect/v2/connecthttp" + "connectrpc.com/connect/v2/internal/assert" + pingv1 "connectrpc.com/connect/v2/internal/gen/connect/ping/v1" + "connectrpc.com/connect/v2/internal/gen/connect/ping/v1/pingv1connect" + "github.com/coder/websocket" + "google.golang.org/protobuf/proto" +) + +// dialCumSum opens a raw CumSum stream with the given query string, so a test +// can drive the wire directly rather than through the Go client. +func dialCumSum(tb testing.TB, httpServer *httptest.Server, query string) *websocket.Conn { + tb.Helper() + url := "ws" + strings.TrimPrefix(httpServer.URL, "http") + + pingv1connect.PingServiceCumSumProcedure + query + conn, res, err := websocket.Dial(tb.Context(), url, &websocket.DialOptions{ + HTTPClient: httpServer.Client(), + Subprotocols: []string{"connectrpc.1+proto"}, + }) + if res != nil && res.Body != nil { + _ = res.Body.Close() + } + assert.Nil(tb, err) + tb.Cleanup(func() { _ = conn.CloseNow() }) + // Every stream opens with Leading-Metadata; see the protocol's ordering rule. + sendJSONMessage(tb, conn, wireMetadata, []byte("[]")) + return conn +} + +// sendProtoBody writes one Protobuf body, which starts the RPC. Protobuf means +// a binary frame. +func sendProtoBody(tb testing.TB, conn *websocket.Conn, msg proto.Message) { + tb.Helper() + payload, err := proto.Marshal(msg) + assert.Nil(tb, err) + sendWireMessage(tb, conn, false, wireBody, payload) +} + +// sendJSONMessage writes one control message: JSON, hence a text frame. +func sendJSONMessage(tb testing.TB, conn *websocket.Conn, marker byte, payload []byte) { + tb.Helper() + sendWireMessage(tb, conn, true, marker, payload) +} + +// sendWireMessage writes one marker and payload, so a test can produce a +// message the Go client would never send. +func sendWireMessage(tb testing.TB, conn *websocket.Conn, text bool, marker byte, payload []byte) { + tb.Helper() + frame := append([]byte{marker}, payload...) + messageType := websocket.MessageBinary + if text { + messageType = websocket.MessageText + } + assert.Nil(tb, conn.Write(tb.Context(), messageType, frame)) +} + +// §11: the deadline is an integer of at most ten digits, with no sign, stated +// once. Anything else is reported in-band as invalid_argument, as over HTTP. +func TestInvalidTimeoutQueryParameterIsRejected(t *testing.T) { + t.Parallel() + for _, query := range []string{ + "connect-timeout-ms=-1000", + "connect-timeout-ms=%2B1000", + "connect-timeout-ms=", + "connect-timeout-ms=soon", + "connect-timeout-ms=1.5", + "connect-timeout-ms=12345678901", + "connect-timeout-ms=1000&connect-timeout-ms=1000", + // Not valid percent-encoding, and a semicolon, both of which a lenient + // query parser drops, making the deadline look absent. + "connect-timeout-ms=1%zz", + "connect-timeout-ms=5;x", + } { + t.Run(strconv.Quote(query), func(t *testing.T) { + t.Parallel() + httpServer := newHybridServer(t, pingServer{}) + conn := dialCumSum(t, httpServer, "?"+query) + sendProtoBody(t, conn, &pingv1.CumSumRequest{Number: 1}) + + data := readServerOpening(t, conn) + assert.Equal(t, data[0], wireServerEndStream) + assert.True(t, strings.Contains(string(data), "invalid_argument")) + }) + } +} + +// §11: a zero deadline is valid and has already passed, so the RPC is not +// dispatched and fails in-band with deadline_exceeded, as over HTTP. +func TestZeroTimeoutExpiresImmediately(t *testing.T) { + t.Parallel() + deadlines := make(chan time.Duration, 1) + httpServer := newHybridServer(t, pingServer{sawDeadline: deadlines}) + conn := dialCumSum(t, httpServer, "?connect-timeout-ms=0") + sendProtoBody(t, conn, &pingv1.CumSumRequest{Number: 1}) + + data := readServerOpening(t, conn) + assert.Equal(t, data[0], wireServerEndStream) + assert.True(t, strings.Contains(string(data), "deadline_exceeded")) + readCtx, cancelRead := readContext(t) + defer cancelRead() + _, _, err := conn.Read(readCtx) + assert.Equal(t, websocket.CloseStatus(err), websocket.StatusNormalClosure) + select { + case <-deadlines: + t.Fatal("the handler ran") + default: + } +} + +// A client that requests no deadline still gets one: the server's default +// bounds every RPC, so a peer cannot hold a connection open forever. +func TestNoClientTimeoutFallsBackToTheServerDefault(t *testing.T) { + t.Parallel() + deadlines := make(chan time.Duration, 1) + httpServer := newHybridServer(t, pingServer{sawDeadline: deadlines}) + conn := dialCumSum(t, httpServer, "") + sendProtoBody(t, conn, &pingv1.CumSumRequest{Number: 1}) + + select { + case remaining := <-deadlines: + // The package default, minus the flight time to get here. + assert.True(t, remaining > 0) + assert.True(t, remaining <= time.Hour) + assert.True(t, remaining > 59*time.Minute) + case <-time.After(5 * time.Second): + t.Fatal("handler never ran") + } +} + +// The query parameter is the deadline's only channel. A Connect-Timeout-Ms +// header is ordinary request metadata here, so a header that disagrees with +// the query parameter does not shorten the RPC — and does not fail it either. +func TestTimeoutHeaderIsNotADeadline(t *testing.T) { + t.Parallel() + deadlines := make(chan time.Duration, 1) + httpServer := newHybridServer(t, pingServer{sawDeadline: deadlines}) + url := "ws" + strings.TrimPrefix(httpServer.URL, "http") + + pingv1connect.PingServiceCumSumProcedure + "?connect-timeout-ms=1500" + conn, res, err := websocket.Dial(t.Context(), url, &websocket.DialOptions{ + HTTPClient: httpServer.Client(), + Subprotocols: []string{"connectrpc.1+proto"}, + HTTPHeader: map[string][]string{"Connect-Timeout-Ms": {"9000"}}, + }) + if res != nil && res.Body != nil { + _ = res.Body.Close() + } + assert.Nil(t, err) + t.Cleanup(func() { _ = conn.CloseNow() }) + sendJSONMessage(t, conn, wireMetadata, []byte("[]")) + sendProtoBody(t, conn, &pingv1.CumSumRequest{Number: 1}) + + select { + case remaining := <-deadlines: + // The query parameter's 1.5s, not the header's 9s. + assert.True(t, remaining <= 1500*time.Millisecond) + assert.True(t, remaining > time.Second) + case <-time.After(5 * time.Second): + t.Fatal("handler never ran") + } +} + +// slowDeadlineServer overruns its deadline while computing rather than while +// blocked in a read, so the socket is still alive when the context dies. It +// never calls Receive, so no read is pending to be torn down. +type slowDeadlineServer struct { + pingv1connect.UnimplementedPingServiceHandler +} + +func (slowDeadlineServer) CountUp( + ctx context.Context, + _ *pingv1.CountUpRequest, + _ pingv1connect.PingServiceCountUpServerStream, +) error { + <-ctx.Done() + time.Sleep(20 * time.Millisecond) + return ctx.Err() +} + +// lateSendServer ignores its deadline and sends after it has passed, as a +// handler busy with slow work does. +type lateSendServer struct { + pingv1connect.UnimplementedPingServiceHandler +} + +func (lateSendServer) CountUp( + ctx context.Context, + _ *pingv1.CountUpRequest, + stream pingv1connect.PingServiceCountUpServerStream, +) error { + deadline, _ := ctx.Deadline() + time.Sleep(time.Until(deadline) + 50*time.Millisecond) + return stream.Send(&pingv1.CountUpResponse{Number: 1}) +} + +// A server whose deadline expires must still be able to say so. The terminal +// write runs detached from the RPC's context for exactly this reason: writing +// under the expired one fails, and the peer is left with a dead connection and +// no verdict, which it can only report as a transport failure. +func TestServerReportsItsOwnExpiredDeadline(t *testing.T) { + t.Parallel() + for _, test := range []struct { + name string + handler pingv1connect.PingServiceHandler + // withoutEnd leaves out the client's C, so the deadline fires while + // the server is still waiting for the request stream to end. + withoutEnd bool + }{ + {name: "handler returns at the deadline", handler: slowDeadlineServer{}}, + // A write under the expired context must neither tear down the + // connection nor count as the opening M. + {name: "handler sends after the deadline", handler: lateSendServer{}}, + {name: "request stream never ends", handler: slowDeadlineServer{}, withoutEnd: true}, + } { + t.Run(test.name, func(t *testing.T) { + t.Parallel() + httpServer := newServerFor(t, test.handler) + // A raw client, so that only the server's deadline is in play: the + // Go client derives the server's deadline from its own, and always + // hears its own fire first. + url := "ws" + strings.TrimPrefix(httpServer.URL, "http") + + pingv1connect.PingServiceCountUpProcedure + "?connect-timeout-ms=200" + conn, res, err := websocket.Dial(t.Context(), url, &websocket.DialOptions{ + HTTPClient: httpServer.Client(), + Subprotocols: []string{"connectrpc.1+proto"}, + }) + if res != nil && res.Body != nil { + _ = res.Body.Close() + } + assert.Nil(t, err) + t.Cleanup(func() { _ = conn.CloseNow() }) + sendJSONMessage(t, conn, wireMetadata, []byte("[]")) + sendProtoBody(t, conn, &pingv1.CountUpRequest{Number: 1}) + if !test.withoutEnd { + sendJSONMessage(t, conn, wireClientEndStream, nil) + } + + data := readServerOpening(t, conn) + // An S message carrying the verdict, not a mute close. + assert.True(t, len(data) > 5) + assert.Equal(t, data[0], wireServerEndStream) + assert.True(t, strings.Contains(string(data), "deadline_exceeded")) + }) + } +} + +// newBidiClientWithTimeouts builds a plain WebSocket-backed client for the +// deadline tests, which care about time rather than about routing. +func newBidiClientWithTimeouts(tb testing.TB) pingv1connect.PingServiceClient { + tb.Helper() + httpServer := newHybridServer(tb, pingServer{}) + transport := connecthttp.NewTransport( + httpServer.Client(), + httpServer.URL, + connecthttp.WithWebSocket(connecthttp.SelectStreaming), + ) + return pingv1connect.NewPingServiceClient(connect.NewClient(transport)) +} + +// A stream that is slow but never idle for longer than its deadline must run +// to completion. The deadline bounds the whole RPC, not the gap between +// messages, and nothing in the transport may shorten it. +func TestSlowStreamSurvivesWithinItsDeadline(t *testing.T) { + t.Parallel() + client := newBidiClientWithTimeouts(t) + ctx, cancel := context.WithTimeout(t.Context(), 10*time.Second) + defer cancel() + + stream, err := client.CumSum(ctx) + assert.Nil(t, err) + var want int64 + for i := int64(1); i <= 5; i++ { + time.Sleep(120 * time.Millisecond) + assert.Nil(t, stream.Send(&pingv1.CumSumRequest{Number: i})) + want += i + response, err := stream.Receive() + assert.Nil(t, err) + assert.Equal(t, response.Sum, want) + } + + assert.Nil(t, stream.CloseSend()) + _, err = stream.Receive() + assert.True(t, errors.Is(err, io.EOF)) + assert.Nil(t, stream.Close()) +} + +// With no deadline anywhere, an idle stream must stay open. There is no +// keep-alive and no idle timeout in this transport; a stream that died here +// would mean something had grown one. +func TestIdleStreamWithoutDeadlineStaysAlive(t *testing.T) { + t.Parallel() + client := newBidiClientWithTimeouts(t) + + stream, err := client.CumSum(t.Context()) + assert.Nil(t, err) + assert.Nil(t, stream.Send(&pingv1.CumSumRequest{Number: 4})) + response, err := stream.Receive() + assert.Nil(t, err) + assert.Equal(t, response.Sum, int64(4)) + + // Idle long enough that an accidental short timeout would trip. The server + // spends this blocked in Receive. + time.Sleep(1500 * time.Millisecond) + + assert.Nil(t, stream.Send(&pingv1.CumSumRequest{Number: 6})) + response, err = stream.Receive() + assert.Nil(t, err) + assert.Equal(t, response.Sum, int64(10)) + + assert.Nil(t, stream.CloseSend()) + assert.Nil(t, stream.Close()) +} + +// The other half of the same property: a stream that goes idle with a deadline +// must fail when the deadline arrives, and not before. Only the lower bound is +// asserted; a loaded machine can be late, but it must never be early. +func TestIdleStreamFailsAtItsDeadlineAndNotBefore(t *testing.T) { + t.Parallel() + client := newBidiClientWithTimeouts(t) + const timeout = 900 * time.Millisecond + ctx, cancel := context.WithTimeout(t.Context(), timeout) + defer cancel() + + stream, err := client.CumSum(ctx) + assert.Nil(t, err) + // Make progress first, so the failure cannot be blamed on a stream that + // never worked. + assert.Nil(t, stream.Send(&pingv1.CumSumRequest{Number: 2})) + response, err := stream.Receive() + assert.Nil(t, err) + assert.Equal(t, response.Sum, int64(2)) + + start := time.Now() + _, err = stream.Receive() + elapsed := time.Since(start) + + assert.NotNil(t, err) + assert.Equal(t, connect.CodeOf(err), connect.CodeDeadlineExceeded) + // Generous: the send and first receive consumed some of the budget, so the + // blocked read cannot have waited the full timeout. + assert.True(t, elapsed > timeout/2) + _ = stream.Close() +} + +// The Go client must put its deadline where the protocol says it goes. Nothing +// caught the header-only client for a long while, because every test that +// checked the deadline drove the wire by hand and every test that used the Go +// client had this server on the other end, which accepted both. +func TestGoClientSendsTheTimeoutQueryParameter(t *testing.T) { + t.Parallel() + queries := make(chan string, 1) + mux := http.NewServeMux() + mux.Handle("/", http.HandlerFunc(func(_ http.ResponseWriter, request *http.Request) { + select { + case queries <- request.URL.RawQuery: + default: + } + })) + httpServer := httptest.NewServer(mux) + t.Cleanup(httpServer.Close) + + transport := connecthttp.NewTransport( + httpServer.Client(), + httpServer.URL, + connecthttp.WithWebSocket(connecthttp.SelectAll), + ) + client := pingv1connect.NewPingServiceClient(connect.NewClient(transport)) + + ctx, cancel := context.WithTimeout(t.Context(), 30*time.Second) + defer cancel() + // The handshake fails — this server never upgrades — but the request it + // refused is the one under test. + _, _ = client.Ping(ctx, &pingv1.PingRequest{Number: 1}) + + select { + case query := <-queries: + values, parseErr := url.ParseQuery(query) + assert.Nil(t, parseErr) + millis, convErr := strconv.Atoi(values.Get("connect-timeout-ms")) + assert.Nil(t, convErr) + assert.True(t, millis > 29_000) + assert.True(t, millis <= 30_000) + case <-time.After(5 * time.Second): + t.Fatal("the client never sent a handshake") + } +} + +// A context with no deadline sends no parameter at all, rather than a zero +// that would mean an instantly expired RPC. +func TestGoClientOmitsTheParameterWithoutADeadline(t *testing.T) { + t.Parallel() + queries := make(chan string, 1) + mux := http.NewServeMux() + mux.Handle("/", http.HandlerFunc(func(_ http.ResponseWriter, request *http.Request) { + select { + case queries <- request.URL.RawQuery: + default: + } + })) + httpServer := httptest.NewServer(mux) + t.Cleanup(httpServer.Close) + + transport := connecthttp.NewTransport( + httpServer.Client(), + httpServer.URL, + connecthttp.WithWebSocket(connecthttp.SelectAll), + ) + client := pingv1connect.NewPingServiceClient(connect.NewClient(transport)) + _, _ = client.Ping(context.Background(), &pingv1.PingRequest{Number: 1}) + + select { + case query := <-queries: + assert.Equal(t, query, "") + case <-time.After(5 * time.Second): + t.Fatal("the client never sent a handshake") + } +} + +// wsTestReadTimeout bounds a raw-wire read. It is a backstop against a hang, +// not a latency assertion, so it is far longer than any exchange here needs. +const wsTestReadTimeout = 10 * time.Second + +// readContext bounds one read. tb.Context() alone is cancelled when the test +// ends, which a test blocked in a read cannot reach: it would wait out the +// whole package's timeout and take every other test down with it. +func readContext(tb testing.TB) (context.Context, context.CancelFunc) { + tb.Helper() + return context.WithTimeout(tb.Context(), wsTestReadTimeout) +} + +// readServerOpening reads the server's M message, which opens every response +// stream, and returns the message after it. A test asserting on the server's +// first *interesting* message goes through here, so the opening M is checked +// rather than skipped. +// +// A failed read is fatal: everything after it reads a message that was never +// received, and the assert helpers here do not stop the test. +func readServerOpening(tb testing.TB, conn *websocket.Conn) []byte { + tb.Helper() + ctx, cancel := readContext(tb) + defer cancel() + _, opening, err := conn.Read(ctx) + if err != nil { + tb.Fatalf("read the server's opening M: %v", err) + } + if len(opening) == 0 { + tb.Fatal("opening message carries no marker") + } + assert.Equal(tb, opening[0], wireMetadata) + _, data, err := conn.Read(ctx) + if err != nil { + tb.Fatalf("read the message after the opening M: %v", err) + } + return data +} diff --git a/internal/wstransport/trailers_ext_test.go b/internal/wstransport/trailers_ext_test.go new file mode 100644 index 00000000..ae95b3f8 --- /dev/null +++ b/internal/wstransport/trailers_ext_test.go @@ -0,0 +1,110 @@ +// Copyright 2021-2026 The Connect Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package wstransport_test + +import ( + "context" + "errors" + "io" + "net/http" + "net/http/httptest" + "testing" + + "connectrpc.com/connect/v2" + "connectrpc.com/connect/v2/connecthttp" + "connectrpc.com/connect/v2/internal/assert" + pingv1 "connectrpc.com/connect/v2/internal/gen/connect/ping/v1" + "connectrpc.com/connect/v2/internal/gen/connect/ping/v1/pingv1connect" +) + +const trailerKey = "Acme-Trailer" + +// trailerServer sets a response trailer on every RPC. +type trailerServer struct { + pingv1connect.UnimplementedPingServiceHandler +} + +func (s trailerServer) setTrailer(ctx context.Context) { + if info, ok := connect.CallInfoForServerContext(ctx); ok { + info.ResponseTrailer().Set(trailerKey, "set-by-handler") + } +} + +func (s trailerServer) Ping(ctx context.Context, req *pingv1.PingRequest) (*pingv1.PingResponse, error) { + s.setTrailer(ctx) + return &pingv1.PingResponse{Number: req.Number}, nil +} + +func (s trailerServer) CumSum(ctx context.Context, stream pingv1connect.PingServiceCumSumServerStream) error { + s.setTrailer(ctx) + for { + req, err := stream.Receive() + if errors.Is(err, io.EOF) { + return nil + } + if err != nil { + return err + } + if err := stream.Send(&pingv1.CumSumResponse{Sum: req.Number}); err != nil { + return err + } + } +} + +func newTrailerClient(tb testing.TB, handler trailerServer) pingv1connect.PingServiceClient { + tb.Helper() + server := connect.NewServer() + pingv1connect.RegisterPingServiceHandler(server, handler) + mux := http.NewServeMux() + connecthttp.Mount(mux, server) + httpServer := httptest.NewServer(mux) + tb.Cleanup(httpServer.Close) + + transport := connecthttp.NewTransport( + httpServer.Client(), + httpServer.URL, + connecthttp.WithWebSocket(connecthttp.SelectAll), + ) + return pingv1connect.NewPingServiceClient(connect.NewClient(transport)) +} + +// Trailers a handler sets must reach the caller on a successful unary call. +func TestUnaryTrailersOverWebSocket(t *testing.T) { + t.Parallel() + client := newTrailerClient(t, trailerServer{}) + ctx, info := connect.NewClientContext(t.Context()) + res, err := client.Ping(ctx, &pingv1.PingRequest{Number: 7}) + assert.Nil(t, err) + assert.Equal(t, res.Number, int64(7)) + assert.Equal(t, info.ResponseTrailer().Get(trailerKey), "set-by-handler") +} + +// The streaming case, where the caller reads to io.EOF and so does consume the +// end-of-stream message. +func TestStreamingTrailersOverWebSocket(t *testing.T) { + t.Parallel() + client := newTrailerClient(t, trailerServer{}) + ctx, info := connect.NewClientContext(t.Context()) + stream, err := client.CumSum(ctx) + assert.Nil(t, err) + assert.Nil(t, stream.Send(&pingv1.CumSumRequest{Number: 3})) + _, err = stream.Receive() + assert.Nil(t, err) + assert.Nil(t, stream.CloseSend()) + _, err = stream.Receive() + assert.True(t, errors.Is(err, io.EOF)) + assert.Nil(t, stream.Close()) + assert.Equal(t, info.ResponseTrailer().Get(trailerKey), "set-by-handler") +} diff --git a/internal/wstransport/upgrade.go b/internal/wstransport/upgrade.go new file mode 100644 index 00000000..535ef59d --- /dev/null +++ b/internal/wstransport/upgrade.go @@ -0,0 +1,421 @@ +// Copyright 2021-2026 The Connect Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package wstransport + +import ( + "context" + "net/http" + "net/url" + "slices" + "strings" + "time" + + "connectrpc.com/connect/v2" + "connectrpc.com/connect/v2/connectproto" + "github.com/coder/websocket" +) + +// hijackerHelp is returned when the listener cannot hijack the connection, +// which is the usual symptom of an h2c-only server. +const hijackerHelp = "Connect over WebSocket requires the HTTP listener to support http.Hijacker; " + + "see https://connectrpc.com/docs/go/deployment/#h2c for enabling HTTP/1.1" + +// SessionInfo describes a connection that has completed the WebSocket +// handshake. Every field is resolved before the 101 response, because HTTP +// headers cannot be added once the connection is upgraded. +type SessionInfo struct { + // Codec is the codec negotiated through the WebSocket subprotocol. Bodies + // in both directions use it, in the frame type it calls for (§6.1). + Codec connect.Codec + // Request is the HTTP request that carried the upgrade. Its body has been + // consumed by the handshake; it is provided for headers, URL, context, and + // the client's address (RemoteAddr). + Request *http.Request + // OnProtocolError observes a client's framing mistakes; see + // [WithServerProtocolErrorHandler]. It is nil unless one was registered. + OnProtocolError ServerProtocolErrorHandler + // MaxTimeout bounds the RPC; see [WithMaxTimeout]. Zero means no bound. + MaxTimeout time.Duration + // ReadMaxBytes and SendMaxBytes are the size limits configured on the + // handler. They travel with the connection rather than being held by the + // Session so that a Session supplied through WithSession is configured by + // the same options as the handshake, with no second place for them to live + // and disagree. Zero means no limit. + ReadMaxBytes int + SendMaxBytes int + // InfrastructureHeaders names the request headers this deployment's own + // proxies set, which a client may therefore not send in a Leading-Metadata + // message. A trailing "*" matches any suffix. See WithInfrastructureHeaders. + InfrastructureHeaders []string + // KeepAliveInterval is how often the session pings the client; see + // [WithKeepAlive]. Zero sends no Pings. + KeepAliveInterval time.Duration + // KeepAliveTimeout is how long the client may stay silent; see + // [WithKeepAliveTimeout]. + KeepAliveTimeout time.Duration + // HandshakeTimeout bounds the wait for the client's opening M message; + // see [WithHandshakeTimeout]. Zero means no bound. + HandshakeTimeout time.Duration + // Procedure is the procedure this connection calls; see [WithProcedure]. + // Empty means the request path. + Procedure string + // TransportInfo is what [connect.CallInfo.TransportInfo] carries; see + // [WithTransportInfo]. + TransportInfo any + // drain caps what the closing handshake reads; see drainLimiter. + drain *drainLimiter + // heartbeat carries the peer's PINGs and PONGs to the session's reader. + heartbeat *heartbeat +} + +// Session serves RPCs on an upgraded WebSocket connection. Serve reads +// messages from conn, builds a [connect.ServerStream] per logical stream, and +// dispatches each through [connect.Server.Call]. It owns conn and closes it. +// +// Serve returns when the connection ends. Its error is logged, not sent: the +// HTTP response is already committed by the time it runs. +type Session interface { + Serve(ctx context.Context, server *connect.Server, conn *websocket.Conn, info SessionInfo) error +} + +// SessionFunc adapts a function to the [Session] interface. +type SessionFunc func(ctx context.Context, server *connect.Server, conn *websocket.Conn, info SessionInfo) error + +// Serve implements [Session]. +func (f SessionFunc) Serve(ctx context.Context, server *connect.Server, conn *websocket.Conn, info SessionInfo) error { + return f(ctx, server, conn, info) +} + +// Upgrade returns an [http.Handler] that serves WebSocket RPCs for server and +// delegates every other request to next. It lets one route carry both +// transports, so WebSocket streams and plain HTTP unary calls share a URL. +// +// The codec is negotiated before the handshake and reported on [SessionInfo]. +// Message compression is the WebSocket transport's own permessage-deflate, not +// a Connect content encoding. A nil next responds 404 to non-WebSocket requests. +// +// RPCs are served by the [Session] from [WithSession], or by a default one +// built from these same options. +func Upgrade(server *connect.Server, next http.Handler, options ...ServerOption) http.Handler { + opts := defaultOptions() + for _, opt := range options { + opt.applyToServer(&opts) + } + serve := opts.session + if serve == nil { + serve = &session{} + } + // §4.3: a server MUST support JSON, so a client that offers it can always + // connect, whatever else the codecs were narrowed to. + if _, ok := newCodecRegistry(opts.codecs).get(connect.CodecNameJSON); !ok { + opts.codecs = append(slices.Clone(opts.codecs), connectproto.NewJSONCodec()) + } + return &upgradeHandler{ + server: server, + session: serve, + next: next, + codecs: newCodecRegistry(opts.codecs), + carried: carriedCodecs(opts.codecs), + opts: &opts, + shutdowns: newShutdownTracker(), + } +} + +type upgradeHandler struct { + server *connect.Server + session Session + next http.Handler + codecs registry[connect.Codec] + // carried is the registered codecs a token can name, in registration + // order, for the 400 body. + carried []connect.Codec + opts *options + // shutdowns ends this handler's sessions when their server shuts down. + shutdowns *shutdownTracker +} + +func (h *upgradeHandler) ServeHTTP(responseWriter http.ResponseWriter, request *http.Request) { + // Ahead of the IsUpgrade gate, which only recognizes GET: an Extended + // CONNECT would otherwise fall through to the HTTP handler and be answered + // as an ordinary RPC. RFC 8441 carries WebSocket over HTTP/2 and this + // binding does not adopt it (§4.1), so the request is refused instead. + if request.Method == http.MethodConnect { + http.Error( + responseWriter, + "this server does not support Extended CONNECT (RFC 8441); "+ + "upgrade over HTTP/1.1 instead", + http.StatusNotImplemented, + ) + return + } + if !IsUpgrade(request) || h.session == nil { + if h.next == nil { + http.NotFound(responseWriter, request) + return + } + h.next.ServeHTTP(responseWriter, request) + return + } + subprotocol, codecName, admitted := h.admit(responseWriter, request) + if !admitted { + return + } + codec, _ := h.codecs.get(codecName) + drain := newDrainLimiter(messageReadLimit(h.opts.readMaxBytes)) + beat := &heartbeat{} + conn, upgradeErr := websocket.Accept( + &drainResponseWriter{ResponseWriter: responseWriter, limiter: drain}, + request, + h.acceptOptions(subprotocol, beat), + ) + if upgradeErr != nil { + // Accept has already written the error response. + return + } + info := h.sessionInfo(request, codec, drain, beat) + ctx, untrack := h.shutdowns.track(request.Context()) + defer untrack() + if err := h.session.Serve(ctx, h.server, conn, info); err != nil { + h.opts.logger.Error( + "websocket session ended with error", + "procedure", info.Procedure, + "peer", request.RemoteAddr, + "error", err, + ) + } +} + +// admit decides whether to complete an upgrade, and picks the subprotocol and +// codec when it does. A refusal has already been written to responseWriter. +func (h *upgradeHandler) admit( + responseWriter http.ResponseWriter, + request *http.Request, +) (subprotocol, codecName string, admitted bool) { + // Checked first: a listener that cannot hijack is a deployment fault, and + // reporting it as a client error would send the operator down the wrong path. + if !canHijack(responseWriter) { + http.Error(responseWriter, hijackerHelp, http.StatusInternalServerError) + return "", "", false + } + // §4.4 before §4.3, so a cross-origin handshake is refused as one whatever + // it offered. Accept is told to skip its own check, which would run too + // late; WithCheckOrigin replaces this one rather than adding to it. + checkOrigin := h.opts.checkOrigin + if checkOrigin == nil { + checkOrigin = isSameOrigin + } + if !checkOrigin(request) { + http.Error(responseWriter, "origin not allowed", http.StatusForbidden) + return "", "", false + } + // §4.3: an upgrade that offers no token this server can serve is refused + // before the handshake completes, whether or not it offered a Connect token. + subprotocol, codecName, negotiated := negotiateSubprotocol( + requestedSubprotocols(request), + h.servesCodec, + ) + if !negotiated { + http.Error( + responseWriter, + "no supported Connect subprotocol in Sec-WebSocket-Protocol; this server speaks "+ + strings.Join(h.servedSubprotocols(), ", "), + http.StatusBadRequest, + ) + return "", "", false + } + return subprotocol, codecName, true +} + +func (h *upgradeHandler) acceptOptions(subprotocol string, beat *heartbeat) *websocket.AcceptOptions { + return &websocket.AcceptOptions{ + // Accept echoes Sec-WebSocket-Protocol itself from the list it is given. + Subprotocols: []string{subprotocol}, + // The origin policy has already run. + InsecureSkipVerify: true, + // §4.6: a peer's own PINGs and PONGs are frames from it too. + OnPingReceived: beat.onPing, + OnPongReceived: beat.onPong, + // Compression is the transport's job, not the framing layer's: browsers + // get permessage-deflate for free and cannot negotiate a Connect-level + // encoding on an upgrade request. + // + // NoContextTakeover is required rather than preferred. A compression + // context shared across messages leaks plaintext across trust + // boundaries (the CRIME/BREACH family), and the server may impose the + // parameter unilaterally under RFC 7692 §7.1.1, so a client offering + // plain permessage-deflate still gets a per-message context. + CompressionMode: h.opts.compressionMode(), + CompressionThreshold: h.opts.compressionThreshold(), + } +} + +func (h *upgradeHandler) sessionInfo( + request *http.Request, + codec connect.Codec, + drain *drainLimiter, + beat *heartbeat, +) SessionInfo { + procedure := h.opts.procedure + if procedure == "" { + procedure = request.URL.Path + } + var transportInfo any + if h.opts.transportInfo != nil { + transportInfo = h.opts.transportInfo(request) + } + return SessionInfo{ + Procedure: procedure, + TransportInfo: transportInfo, + HandshakeTimeout: h.opts.handshakeTimeout, + Codec: codec, + Request: request, + MaxTimeout: h.opts.maxTimeout, + ReadMaxBytes: h.opts.readMaxBytes, + SendMaxBytes: h.opts.sendMaxBytes, + InfrastructureHeaders: h.opts.infrastructureHeaders, + OnProtocolError: h.opts.onProtocolError, + drain: drain, + heartbeat: beat, + KeepAliveInterval: h.opts.keepAliveInterval, + KeepAliveTimeout: h.opts.keepAliveTimeout, + } +} + +// isSameOrigin is the default origin policy (§4.4): a request without Origin is +// not from a browser, and one with it must name the request's own host and +// port, compared case-insensitively and exactly as written. +func isSameOrigin(request *http.Request) bool { + origin := request.Header.Get("Origin") + if origin == "" { + return true + } + parsed, err := url.Parse(origin) + if err != nil { + return false + } + return parsed.Host != "" && strings.EqualFold(parsed.Host, request.Host) +} + +// canHijack reports whether responseWriter, or one it wraps, can hijack the +// connection, which is how [http.ResponseController] finds a Hijacker too. +func canHijack(responseWriter http.ResponseWriter) bool { + for { + if _, ok := responseWriter.(http.Hijacker); ok { + return true + } + unwrapper, ok := responseWriter.(interface{ Unwrap() http.ResponseWriter }) + if !ok { + return false + } + responseWriter = unwrapper.Unwrap() + } +} + +// IsUpgrade reports whether request is a WebSocket upgrade, so callers can +// route it away from the HTTP handlers before reading a body. +func IsUpgrade(request *http.Request) bool { + if request.Method != http.MethodGet { + return false + } + if !headerContainsToken(request.Header, wsHeaderConnection, "upgrade") { + return false + } + return strings.EqualFold(request.Header.Get(wsHeaderUpgrade), "websocket") +} + +// servesCodec reports whether this server can encode and decode bodies with +// the named codec. JSON is always among them (§4.3). +func (h *upgradeHandler) servesCodec(name string) bool { + _, ok := h.codecs.get(name) + return ok +} + +// servedSubprotocols lists the tokens a client could offer, for the 400 body. +func (h *upgradeHandler) servedSubprotocols() []string { + tokens := make([]string, 0, len(h.carried)) + for _, codec := range h.carried { + tokens = append(tokens, subprotocolForCodec(codec.Name())) + } + return tokens +} + +// requestedSubprotocols parses the client's Sec-WebSocket-Protocol offer, in +// the order it was offered. +func requestedSubprotocols(request *http.Request) []string { + var protocols []string + for _, value := range request.Header.Values(wsHeaderProtocol) { + for part := range strings.SplitSeq(value, ",") { + if token := strings.TrimSpace(part); token != "" { + protocols = append(protocols, token) + } + } + } + return protocols +} + +// negotiateSubprotocol picks the first offered subprotocol this server both +// recognizes and can serve, as RFC 6455 §4.1 negotiation does. Tokens it does +// not recognize, and recognized tokens whose codec it lacks, are skipped, so a +// client offering JSON first still reaches a Protobuf-only server through its +// second choice. +func negotiateSubprotocol( + requested []string, + supported func(string) bool, +) (subprotocol, codecName string, ok bool) { + for _, name := range requested { + codec := codecForSubprotocol(name) + if codec != "" && supported(codec) { + return name, codec, true + } + } + return "", "", false +} + +func headerContainsToken(header http.Header, key, token string) bool { + for _, value := range header.Values(key) { + for part := range strings.SplitSeq(value, ",") { + if strings.EqualFold(strings.TrimSpace(part), token) { + return true + } + } + } + return false +} + +// registry is a name-keyed lookup for codecs. +type registry[T interface{ Name() string }] struct { + byName map[string]T +} + +func newCodecRegistry(codecs []connect.Codec) registry[connect.Codec] { + return newRegistry(codecs) +} + +func newRegistry[T interface{ Name() string }](entries []T) registry[T] { + reg := registry[T]{byName: make(map[string]T, len(entries))} + for _, entry := range entries { + name := entry.Name() + if _, dup := reg.byName[name]; dup { + continue + } + reg.byName[name] = entry + } + return reg +} + +func (r registry[T]) get(name string) (T, bool) { + entry, ok := r.byName[name] + return entry, ok +} diff --git a/internal/wstransport/upgrade_ext_test.go b/internal/wstransport/upgrade_ext_test.go new file mode 100644 index 00000000..5109c5c6 --- /dev/null +++ b/internal/wstransport/upgrade_ext_test.go @@ -0,0 +1,439 @@ +// Copyright 2021-2026 The Connect Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package wstransport_test + +import ( + "bufio" + "context" + "errors" + "log/slog" + "net" + "net/http" + "net/http/httptest" + "strings" + "sync" + "sync/atomic" + "testing" + "time" + + "connectrpc.com/connect/v2" + "connectrpc.com/connect/v2/connecthttp" + "connectrpc.com/connect/v2/internal/assert" + pingv1 "connectrpc.com/connect/v2/internal/gen/connect/ping/v1" + "connectrpc.com/connect/v2/internal/gen/connect/ping/v1/pingv1connect" + "connectrpc.com/connect/v2/internal/wstransport" + "github.com/coder/websocket" +) + +const pingProcedure = "/connect.ping.v1.PingService/CumSum" + +// newUpgradeHandler builds the Upgrade handler alone, with no HTTP fallthrough +// behind it, so a rejected handshake is answered by Upgrade itself. +func newUpgradeHandler(tb testing.TB, options ...wstransport.ServerOption) http.Handler { + tb.Helper() + server := connect.NewServer() + pingv1connect.RegisterPingServiceHandler(server, pingServer{}) + return wstransport.Upgrade(server, nil, options...) +} + +// hijackableRecorder satisfies http.Hijacker so a request reaches the checks +// that run after it. Hijack itself is never called: every test here is +// rejected before the handshake. +type hijackableRecorder struct { + *httptest.ResponseRecorder +} + +func (h hijackableRecorder) Hijack() (net.Conn, *bufio.ReadWriter, error) { + return nil, nil, errors.New("wstransport_test: hijack not supported") +} + +func newHijackableRecorder() hijackableRecorder { + return hijackableRecorder{ResponseRecorder: httptest.NewRecorder()} +} + +// upgradeRequest builds a syntactically valid WebSocket upgrade so each test +// can invalidate exactly one thing. +func upgradeRequest(tb testing.TB, subprotocol string) *http.Request { + tb.Helper() + req := httptest.NewRequestWithContext(tb.Context(), http.MethodGet, pingProcedure, nil) + req.Header.Set("Connection", "Upgrade") + req.Header.Set("Upgrade", "websocket") + req.Header.Set("Sec-WebSocket-Version", "13") + req.Header.Set("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==") + if subprotocol != "" { + req.Header.Set("Sec-WebSocket-Protocol", subprotocol) + } + return req +} + +// httptest.ResponseRecorder does not implement http.Hijacker, which is exactly +// the h2c-only shape the handler must diagnose. +func TestUpgradeRejectsUnhijackableListener(t *testing.T) { + t.Parallel() + recorder := httptest.NewRecorder() + newUpgradeHandler(t).ServeHTTP(recorder, upgradeRequest(t, "connectrpc.1+proto")) + assert.Equal(t, recorder.Code, http.StatusInternalServerError) + // The message must name h2c: an operator who sees a bare 500 looks in the + // wrong place. + assert.True(t, len(recorder.Body.String()) > 0) + assert.True(t, containsAll(recorder.Body.String(), "http.Hijacker", "h2c")) +} + +func TestUpgradeRejectsDisallowedOrigin(t *testing.T) { + t.Parallel() + handler := newUpgradeHandler(t, wstransport.WithCheckOrigin( + func(*http.Request) bool { return false }, + )) + recorder := newHijackableRecorder() + handler.ServeHTTP(recorder, upgradeRequest(t, "connectrpc.1+proto")) + assert.Equal(t, recorder.Code, http.StatusForbidden) +} + +// RFC 8441's Extended CONNECT carries WebSocket over HTTP/2, which this binding +// does not adopt. Left to fall through it reaches the HTTP handler, which would +// run the procedure the client meant to reach over a WebSocket it never got. +func TestUpgradeRefusesExtendedConnect(t *testing.T) { + t.Parallel() + recorder := newHijackableRecorder() + request := httptest.NewRequestWithContext(t.Context(), http.MethodConnect, pingProcedure, nil) + request.Header.Set("Connection", "Upgrade") + request.Header.Set("Upgrade", "websocket") + request.Header.Set("Sec-WebSocket-Version", "13") + request.Header.Set("Sec-WebSocket-Protocol", "connectrpc.1+proto") + + newUpgradeHandler(t).ServeHTTP(recorder, request) + assert.Equal(t, recorder.Code, http.StatusNotImplemented) + assert.True(t, strings.Contains(recorder.Body.String(), "Extended CONNECT")) +} + +// A request that is not an upgrade must fall through, not be rejected. +func TestUpgradeIgnoresNonWebSocketRequest(t *testing.T) { + t.Parallel() + recorder := newHijackableRecorder() + req := httptest.NewRequestWithContext(t.Context(), http.MethodPost, pingProcedure, nil) + newUpgradeHandler(t).ServeHTTP(recorder, req) + // Mount passes nil for next, so a non-upgrade is a 404 rather than a 400: + // the handler declined it instead of failing it. + assert.Equal(t, recorder.Code, http.StatusNotFound) +} + +func containsAll(haystack string, needles ...string) bool { + for _, needle := range needles { + if !strings.Contains(haystack, needle) { + return false + } + } + return true +} + +// WithSession still allows a Session of one's own, which is the reason the +// extension point exists. +func TestWithSessionReplacesTheDefault(t *testing.T) { + t.Parallel() + var served atomic.Int64 + server := connect.NewServer() + pingv1connect.RegisterPingServiceHandler(server, pingServer{}) + inner := wstransport.NewSession() + counting := wstransport.SessionFunc(func( + ctx context.Context, + srv *connect.Server, + conn *websocket.Conn, + info wstransport.SessionInfo, + ) error { + served.Add(1) + return inner.Serve(ctx, srv, conn, info) + }) + mux := http.NewServeMux() + // WithSession has no public equivalent — replacing the serve loop would + // put coder/websocket types in connecthttp's API — so this reaches the + // internal option directly. + mountBoth(mux, server, wstransport.WithSession(counting)) + httpServer := httptest.NewServer(mux) + t.Cleanup(httpServer.Close) + + transport := connecthttp.NewTransport( + httpServer.Client(), + httpServer.URL, + connecthttp.WithWebSocket(connecthttp.SelectStreaming), + ) + client := pingv1connect.NewPingServiceClient(connect.NewClient(transport)) + + stream, err := client.CumSum(t.Context()) + assert.Nil(t, err) + assert.Nil(t, stream.Send(&pingv1.CumSumRequest{Number: 2})) + response, err := stream.Receive() + assert.Nil(t, err) + assert.Equal(t, response.Sum, int64(2)) + assert.Nil(t, stream.CloseSend()) + assert.Nil(t, stream.Close()) + assert.Equal(t, served.Load(), int64(1)) +} + +// logSink collects slog output from the session's own goroutine and says when +// a record has landed, so a reader never races the write. +type logSink struct { + mu sync.Mutex + records []string + wrote chan struct{} +} + +func newLogSink() *logSink { + return &logSink{wrote: make(chan struct{}, 1)} +} + +func (s *logSink) Write(record []byte) (int, error) { + s.mu.Lock() + s.records = append(s.records, string(record)) + s.mu.Unlock() + select { + case s.wrote <- struct{}{}: + default: + } + return len(record), nil +} + +func (s *logSink) text() string { + s.mu.Lock() + defer s.mu.Unlock() + return strings.Join(s.records, "") +} + +// A session that fails must say so where an operator will see it. Nothing else +// reports it: the peer already has its verdict, and Serve's error is dropped. +func TestSessionErrorIsLogged(t *testing.T) { + t.Parallel() + sink := newLogSink() + server := connect.NewServer() + pingv1connect.RegisterPingServiceHandler(server, pingServer{}) + failing := wstransport.SessionFunc(func( + _ context.Context, _ *connect.Server, conn *websocket.Conn, _ wstransport.SessionInfo, + ) error { + // Upgrade hands the connection to the Session and never takes it back, + // so a Session that returns without closing strands the peer. + _ = conn.CloseNow() + return errors.New("session gave up") + }) + mux := http.NewServeMux() + mountBoth(mux, server, + wstransport.WithSession(failing), + wstransport.WithLogger(slog.New(slog.NewTextHandler(sink, nil))), + ) + httpServer := httptest.NewServer(mux) + t.Cleanup(httpServer.Close) + + transport := connecthttp.NewTransport( + httpServer.Client(), + httpServer.URL, + connecthttp.WithWebSocket(connecthttp.SelectStreaming), + ) + client := pingv1connect.NewPingServiceClient(connect.NewClient(transport)) + stream, err := client.CumSum(t.Context()) + assert.Nil(t, err) + _ = stream.Send(&pingv1.CumSumRequest{Number: 1}) + _, _ = stream.Receive() + _ = stream.Close() + + select { + case <-sink.wrote: + case <-time.After(10 * time.Second): + t.Fatal("the session error was never logged") + } + record := sink.text() + assert.True(t, strings.Contains(record, "session gave up")) + // The procedure and peer are what make one failing connection findable. + assert.True(t, strings.Contains(record, pingv1connect.PingServiceCumSumProcedure)) + assert.True(t, strings.Contains(record, "peer=")) +} + +// A Session supplied through WithSession must be configured by the caller's +// options too. It holds none of its own — the limits arrive on SessionInfo — +// so there is no second place for them to live and disagree. +func TestWithSessionStillGetsTheOptions(t *testing.T) { + t.Parallel() + server := connect.NewServer() + pingv1connect.RegisterPingServiceHandler(server, pingServer{}) + mux := http.NewServeMux() + mountBoth(mux, server, + wstransport.WithReadMaxBytes(1024), + // The explicit default: the shape that silently lost the limits + // while the Session carried its own options. + wstransport.WithSession(wstransport.NewSession()), + ) + httpServer := httptest.NewServer(mux) + t.Cleanup(httpServer.Close) + + transport := connecthttp.NewTransport( + httpServer.Client(), + httpServer.URL, + connecthttp.WithWebSocket(connecthttp.SelectAll), + connecthttp.WithSendMaxBytes(1<<20), + ) + client := pingv1connect.NewPingServiceClient(connect.NewClient(transport)) + + _, err := client.Ping(t.Context(), &pingv1.PingRequest{Text: strings.Repeat("x", 8192)}) + assert.NotNil(t, err) + assert.Equal(t, connect.CodeOf(err), connect.CodeResourceExhausted) +} + +// The limits are on SessionInfo, so a custom Session can read them. +func TestSessionInfoCarriesTheLimits(t *testing.T) { + t.Parallel() + seen := make(chan wstransport.SessionInfo, 1) + inner := wstransport.NewSession() + recording := wstransport.SessionFunc(func( + ctx context.Context, + srv *connect.Server, + conn *websocket.Conn, + info wstransport.SessionInfo, + ) error { + seen <- info + return inner.Serve(ctx, srv, conn, info) + }) + server := connect.NewServer() + pingv1connect.RegisterPingServiceHandler(server, pingServer{}) + mux := http.NewServeMux() + // The limits go through connecthttp, which forwards them; the Session has + // no public equivalent and is supplied directly. + mountBoth(mux, server, + wstransport.WithReadMaxBytes(4096), + wstransport.WithSendMaxBytes(8192), + wstransport.WithSession(recording), + ) + httpServer := httptest.NewServer(mux) + t.Cleanup(httpServer.Close) + + transport := connecthttp.NewTransport( + httpServer.Client(), + httpServer.URL, + connecthttp.WithWebSocket(connecthttp.SelectStreaming), + ) + client := pingv1connect.NewPingServiceClient(connect.NewClient(transport)) + stream, err := client.CumSum(t.Context()) + assert.Nil(t, err) + assert.Nil(t, stream.Send(&pingv1.CumSumRequest{Number: 1})) + _, err = stream.Receive() + assert.Nil(t, err) + assert.Nil(t, stream.CloseSend()) + assert.Nil(t, stream.Close()) + + info := <-seen + assert.Equal(t, info.ReadMaxBytes, 4096) + assert.Equal(t, info.SendMaxBytes, 8192) +} + +// The option types are the point of the split: an option meaningful to one +// side only must not compile against the other. These assertions fail at build +// time if a With* function is retyped into the wrong category. +var ( + // Shared options satisfy both. + _ wstransport.ClientOption = wstransport.WithReadMaxBytes(0) + _ wstransport.ServerOption = wstransport.WithReadMaxBytes(0) + _ wstransport.ClientOption = wstransport.WithSendMaxBytes(0) + _ wstransport.ServerOption = wstransport.WithSendMaxBytes(0) + _ wstransport.ClientOption = wstransport.WithCodecs() + _ wstransport.ServerOption = wstransport.WithCodecs() + _ wstransport.ClientOption = wstransport.WithoutCompression() + _ wstransport.ServerOption = wstransport.WithoutCompression() + _ wstransport.ClientOption = wstransport.WithCompressMinBytes(0) + _ wstransport.ServerOption = wstransport.WithCompressMinBytes(0) + + // Client-only: these have no server meaning, and WithHTTPClient reaching a + // handler used to be silently ignored. The routing options moved to + // connecthttp, which owns the choice between the two transports. + _ wstransport.ClientOption = wstransport.WithHTTPClient(nil) + _ wstransport.ClientOption = wstransport.WithHandshakeTimeout(0) + _ wstransport.ClientOption = wstransport.WithSendCodec("") + _ wstransport.ClientOption = wstransport.WithEagerDial() + + // Server-only. + _ wstransport.ServerOption = wstransport.WithCheckOrigin(nil) + _ wstransport.ServerOption = wstransport.WithSession(nil) + _ wstransport.ServerOption = wstransport.WithLogger(nil) + // The monitoring hooks mirror each other, one per side. + _ wstransport.ServerOption = wstransport.WithServerProtocolErrorHandler(nil) + _ wstransport.ClientOption = wstransport.WithClientProtocolErrorHandler(nil) +) + +// Mount alone must serve every procedure both ways. Which transport carries an +// RPC is the client's choice, so a server that registered only one would +// reject a client that chose the other — which is what the old selector-gated +// Mount did: a plain HTTP client got 404 on a streaming procedure. +func TestMountServesBothTransports(t *testing.T) { + t.Parallel() + server := connect.NewServer() + pingv1connect.RegisterPingServiceHandler(server, pingServer{}) + mux := http.NewServeMux() + connecthttp.Mount(mux, server) + httpServer := httptest.NewServer(mux) + t.Cleanup(httpServer.Close) + + // A plain connecthttp client, which never upgrades. + httpClient := pingv1connect.NewPingServiceClient( + connect.NewClient(connecthttp.NewTransport(httpServer.Client(), httpServer.URL))) + response, err := httpClient.Ping(t.Context(), &pingv1.PingRequest{Number: 3}) + assert.Nil(t, err) + assert.Equal(t, response.Number, int64(3)) + + // A WebSocket client with everything upgraded, including the unary call the + // old Mount would not have registered for WebSocket at all. + transport := connecthttp.NewTransport( + httpServer.Client(), + httpServer.URL, + connecthttp.WithWebSocket(connecthttp.SelectAll), + ) + websocketClient := pingv1connect.NewPingServiceClient(connect.NewClient(transport)) + response, err = websocketClient.Ping(t.Context(), &pingv1.PingRequest{Number: 4}) + assert.Nil(t, err) + assert.Equal(t, response.Number, int64(4)) + + stream, err := websocketClient.CumSum(t.Context()) + assert.Nil(t, err) + assert.Nil(t, stream.Send(&pingv1.CumSumRequest{Number: 5})) + sum, err := stream.Receive() + assert.Nil(t, err) + assert.Equal(t, sum.Sum, int64(5)) + assert.Nil(t, stream.CloseSend()) + assert.Nil(t, stream.Close()) +} + +// One option configures both wires. The direction is what changed when the +// entry points moved: connecthttp owns Mount, so its own options reach the +// WebSocket half rather than the other way round. +func TestMountOptionsReachBothTransports(t *testing.T) { + t.Parallel() + server := connect.NewServer() + pingv1connect.RegisterPingServiceHandler(server, pingServer{}) + mux := http.NewServeMux() + connecthttp.Mount(mux, server, connecthttp.WithReadMaxBytes(1024)) + httpServer := httptest.NewServer(mux) + t.Cleanup(httpServer.Close) + + oversize := strings.Repeat("x", 8192) + + httpClient := pingv1connect.NewPingServiceClient( + connect.NewClient(connecthttp.NewTransport(httpServer.Client(), httpServer.URL))) + _, err := httpClient.Ping(t.Context(), &pingv1.PingRequest{Text: oversize}) + assert.NotNil(t, err) + assert.Equal(t, connect.CodeOf(err), connect.CodeResourceExhausted) + + wsClient := pingv1connect.NewPingServiceClient(connect.NewClient(connecthttp.NewTransport( + httpServer.Client(), + httpServer.URL, + connecthttp.WithWebSocket(connecthttp.SelectAll), + ))) + _, err = wsClient.Ping(t.Context(), &pingv1.PingRequest{Text: oversize}) + assert.NotNil(t, err) + assert.Equal(t, connect.CodeOf(err), connect.CodeResourceExhausted) +} diff --git a/internal/wstransport/websocket.go b/internal/wstransport/websocket.go new file mode 100644 index 00000000..579b6130 --- /dev/null +++ b/internal/wstransport/websocket.go @@ -0,0 +1,453 @@ +// Copyright 2021-2026 The Connect Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// Package wstransport carries Connect RPCs over WebSocket, one RPC per +// connection. Both directions stream at once, which is what makes +// bidirectional streaming work on HTTP/1.1 and in browsers. +// +// The package is internal: Connect is protobuf-first, so which wire carries an +// RPC is an implementation detail. [connectrpc.com/connect/v2/connecthttp] +// owns the public surface — Mount registers this transport alongside HTTP by +// default, and NewTransport routes to it when given a selector. +package wstransport + +import ( + "log/slog" + "net/http" + "time" + + "connectrpc.com/connect/v2" + "connectrpc.com/connect/v2/connectproto" + "github.com/coder/websocket" +) + +const defaultHandshakeTimeout = 10 * time.Second + +// defaultMaxTimeout bounds an RPC that requested no deadline of its own. It is +// generous because a long-lived subscription is the transport's whole point; it +// exists so that a peer cannot hold a connection open forever — including one +// that upgrades and never sends the metadata that opens the stream. Override it +// with [WithMaxTimeout]. +const defaultMaxTimeout = time.Hour + +// defaultReadMaxBytes matches connecthttp's default so that one set of options +// gives both transports the same limit. A stream-type-dependent limit is a +// bug waiting to happen. +const defaultReadMaxBytes = 1024 * 1024 * 4 // 4MiB + +// defaultCompressMinBytes is set for the same reason, and to the value the +// WebSocket library would otherwise pick for itself. Left unset, the two halves +// disagree: the library treats zero as "use my default" and skips messages +// under 512 bytes, while the message writer treats zero as "no minimum" and +// compresses everything. Small payloads usually grow under deflate, so 512 is +// the better answer for both. +const defaultCompressMinBytes = 512 + +// defaultKeepAliveInterval sits at the low end of the 30-60 second idle +// timeout common among proxies and load balancers. +const defaultKeepAliveInterval = 30 * time.Second + +// defaultKeepAliveTimeout is long because a peer whose application stops taking +// messages stops answering Pings too. It still beats TCP's ~15 minutes. +const defaultKeepAliveTimeout = 5 * time.Minute + +// ClientOption configures [NewTransport]. +type ClientOption interface { + applyToClient(*options) +} + +// ServerOption configures [Upgrade]. +type ServerOption interface { + applyToServer(*options) +} + +// Option configures either side. Size limits, codecs, and compression settings +// are Options because both ends of a connection need them; anything meaningful +// to only one side is a [ClientOption] or a [ServerOption], so passing it to +// the wrong constructor is a compile error rather than a setting that is +// silently ignored. +type Option interface { + ClientOption + ServerOption +} + +// WithEagerDial makes NewClientStream complete the handshake before it +// returns, rather than dialing on first use. +// +// Lazy dialing is the default because it lets a stream be created without a +// round trip. A caller that has somewhere else to send the RPC needs the +// handshake's outcome while that choice is still open, though: once a stream +// is returned, an upgrade failure surfaces from Send, by which point falling +// back is no longer possible. connecthttp.WithFallbackOnUpgradeError sets +// this for exactly that reason. +func WithEagerDial() ClientOption { + return clientOptionFunc(func(o *options) { o.eagerDial = true }) +} + +// WithHandshakeTimeout bounds the WebSocket handshake. A server applies it to +// the client's opening M message, which completes the handshake at the +// protocol level: without it, a client that upgrades and then sends nothing +// holds the connection until [WithMaxTimeout]. Zero means no timeout. +func WithHandshakeTimeout(timeout time.Duration) Option { + return optionFunc(func(o *options) { o.handshakeTimeout = timeout }) +} + +// WithProcedure fixes the procedure an [Upgrade] handler serves, as a route +// registered for one procedure does over HTTP. Without it the procedure is the +// request path, which is wrong once a mux serves the route under a prefix. +func WithProcedure(procedure string) ServerOption { + return serverOptionFunc(func(o *options) { o.procedure = procedure }) +} + +// WithTransportInfo sets what [connect.CallInfo.TransportInfo] carries for each +// RPC, built from the handshake request. +func WithTransportInfo(transportInfo func(*http.Request) any) ServerOption { + return serverOptionFunc(func(o *options) { o.transportInfo = transportInfo }) +} + +// WithCheckOrigin replaces the default origin check. +// +// By default a cross-origin handshake is refused: a browser attaches the +// user's cookies to a WebSocket handshake and, unlike fetch, no CORS +// preflight stands in the way, so any page on any site could otherwise open +// an authenticated stream (cross-site WebSocket hijacking). A request with no +// Origin header is allowed, which covers every non-browser client. +// +// Pass a function returning true to accept every origin — appropriate only +// when the endpoint carries no ambient credentials. +func WithCheckOrigin(check func(*http.Request) bool) ServerOption { + return serverOptionFunc(func(o *options) { + if check != nil { + o.checkOrigin = check + } + }) +} + +// WithSession replaces the [Session] that serves RPCs on an upgraded +// connection. The default is built from the same options as the handshake, so +// it needs no configuring; supply one only to change how streams are served — +// to instrument them, or to dispatch differently. Wrapping [NewSession] keeps +// the default behavior underneath. +// +// A nil Session is ignored. +func WithSession(session Session) ServerOption { + return serverOptionFunc(func(o *options) { + if session != nil { + o.session = session + } + }) +} + +// ProtocolFault classifies a peer's framing mistake, so a monitor can tell a +// client that consistently sends unknown markers from one that mismatches a +// frame type once. The Connect code alone cannot: every framing fault is +// Internal, separable only by matching message strings. +type ProtocolFault int + +const ( + // faultNone is the zero value: nothing has been classified. A protocol + // error handler never receives it. + faultNone ProtocolFault = iota + // FaultMarker is a message that is empty, has an unknown marker or one for + // the other direction, or breaks the rules for C. + FaultMarker + // FaultFrameType is a frame whose type does not match its payload: an + // empty body in a text frame, or a message type that is neither. + FaultFrameType + // FaultSizeLimit is a message past the configured read limit. + FaultSizeLimit + // FaultMetadata is a malformed, missing, or repeated M message. + FaultMetadata + // FaultMessageEncoding is a payload the negotiated codec cannot decode. + FaultMessageEncoding + // FaultTextEncoding is a text message that is not valid UTF-8. + FaultTextEncoding +) + +func (f ProtocolFault) String() string { + switch f { + case FaultMarker: + return "marker" + case FaultFrameType: + return "frame_type" + case FaultSizeLimit: + return "size_limit" + case FaultMetadata: + return "metadata" + case FaultMessageEncoding: + return "message_encoding" + case FaultTextEncoding: + return "text_encoding" + case faultNone: + return "unknown" + default: + return "unknown" + } +} + +// ServerProtocolErrorHandler observes a client's framing mistake. It cannot +// change the outcome: the error is reported to the peer and returned to the +// handler either way, so this is for logging, metrics, and rate limiting only. +// +// It runs on the connection's read path, so it must not block or panic. +type ServerProtocolErrorHandler func(SessionInfo, ProtocolFault, *connect.Error) + +// ClientProtocolErrorHandler observes a server's framing mistake. Like its +// server-side twin it cannot change the outcome; the [connect.Spec] says which +// RPC was in flight, the peer being whichever server the transport dials. +// +// It runs on the connection's read path, so it must not block or panic. +type ClientProtocolErrorHandler func(connect.Spec, ProtocolFault, *connect.Error) + +// WithServerProtocolErrorHandler registers a [ServerProtocolErrorHandler]. Use +// it to attribute framing faults to a client — [SessionInfo] carries the +// upgrade request, and so the client's address — which the logger cannot do: a framing fault is +// reported to the peer in the S message and is a successful outcome from the +// session's point of view, so it never reaches [WithLogger]. +func WithServerProtocolErrorHandler(handler ServerProtocolErrorHandler) ServerOption { + return serverOptionFunc(func(o *options) { + if handler != nil { + o.onProtocolError = handler + } + }) +} + +// WithClientProtocolErrorHandler registers a [ClientProtocolErrorHandler], the +// mirror of [WithServerProtocolErrorHandler]: it reports a server that frames +// its responses wrongly. A client has no equivalent of the logger or the +// session wrapper, so without this a framing fault is visible only as the +// Internal error the RPC fails with. +func WithClientProtocolErrorHandler(handler ClientProtocolErrorHandler) ClientOption { + return clientOptionFunc(func(o *options) { + if handler != nil { + o.onClientProtocolError = handler + } + }) +} + +// WithMaxTimeout bounds every RPC the handler serves. It is both the default +// when a client requests no deadline and the ceiling on one that does: the +// effective deadline is the shorter of the two, so a client may ask for less +// time but never more. +// +// Zero means no bound, which lets a peer that opens a connection and then goes +// silent hold it indefinitely. +func WithMaxTimeout(timeout time.Duration) ServerOption { + return serverOptionFunc(func(o *options) { o.maxTimeout = timeout }) +} + +// WithLogger replaces [slog.Default] as the destination for errors that +// surface after the HTTP response is committed. +func WithLogger(logger *slog.Logger) ServerOption { + return serverOptionFunc(func(o *options) { + if logger != nil { + o.logger = logger + } + }) +} + +// WithCodecs replaces the default protobuf binary and JSON codecs. The set is +// replaced entirely, so list every codec you need in one call. A codec is +// reachable only if a WebSocket subprotocol names it. +func WithCodecs(codecs ...connect.Codec) Option { + return optionFunc(func(o *options) { o.codecs = codecs }) +} + +// WithSendCodec selects the codec for outgoing messages by name. It must name +// one of the codecs in the set, and it also selects the WebSocket subprotocol +// the client offers. +func WithSendCodec(name string) ClientOption { + return clientOptionFunc(func(o *options) { o.sendCodec = name }) +} + +// WithoutCompression disables permessage-deflate on this side of the +// connection. Either side can disable it unilaterally, so one call is enough. +// +// The usual reason is security rather than performance. Per-message contexts +// stop a compressed message from leaking the content of earlier ones, but they +// do not stop a single message from leaking: caller-influenced data sitting +// beside a secret still shows up in the compressed length. A service whose +// responses mix the two should turn compression off rather than rely on the +// narrower guarantee. +// +// It is also worth turning off for payloads that do not compress — already +// encoded media, or protobuf binary — where deflate costs CPU for no gain. +func WithoutCompression() Option { + return optionFunc(func(o *options) { o.compressionDisabled = true }) +} + +// WithCompressMinBytes sets the size below which messages are sent +// uncompressed, since compressing a small payload usually makes it bigger. It +// applies to both halves: permessage-deflate's threshold on WebSocket, and the +// Connect content encoding on the HTTP fallback. +// +// The default is 512 bytes. Zero means no minimum — compress everything. +func WithCompressMinBytes(minBytes int) Option { + return optionFunc(func(o *options) { o.compressMinBytes = minBytes }) +} + +// WithInfrastructureHeaders replaces the request headers a client may not set +// in its Leading-Metadata message because this deployment's own infrastructure +// sets them. A trailing "*" matches any suffix, so "X-Forwarded-*" covers the +// family. Matching is case-insensitive. +// +// The default is Forwarded, X-Forwarded-*, and X-Real-IP: what a proxy in +// front of the server sets, and what a client must not be able to forge. Which +// names a deployment's infrastructure actually controls is a property of that +// deployment, so this replaces the list rather than adding to it — pass no +// names to allow all of them. +// +// It does not affect the names the Fetch standard forbids as request headers, +// or the ones this protocol controls. Those are reserved whatever a deployment +// configures. +func WithInfrastructureHeaders(names ...string) ServerOption { + return serverOptionFunc(func(o *options) { + o.infrastructureHeaders = names + }) +} + +// WithKeepAlive sends a WebSocket Ping every interval for as long as the +// connection is open. The interval must be clearly shorter than the idle +// timeout of every proxy and load balancer in the path, or one of them will +// drop a quiet stream; an interval equal to it races the proxy's timer. Common +// idle timeouts are 60 to 100 seconds. The default is 30 seconds; zero or less +// sends no Pings. +// See connecthttp.WithWebSocketKeepAlive. +// +// A peer heard nothing from for the timeout set by [WithKeepAliveTimeout] is +// hung up on: 1011 from a server, 3102 from a client (§4.6). The RPC fails as +// Unavailable on the client and Canceled on the server. +// +// Pongs are sent regardless of this setting. Either side may enable it alone. +func WithKeepAlive(interval time.Duration) Option { + return optionFunc(func(o *options) { o.keepAliveInterval = interval }) +} + +// WithKeepAliveTimeout sets how long a peer may send nothing, neither a message +// nor a Pong, before this side hangs up on it. It applies only while +// [WithKeepAlive] is on. The default is five minutes; a timeout shorter than +// two intervals is raised to that, so a slow Pong is not taken for a dead peer. +// +// A peer whose application has stopped taking messages stops reading its +// connection, and so stops answering Pings. The timeout is how long such a +// stall may last. +func WithKeepAliveTimeout(timeout time.Duration) Option { + return optionFunc(func(o *options) { o.keepAliveTimeout = timeout }) +} + +// WithReadMaxBytes bounds the size of a message this side will accept. Zero +// means no limit. +func WithReadMaxBytes(maxBytes int) Option { + return optionFunc(func(o *options) { o.readMaxBytes = maxBytes }) +} + +// WithSendMaxBytes bounds the size of a message this side will send. Zero +// means no limit. +func WithSendMaxBytes(maxBytes int) Option { + return optionFunc(func(o *options) { o.sendMaxBytes = maxBytes }) +} + +// WithHTTPClient replaces [http.DefaultClient] for the WebSocket handshake, +// which is where TLS, proxy, and dialer settings take effect. +// +// A caller going through [connectrpc.com/connect/v2/connecthttp.NewTransport] +// does not need this: the HTTPClient given there reaches both halves, so their +// settings cannot diverge. +func WithHTTPClient(httpClient *http.Client) ClientOption { + return clientOptionFunc(func(o *options) { + if httpClient != nil { + o.httpClient = httpClient + } + }) +} + +type options struct { + session Session + onProtocolError ServerProtocolErrorHandler + onClientProtocolError ClientProtocolErrorHandler + maxTimeout time.Duration + handshakeTimeout time.Duration + checkOrigin func(*http.Request) bool + eagerDial bool + logger *slog.Logger + codecs []connect.Codec + sendCodec string + compressMinBytes int + compressionDisabled bool + readMaxBytes int + sendMaxBytes int + keepAliveInterval time.Duration + keepAliveTimeout time.Duration + infrastructureHeaders []string + httpClient *http.Client + procedure string + transportInfo func(*http.Request) any +} + +func defaultOptions() options { + return options{ + handshakeTimeout: defaultHandshakeTimeout, + maxTimeout: defaultMaxTimeout, + // nil selects isSameOrigin, the RFC's default policy; see + // WithCheckOrigin. + checkOrigin: nil, + logger: slog.Default(), + infrastructureHeaders: defaultInfrastructureHeaders(), + codecs: []connect.Codec{ + connectproto.NewBinaryCodec(), + connectproto.NewJSONCodec(), + }, + sendCodec: connect.CodecNameProto, + readMaxBytes: defaultReadMaxBytes, + compressMinBytes: defaultCompressMinBytes, + keepAliveInterval: defaultKeepAliveInterval, + keepAliveTimeout: defaultKeepAliveTimeout, + httpClient: http.DefaultClient, + } +} + +// compressionThreshold is the deflate threshold to hand the WebSocket library. +// Zero is that library's sentinel for "use my default", so an explicit request +// for no minimum has to be expressed as one byte to mean the same thing on both +// halves of the transport. +func (o *options) compressionThreshold() int { + if o.compressMinBytes <= 0 { + return 1 + } + return o.compressMinBytes +} + +// compressionMode is the permessage-deflate setting these options ask for. +// NoContextTakeover is the only enabled mode: a context shared across messages +// is the CRIME/BREACH exposure, so it is not offered. +func (o *options) compressionMode() websocket.CompressionMode { + if o.compressionDisabled { + return websocket.CompressionDisabled + } + return websocket.CompressionNoContextTakeover +} + +// optionFunc satisfies both sides, so a shared option is one function value. +type optionFunc func(*options) + +func (f optionFunc) applyToClient(o *options) { f(o) } +func (f optionFunc) applyToServer(o *options) { f(o) } + +type clientOptionFunc func(*options) + +func (f clientOptionFunc) applyToClient(o *options) { f(o) } + +type serverOptionFunc func(*options) + +func (f serverOptionFunc) applyToServer(o *options) { f(o) } diff --git a/internal/wstransport/websocket_ext_test.go b/internal/wstransport/websocket_ext_test.go new file mode 100644 index 00000000..2c5c3c9c --- /dev/null +++ b/internal/wstransport/websocket_ext_test.go @@ -0,0 +1,352 @@ +// Copyright 2021-2026 The Connect Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package wstransport_test + +import ( + "context" + "errors" + "io" + "net/http" + "net/http/httptest" + "strings" + "sync/atomic" + "testing" + "time" + + "connectrpc.com/connect/v2" + "connectrpc.com/connect/v2/connecthttp" + "connectrpc.com/connect/v2/internal/assert" + pingv1 "connectrpc.com/connect/v2/internal/gen/connect/ping/v1" + "connectrpc.com/connect/v2/internal/gen/connect/ping/v1/pingv1connect" + "connectrpc.com/connect/v2/internal/wstransport" +) + +type pingServer struct { + pingv1connect.UnimplementedPingServiceHandler + + // sawDeadline records whether CumSum's context carried a deadline, so a + // test can tell that the client's timeout crossed the wire. + sawDeadline chan time.Duration +} + +func (pingServer) Ping(_ context.Context, req *pingv1.PingRequest) (*pingv1.PingResponse, error) { + return &pingv1.PingResponse{Number: req.Number, Text: req.Text}, nil +} + +func (p pingServer) CumSum(ctx context.Context, stream pingv1connect.PingServiceCumSumServerStream) error { + if p.sawDeadline != nil { + var remaining time.Duration + if deadline, ok := ctx.Deadline(); ok { + remaining = time.Until(deadline) + } + p.sawDeadline <- remaining + } + var total int64 + for { + req, err := stream.Receive() + if errors.Is(err, io.EOF) { + return nil + } + if err != nil { + return err + } + total += req.Number + if err := stream.Send(&pingv1.CumSumResponse{Sum: total}); err != nil { + return err + } + } +} + +// newHybridServer mounts the ping service so that each procedure answers both +// plain HTTP and a WebSocket upgrade on the same path. +func newHybridServer(tb testing.TB, handler pingServer) *httptest.Server { + tb.Helper() + server := connect.NewServer() + pingv1connect.RegisterPingServiceHandler(server, handler) + mux := http.NewServeMux() + connecthttp.Mount(mux, server) + httpServer := httptest.NewServer(mux) + tb.Cleanup(httpServer.Close) + return httpServer +} + +// recordProtocol captures the wire protocol the transport resolved, so a test +// can tell a WebSocket call from one that fell through to HTTP. +func recordProtocol(into *string) connect.ClientInterceptor { + return func(next connect.ClientFunc) connect.ClientFunc { + return func(ctx context.Context, spec connect.Spec) (connect.ClientStream, error) { + stream, err := next(ctx, spec) + if info, ok := connect.CallInfoForClientContext(ctx); ok { + *into = info.Protocol + } + return stream, err + } + } +} + +// newLimitedServer mounts the service with an explicit read limit, so a test +// can carry a payload the default would refuse. +func newLimitedServer(tb testing.TB, readMaxBytes int) *httptest.Server { + tb.Helper() + server := connect.NewServer() + pingv1connect.RegisterPingServiceHandler(server, pingServer{}) + mux := http.NewServeMux() + connecthttp.Mount(mux, server, connecthttp.WithReadMaxBytes(readMaxBytes)) + httpServer := httptest.NewServer(mux) + tb.Cleanup(httpServer.Close) + return httpServer +} + +// recordingTransport captures the upgrade response so a test can inspect what +// the handshake negotiated. +type recordingTransport struct { + base http.RoundTripper + extensions atomic.Pointer[string] + subprotocol atomic.Pointer[string] +} + +func (t *recordingTransport) RoundTrip(req *http.Request) (*http.Response, error) { + res, err := t.base.RoundTrip(req) + if res != nil { + value := res.Header.Get("Sec-WebSocket-Extensions") + t.extensions.Store(&value) + negotiated := res.Header.Get("Sec-WebSocket-Protocol") + t.subprotocol.Store(&negotiated) + } + return res, err +} + +// TestWebSocketNegotiatesPerMessageDeflate pins the compression contract: the +// handshake must agree permessage-deflate, and it must be no-context-takeover +// in both directions. A shared compression context across messages is the +// CRIME/BREACH exposure the design forbids. +func TestWebSocketNegotiatesPerMessageDeflate(t *testing.T) { + t.Parallel() + httpServer := newHybridServer(t, pingServer{}) + recorder := &recordingTransport{base: httpServer.Client().Transport} + transport := connecthttp.NewTransport( + &http.Client{Transport: recorder}, + httpServer.URL, + connecthttp.WithWebSocket(connecthttp.SelectAll), + ) + client := pingv1connect.NewPingServiceClient(connect.NewClient(transport)) + + _, err := client.Ping(t.Context(), &pingv1.PingRequest{Number: 1, Text: "hello"}) + assert.Nil(t, err) + + negotiated := recorder.extensions.Load() + assert.NotNil(t, negotiated) + assert.True(t, strings.Contains(*negotiated, "permessage-deflate")) + assert.True(t, strings.Contains(*negotiated, "client_no_context_takeover")) + assert.True(t, strings.Contains(*negotiated, "server_no_context_takeover")) +} + +// TestWebSocketRoundTripsCompressiblePayload exercises a payload large enough +// to actually be deflated, so the compression path is not merely negotiated. +func TestWebSocketRoundTripsCompressiblePayload(t *testing.T) { + t.Parallel() + httpServer := newLimitedServer(t, 1024*1024) + transport := connecthttp.NewTransport( + httpServer.Client(), + httpServer.URL, + connecthttp.WithWebSocket(connecthttp.SelectAll), + ) + client := pingv1connect.NewPingServiceClient(connect.NewClient(transport)) + + text := strings.Repeat("compress me ", 8192) // ~96KiB, highly compressible + res, err := client.Ping(t.Context(), &pingv1.PingRequest{Number: 7, Text: text}) + assert.Nil(t, err) + assert.Equal(t, res.Text, text) + assert.Equal(t, res.Number, int64(7)) +} + +// TestWebSocketIgnoresSendCompression pins that a Connect-level send +// compressor does not reach the WebSocket path. The peer rejects a +// compressed-message flag outright, so if this option ever leaked through +// again the RPC would fail rather than merely double-compress. +func TestWebSocketIgnoresSendCompression(t *testing.T) { + t.Parallel() + httpServer := newHybridServer(t, pingServer{}) + transport := connecthttp.NewTransport( + httpServer.Client(), + httpServer.URL, + connecthttp.WithWebSocket(connecthttp.SelectAll), + connecthttp.WithSendCompression("gzip"), + connecthttp.WithCompressMinBytes(1), + ) + client := pingv1connect.NewPingServiceClient(connect.NewClient(transport)) + + text := strings.Repeat("compress me ", 1024) + res, err := client.Ping(t.Context(), &pingv1.PingRequest{Number: 1, Text: text}) + assert.Nil(t, err) + assert.Equal(t, res.Text, text) +} + +// newCompressionServer mounts the service with the given options so a test can +// disable compression on the server alone. +func newCompressionServer(tb testing.TB, options ...connecthttp.Option) *httptest.Server { + tb.Helper() + server := connect.NewServer() + pingv1connect.RegisterPingServiceHandler(server, pingServer{}) + mux := http.NewServeMux() + connecthttp.Mount(mux, server, options...) + httpServer := httptest.NewServer(mux) + tb.Cleanup(httpServer.Close) + return httpServer +} + +// negotiatedExtensions runs one RPC and reports what the handshake agreed. +func negotiatedExtensions( + tb testing.TB, + httpServer *httptest.Server, + options ...connecthttp.Option, +) string { + tb.Helper() + recorder := &recordingTransport{base: httpServer.Client().Transport} + transport := connecthttp.NewTransport( + &http.Client{Transport: recorder}, + httpServer.URL, + append([]connecthttp.Option{ + connecthttp.WithWebSocket(connecthttp.SelectAll), + }, options...)..., + ) + client := pingv1connect.NewPingServiceClient(connect.NewClient(transport)) + + text := strings.Repeat("compress me ", 512) + res, err := client.Ping(tb.Context(), &pingv1.PingRequest{Number: 1, Text: text}) + assert.Nil(tb, err) + // The RPC must still work either way; only the framing changes. + assert.Equal(tb, res.Text, text) + + negotiated := recorder.extensions.Load() + assert.NotNil(tb, negotiated) + return *negotiated +} + +// Disabling on the server must win even though the client still offers it. +func TestWithoutCompressionOnTheServer(t *testing.T) { + t.Parallel() + httpServer := newCompressionServer(t, connecthttp.WithoutWebSocketCompression()) + assert.Equal(t, negotiatedExtensions(t, httpServer), "") +} + +// Disabling on the client must win even though the server still offers it. +func TestWithoutCompressionOnTheClient(t *testing.T) { + t.Parallel() + httpServer := newCompressionServer(t) + assert.Equal(t, negotiatedExtensions(t, httpServer, connecthttp.WithoutWebSocketCompression()), "") +} + +// TestCompressMinBytesAgreesAcrossHalves pins that the threshold means the same +// thing whichever wire an RPC takes. The two libraries read a zero differently +// — one as "use my default", the other as "no minimum" — so an unset or +// explicitly-zero option is exactly where they would drift apart. +func TestCompressMinBytesAgreesAcrossHalves(t *testing.T) { + t.Parallel() + for _, test := range []struct { + name string + options []connecthttp.Option + }{ + {"default", nil}, + {"explicit zero", []connecthttp.Option{connecthttp.WithCompressMinBytes(0)}}, + {"explicit value", []connecthttp.Option{connecthttp.WithCompressMinBytes(4096)}}, + } { + t.Run(test.name, func(t *testing.T) { + t.Parallel() + httpServer := newCompressionServer(t, test.options...) + transport := connecthttp.NewTransport( + httpServer.Client(), + httpServer.URL, + append([]connecthttp.Option{ + connecthttp.WithWebSocket(connecthttp.SelectStreaming), + }, test.options...)..., + ) + client := pingv1connect.NewPingServiceClient(connect.NewClient(transport)) + + // Well under the default threshold, and well over it, over both + // wires: unary falls through to HTTP, CumSum goes over WebSocket. + for _, text := range []string{"tiny", strings.Repeat("x", 8192)} { + res, err := client.Ping(t.Context(), &pingv1.PingRequest{Text: text}) + assert.Nil(t, err) + assert.Equal(t, res.Text, text) + } + stream, err := client.CumSum(t.Context()) + assert.Nil(t, err) + assert.Nil(t, stream.Send(&pingv1.CumSumRequest{Number: 5})) + sum, err := stream.Receive() + assert.Nil(t, err) + assert.Equal(t, sum.Sum, int64(5)) + assert.Nil(t, stream.CloseSend()) + assert.Nil(t, stream.Close()) + }) + } +} + +// TestSendCodecSelectsSubprotocol pins that the codec and the negotiated +// subprotocol cannot disagree. They are chosen in different places — the codec +// from WithSendCodec, the token in the dial options — so a mismatch encodes +// with one and decodes with the other, which surfaces as a corrupt-wire-format +// error rather than anything pointing at the codec. +func TestSendCodecSelectsSubprotocol(t *testing.T) { + t.Parallel() + for _, test := range []struct { + codec string + token string + }{ + {connect.CodecNameProto, "connectrpc.1+proto"}, + {connect.CodecNameJSON, "connectrpc.1+json"}, + } { + t.Run(test.codec, func(t *testing.T) { + t.Parallel() + httpServer := newHybridServer(t, pingServer{}) + recorder := &recordingTransport{base: httpServer.Client().Transport} + transport := connecthttp.NewTransport( + &http.Client{Transport: recorder}, + httpServer.URL, + connecthttp.WithWebSocket(connecthttp.SelectAll), + connecthttp.WithSendCodec(test.codec), + ) + client := pingv1connect.NewPingServiceClient(connect.NewClient(transport)) + + res, err := client.Ping(t.Context(), &pingv1.PingRequest{Number: 42, Text: "hello"}) + assert.Nil(t, err) + assert.Equal(t, res.Number, int64(42)) + assert.Equal(t, res.Text, "hello") + assert.Equal(t, recorder.subprotocol.Load() != nil, true) + assert.Equal(t, *recorder.subprotocol.Load(), test.token) + }) + } +} + +// mountBoth registers server on mux over both transports, with WebSocket +// options the public connecthttp surface deliberately has no name for. +// +// Test scaffolding only. A user configures through connecthttp; these tests +// live beside the internal package and reach it directly so that behaviour +// with no public knob is still covered. +func mountBoth(mux *http.ServeMux, server *connect.Server, options ...wstransport.ServerOption) { + connecthttp.Mount(&upgradingMux{mux: mux, server: server, options: options}, server, + connecthttp.WithoutWebSocket()) +} + +type upgradingMux struct { + mux *http.ServeMux + server *connect.Server + options []wstransport.ServerOption +} + +func (m *upgradingMux) Handle(pattern string, handler http.Handler) { + m.mux.Handle(pattern, wstransport.Upgrade(m.server, handler, m.options...)) +} diff --git a/internal/wstransport/writerace_ext_test.go b/internal/wstransport/writerace_ext_test.go new file mode 100644 index 00000000..ba777809 --- /dev/null +++ b/internal/wstransport/writerace_ext_test.go @@ -0,0 +1,103 @@ +// Copyright 2021-2026 The Connect Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package wstransport_test + +import ( + "context" + "crypto/rand" + "encoding/base64" + "net" + "testing" + "time" + + "connectrpc.com/connect/v2/internal/assert" + pingv1 "connectrpc.com/connect/v2/internal/gen/connect/ping/v1" + "connectrpc.com/connect/v2/internal/gen/connect/ping/v1/pingv1connect" + "connectrpc.com/connect/v2/internal/wstransport" + "github.com/coder/websocket" +) + +// deadlineMillis is the deadline the race tests send, and resumeAfter when +// their clients start reading again: after it, while a write is in flight. +const ( + deadlineMillis = "300" + resumeAfter = 350 * time.Millisecond +) + +// bigPingServer answers with more than the socket buffers hold, so its write +// is still in flight while a client that is not reading holds it up. +type bigPingServer struct { + pingv1connect.UnimplementedPingServiceHandler + + text string +} + +func (s bigPingServer) Ping(context.Context, *pingv1.PingRequest) (*pingv1.PingResponse, error) { + return &pingv1.PingResponse{Text: s.text}, nil +} + +// §11.1: an expired deadline still ends in S and 1000. The library closes the +// connection when a write's context ends, so a write under the RPC's context +// lost both whenever the deadline caught it mid-write. +func TestWriteInFlightAtDeadlineStillEndsWithS(t *testing.T) { + t.Parallel() + // Random, so that permessage-deflate cannot shrink it below the buffers. + random := make([]byte, 24<<20) + _, _ = rand.Read(random) + httpServer := newHybridServer2(t, bigPingServer{text: base64.StdEncoding.EncodeToString(random)}) + conn := dialRaw(t, httpServer, pingv1connect.PingServicePingProcedure+"?connect-timeout-ms="+deadlineMillis) + conn.SetReadLimit(-1) + sendJSONMessage(t, conn, wireMetadata, []byte("[]")) + sendProtoBody(t, conn, &pingv1.PingRequest{}) + sendJSONMessage(t, conn, wireClientEndStream, nil) + + time.Sleep(resumeAfter) + ctx, cancel := context.WithTimeout(t.Context(), 10*time.Second) + defer cancel() + var last byte + for { + _, data, err := conn.Read(ctx) + if err != nil { + assert.Equal(t, websocket.CloseStatus(err), websocket.StatusNormalClosure) + break + } + if len(data) > 0 { + last = data[0] + } + } + assert.Equal(t, last, wireServerEndStream) +} + +// The same holds for a keep-alive Ping awaiting its Pong when the deadline +// expires: the library closes the connection when the Ping's context ends. +func TestPingInFlightAtDeadlineStillEndsWithS(t *testing.T) { + t.Parallel() + httpServer := newKeepAliveServer(t, + wstransport.WithKeepAlive(keepAliveInterval), + wstransport.WithKeepAliveTimeout(time.Minute), + ) + addr := httpServer.Listener.Addr().String() + conn, err := (&net.Dialer{}).DialContext(t.Context(), "tcp", addr) + assert.Nil(t, err) + t.Cleanup(func() { _ = conn.Close() }) + _ = rawHandshake(t, conn, addr, pingProcedure+"?connect-timeout-ms="+deadlineMillis) + assert.Nil(t, writeClientFrame(conn, openMessage(), false, true)) + + // Never answering, so a Ping is always awaiting its Pong. + assert.Nil(t, conn.SetReadDeadline(time.Now().Add(10*time.Second))) + pings, closeCode, _ := watchFrames(conn, nil) + assert.True(t, pings >= 1) + assert.Equal(t, closeCode, 1000) +}