forked from connectrpc/connect-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
protocol_connect_test.go
366 lines (349 loc) · 10.9 KB
/
protocol_connect_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
// Copyright 2021-2024 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 connect
import (
"bytes"
"context"
"encoding/json"
"fmt"
"net/http"
"strings"
"testing"
"time"
"connectrpc.com/connect/internal/assert"
"google.golang.org/protobuf/proto"
"google.golang.org/protobuf/types/descriptorpb"
"google.golang.org/protobuf/types/known/durationpb"
)
func TestConnectErrorDetailMarshaling(t *testing.T) {
t.Parallel()
testCases := []struct {
name string
errorDetail proto.Message
expectDebug any
}{
{
name: "normal",
errorDetail: &descriptorpb.FieldOptions{
Deprecated: proto.Bool(true),
Jstype: descriptorpb.FieldOptions_JS_STRING.Enum(),
},
expectDebug: map[string]any{
"deprecated": true,
"jstype": "JS_STRING",
},
},
{
name: "well-known type with custom JSON",
errorDetail: durationpb.New(time.Second),
expectDebug: "1s", // special JS representation as duration string
},
}
for _, testCase := range testCases {
testCase := testCase
t.Run(testCase.name, func(t *testing.T) {
t.Parallel()
detail, err := NewErrorDetail(testCase.errorDetail)
assert.Nil(t, err)
data, err := json.Marshal((*connectWireDetail)(detail))
assert.Nil(t, err)
t.Logf("marshaled error detail: %s", string(data))
var unmarshaled connectWireDetail
assert.Nil(t, json.Unmarshal(data, &unmarshaled))
assert.Equal(t, unmarshaled.wireJSON, string(data))
assert.Equal(t, unmarshaled.pbAny, detail.pbAny)
var extractDetails struct {
Debug any `json:"debug"`
}
assert.Nil(t, json.Unmarshal(data, &extractDetails))
assert.Equal(t, extractDetails.Debug, testCase.expectDebug)
})
}
}
func TestConnectErrorDetailMarshalingNoDescriptor(t *testing.T) {
t.Parallel()
raw := `{"type":"acme.user.v1.User","value":"DEADBF",` +
`"debug":{"email":"[email protected]"}}`
var detail connectWireDetail
assert.Nil(t, json.Unmarshal([]byte(raw), &detail))
assert.Equal(t, detail.pbAny.GetTypeUrl(), defaultAnyResolverPrefix+"acme.user.v1.User")
_, err := (*ErrorDetail)(&detail).Value()
assert.NotNil(t, err)
assert.True(t, strings.HasSuffix(err.Error(), "not found"))
encoded, err := json.Marshal(&detail)
assert.Nil(t, err)
assert.Equal(t, string(encoded), raw)
}
func TestConnectEndOfResponseCanonicalTrailers(t *testing.T) {
t.Parallel()
buffer := bytes.Buffer{}
bufferPool := newBufferPool()
endStreamMessage := connectEndStreamMessage{Trailer: make(http.Header)}
endStreamMessage.Trailer["not-canonical-header"] = []string{"a"}
endStreamMessage.Trailer["mixed-Canonical"] = []string{"b"}
endStreamMessage.Trailer["Mixed-Canonical"] = []string{"b"}
endStreamMessage.Trailer["Canonical-Header"] = []string{"c"}
endStreamData, err := json.Marshal(endStreamMessage)
assert.Nil(t, err)
writer := envelopeWriter{
sender: writeSender{writer: &buffer},
bufferPool: bufferPool,
}
err = writer.Write(&envelope{
Flags: connectFlagEnvelopeEndStream,
Data: bytes.NewBuffer(endStreamData),
})
assert.Nil(t, err)
unmarshaler := connectStreamingUnmarshaler{
envelopeReader: envelopeReader{
ctx: context.Background(),
reader: &buffer,
bufferPool: bufferPool,
},
}
err = unmarshaler.Unmarshal(nil) // parameter won't be used
assert.ErrorIs(t, err, errSpecialEnvelope)
assert.Equal(t, unmarshaler.Trailer().Values("Not-Canonical-Header"), []string{"a"})
assert.Equal(t, unmarshaler.Trailer().Values("Mixed-Canonical"), []string{"b", "b"})
assert.Equal(t, unmarshaler.Trailer().Values("Canonical-Header"), []string{"c"})
}
func TestConnectValidateUnaryResponseContentType(t *testing.T) {
t.Parallel()
testCases := []struct {
codecName string
get bool
statusCode int
responseContentType string
expectCode Code
expectBadContentType bool
expectNotModified bool
}{
// Allowed content-types for OK responses.
{
codecName: codecNameProto,
statusCode: http.StatusOK,
responseContentType: "application/proto",
},
{
codecName: codecNameJSON,
statusCode: http.StatusOK,
responseContentType: "application/json",
},
{
codecName: codecNameJSON,
statusCode: http.StatusOK,
responseContentType: "application/json; charset=utf-8",
},
{
codecName: codecNameJSONCharsetUTF8,
statusCode: http.StatusOK,
responseContentType: "application/json",
},
{
codecName: codecNameJSONCharsetUTF8,
statusCode: http.StatusOK,
responseContentType: "application/json; charset=utf-8",
},
// Allowed content-types for error responses.
{
codecName: codecNameProto,
statusCode: http.StatusNotFound,
responseContentType: "application/json",
},
{
codecName: codecNameProto,
statusCode: http.StatusBadRequest,
responseContentType: "application/json; charset=utf-8",
},
{
codecName: codecNameJSON,
statusCode: http.StatusInternalServerError,
responseContentType: "application/json",
},
{
codecName: codecNameJSON,
statusCode: http.StatusPreconditionFailed,
responseContentType: "application/json; charset=utf-8",
},
// 304 Not Modified for GET request gets a special error, regardless of content-type
{
codecName: codecNameProto,
get: true,
statusCode: http.StatusNotModified,
responseContentType: "application/json",
expectCode: CodeUnknown,
expectNotModified: true,
},
{
codecName: codecNameJSON,
get: true,
statusCode: http.StatusNotModified,
responseContentType: "application/json",
expectCode: CodeUnknown,
expectNotModified: true,
},
// OK status, invalid content-type
{
codecName: codecNameProto,
statusCode: http.StatusOK,
responseContentType: "application/proto; charset=utf-8",
expectCode: CodeInternal,
expectBadContentType: true,
},
{
codecName: codecNameProto,
statusCode: http.StatusOK,
responseContentType: "application/json",
expectCode: CodeInternal,
expectBadContentType: true,
},
{
codecName: codecNameJSON,
statusCode: http.StatusOK,
responseContentType: "application/proto",
expectCode: CodeInternal,
expectBadContentType: true,
},
{
codecName: codecNameJSON,
statusCode: http.StatusOK,
responseContentType: "some/garbage",
expectCode: CodeUnknown, // doesn't even look like it could be connect protocol
expectBadContentType: true,
},
// Error status, invalid content-type, returns code based on HTTP status code
{
codecName: codecNameProto,
statusCode: http.StatusNotFound,
responseContentType: "application/proto",
expectCode: httpToCode(http.StatusNotFound),
},
{
codecName: codecNameJSON,
statusCode: http.StatusBadRequest,
responseContentType: "some/garbage",
expectCode: httpToCode(http.StatusBadRequest),
},
{
codecName: codecNameJSON,
statusCode: http.StatusTooManyRequests,
responseContentType: "some/garbage",
expectCode: httpToCode(http.StatusTooManyRequests),
},
}
for _, testCase := range testCases {
testCase := testCase
httpMethod := http.MethodPost
if testCase.get {
httpMethod = http.MethodGet
}
testCaseName := fmt.Sprintf("%s_%s->%d_%s", httpMethod, testCase.codecName, testCase.statusCode, testCase.responseContentType)
t.Run(testCaseName, func(t *testing.T) {
t.Parallel()
err := connectValidateUnaryResponseContentType(
testCase.codecName,
httpMethod,
testCase.statusCode,
http.StatusText(testCase.statusCode),
testCase.responseContentType,
)
if testCase.expectCode == 0 {
assert.Nil(t, err)
} else if assert.NotNil(t, err) {
assert.Equal(t, CodeOf(err), testCase.expectCode)
switch {
case testCase.expectNotModified:
assert.ErrorIs(t, err, errNotModified)
case testCase.expectBadContentType:
assert.True(t, strings.Contains(err.Message(), fmt.Sprintf("invalid content-type: %q; expecting", testCase.responseContentType)))
default:
assert.Equal(t, err.Message(), http.StatusText(testCase.statusCode))
}
}
})
}
}
func TestConnectValidateStreamResponseContentType(t *testing.T) {
t.Parallel()
testCases := []struct {
codecName string
responseContentType string
expectCode Code
}{
// Allowed content-types
{
codecName: codecNameProto,
responseContentType: "application/connect+proto",
},
{
codecName: codecNameJSON,
responseContentType: "application/connect+json",
},
// Mismatched response codec
{
codecName: codecNameProto,
responseContentType: "application/connect+json",
expectCode: CodeInternal,
},
{
codecName: codecNameJSON,
responseContentType: "application/connect+proto",
expectCode: CodeInternal,
},
// Disallowed content-types
{
codecName: codecNameJSON,
responseContentType: "application/connect+json; charset=utf-8",
expectCode: CodeInternal, // *almost* looks right
},
{
codecName: codecNameProto,
responseContentType: "application/proto",
expectCode: CodeUnknown,
},
{
codecName: codecNameJSON,
responseContentType: "application/json",
expectCode: CodeUnknown,
},
{
codecName: codecNameJSON,
responseContentType: "application/json; charset=utf-8",
expectCode: CodeUnknown,
},
{
codecName: codecNameProto,
responseContentType: "some/garbage",
expectCode: CodeUnknown,
},
}
for _, testCase := range testCases {
testCase := testCase
testCaseName := fmt.Sprintf("%s->%s", testCase.codecName, testCase.responseContentType)
t.Run(testCaseName, func(t *testing.T) {
t.Parallel()
err := connectValidateStreamResponseContentType(
testCase.codecName,
StreamTypeServer,
testCase.responseContentType,
)
if testCase.expectCode == 0 {
assert.Nil(t, err)
} else if assert.NotNil(t, err) {
assert.Equal(t, CodeOf(err), testCase.expectCode)
assert.True(t, strings.Contains(err.Message(), fmt.Sprintf("invalid content-type: %q; expecting", testCase.responseContentType)))
}
})
}
}