| 1 |
// Copyright 2020-2026 The NATS Authors |
| 2 |
// Licensed under the Apache License, Version 2.0 (the "License"); |
| 3 |
// you may not use this file except in compliance with the License. |
| 4 |
// You may obtain a copy of the License at |
| 5 |
// |
| 6 |
// http://www.apache.org/licenses/LICENSE-2.0 |
| 7 |
// |
| 8 |
// Unless required by applicable law or agreed to in writing, software |
| 9 |
// distributed under the License is distributed on an "AS IS" BASIS, |
| 10 |
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 11 |
// See the License for the specific language governing permissions and |
| 12 |
// limitations under the License. |
| 13 |
|
| 14 |
package test |
| 15 |
|
| 16 |
import ( |
| 17 |
"context" |
| 18 |
"encoding/json" |
| 19 |
"fmt" |
| 20 |
"net/http" |
| 21 |
"net/http/httptest" |
| 22 |
"reflect" |
| 23 |
"sort" |
| 24 |
"sync" |
| 25 |
"testing" |
| 26 |
"time" |
| 27 |
|
| 28 |
"github.com/nats-io/nats.go" |
| 29 |
testservice "github.com/synadia-io/orbit.go/ntf-client" |
| 30 |
) |
| 31 |
|
| 32 |
func TestBasicHeaders(t *testing.T) { |
| 33 |
withServer(t, func(t *testing.T, nc *nats.Conn) { |
| 34 |
subject := "headers.test" |
| 35 |
sub, err := nc.SubscribeSync(subject) |
| 36 |
if err != nil { |
| 37 |
t.Fatalf("Could not subscribe to %q: %v", subject, err) |
| 38 |
} |
| 39 |
defer sub.Unsubscribe() |
| 40 |
|
| 41 |
m := nats.NewMsg(subject) |
| 42 |
m.Header.Add("Accept-Encoding", "json") |
| 43 |
m.Header.Add("Authorization", "s3cr3t") |
| 44 |
m.Data = []byte("Hello Headers!") |
| 45 |
|
| 46 |
nc.PublishMsg(m) |
| 47 |
msg, err := sub.NextMsg(time.Second) |
| 48 |
if err != nil { |
| 49 |
t.Fatalf("Did not receive response: %v", err) |
| 50 |
} |
| 51 |
|
| 52 |
if !m.Equal(msg) { |
| 53 |
t.Fatalf("Messages did not match! \n%+v\n%+v\n", m, msg) |
| 54 |
} |
| 55 |
}) |
| 56 |
} |
| 57 |
|
| 58 |
func TestRequestMsg(t *testing.T) { |
| 59 |
withServer(t, func(t *testing.T, nc *nats.Conn) { |
| 60 |
subject := "headers.test" |
| 61 |
sub, err := nc.Subscribe(subject, func(m *nats.Msg) { |
| 62 |
if m.Header.Get("Hdr-Test") != "1" { |
| 63 |
m.Respond([]byte("-ERR")) |
| 64 |
} |
| 65 |
r := nats.NewMsg(m.Reply) |
| 66 |
r.Header = m.Header |
| 67 |
r.Data = []byte("+OK") |
| 68 |
m.RespondMsg(r) |
| 69 |
}) |
| 70 |
if err != nil { |
| 71 |
t.Fatalf("subscribe failed: %v", err) |
| 72 |
} |
| 73 |
defer sub.Unsubscribe() |
| 74 |
|
| 75 |
msg := nats.NewMsg(subject) |
| 76 |
msg.Header.Add("Hdr-Test", "1") |
| 77 |
resp, err := nc.RequestMsg(msg, time.Second) |
| 78 |
if err != nil { |
| 79 |
t.Fatalf("Expected request to be published: %v", err) |
| 80 |
} |
| 81 |
if string(resp.Data) != "+OK" { |
| 82 |
t.Fatalf("Headers were not published to the requestor") |
| 83 |
} |
| 84 |
if resp.Header.Get("Hdr-Test") != "1" { |
| 85 |
t.Fatalf("Did not receive header in response") |
| 86 |
} |
| 87 |
|
| 88 |
if err = nc.PublishMsg(nil); err != nats.ErrInvalidMsg { |
| 89 |
t.Errorf("Unexpected error: %v", err) |
| 90 |
} |
| 91 |
if _, err = nc.RequestMsg(nil, time.Second); err != nats.ErrInvalidMsg { |
| 92 |
t.Errorf("Unexpected error: %v", err) |
| 93 |
} |
| 94 |
ctx, cancel := context.WithTimeout(context.Background(), 250*time.Millisecond) |
| 95 |
defer cancel() |
| 96 |
if _, err = nc.RequestMsgWithContext(ctx, nil); err != nats.ErrInvalidMsg { |
| 97 |
t.Errorf("Unexpected error: %v", err) |
| 98 |
} |
| 99 |
}) |
| 100 |
} |
| 101 |
|
| 102 |
func TestRequestMsgRaceAsyncInfo(t *testing.T) { |
| 103 |
// Original spun up a 2-node cluster and then in a goroutine repeatedly |
| 104 |
// started/shut down the second node to provoke async INFO churn. The |
| 105 |
// testservice equivalent: create a 2-node cluster up front and Stop/Start |
| 106 |
// the second node in a loop. |
| 107 |
c := newTester(t) |
| 108 |
inst := c.CreateCluster(t, 2, false) |
| 109 |
t.Cleanup(func() { inst.Destroy(t) }) |
| 110 |
|
| 111 |
primary := inst.Servers[0] |
| 112 |
churn := inst.Servers[1] |
| 113 |
|
| 114 |
nc, err := nats.Connect(primary.URL) |
| 115 |
if err != nil { |
| 116 |
t.Fatalf("Error connecting to server: %v", err) |
| 117 |
} |
| 118 |
defer nc.Close() |
| 119 |
|
| 120 |
nc2, err := nats.Connect(primary.URL, nats.UseOldRequestStyle()) |
| 121 |
if err != nil { |
| 122 |
t.Fatalf("Error connecting to server: %v", err) |
| 123 |
} |
| 124 |
defer nc2.Close() |
| 125 |
|
| 126 |
subject := "headers.test" |
| 127 |
if _, err := nc.Subscribe(subject, func(m *nats.Msg) { |
| 128 |
r := nats.NewMsg(m.Reply) |
| 129 |
r.Header["Hdr-Test"] = []string{"bar"} |
| 130 |
r.Data = []byte("+OK") |
| 131 |
m.RespondMsg(r) |
| 132 |
}); err != nil { |
| 133 |
t.Fatalf("subscribe failed: %v", err) |
| 134 |
} |
| 135 |
nc.Flush() |
| 136 |
|
| 137 |
// Churn goroutine bypasses inst.StopServer/StartServer because those |
| 138 |
// fail via t.Fatalf from a non-test goroutine, which is illegal per the |
| 139 |
// testing docs (FailNow → runtime.Goexit only terminates the calling |
| 140 |
// goroutine; the parent test may continue obliviously). Drive the same |
| 141 |
// tester RPCs directly and surface errors via an error channel that the |
| 142 |
// test goroutine drains after the workload. |
| 143 |
testerNc, err := nats.Connect(testerURL) |
| 144 |
if err != nil { |
| 145 |
t.Fatalf("could not dial tester: %v", err) |
| 146 |
} |
| 147 |
defer testerNc.Close() |
| 148 |
|
| 149 |
churnOp := func(subject, name string) error { |
| 150 |
body, _ := json.Marshal(map[string]string{"name": name}) |
| 151 |
m, err := testerNc.Request(subject, body, 10*time.Second) |
| 152 |
if err != nil { |
| 153 |
return fmt.Errorf("%s: %w", subject, err) |
| 154 |
} |
| 155 |
if e := m.Header.Get("Nats-Service-Error"); e != "" { |
| 156 |
return fmt.Errorf("%s: %s", subject, e) |
| 157 |
} |
| 158 |
return nil |
| 159 |
} |
| 160 |
|
| 161 |
errCh := make(chan error, 1) |
| 162 |
wg := sync.WaitGroup{} |
| 163 |
wg.Add(1) |
| 164 |
ch := make(chan struct{}) |
| 165 |
go func() { |
| 166 |
defer wg.Done() |
| 167 |
for { |
| 168 |
if err := churnOp("tester.stop.server", churn.Name); err != nil { |
| 169 |
select { |
| 170 |
case errCh <- err: |
| 171 |
default: |
| 172 |
} |
| 173 |
return |
| 174 |
} |
| 175 |
if err := churnOp("tester.start.server", churn.Name); err != nil { |
| 176 |
select { |
| 177 |
case errCh <- err: |
| 178 |
default: |
| 179 |
} |
| 180 |
return |
| 181 |
} |
| 182 |
select { |
| 183 |
case <-ch: |
| 184 |
return |
| 185 |
default: |
| 186 |
} |
| 187 |
} |
| 188 |
}() |
| 189 |
|
| 190 |
msg := nats.NewMsg(subject) |
| 191 |
msg.Header["Hdr-Test"] = []string{"quux"} |
| 192 |
for range 100 { |
| 193 |
nc.RequestMsg(msg, time.Second) |
| 194 |
ctx, cancel := context.WithTimeout(context.Background(), time.Second) |
| 195 |
nc.RequestMsgWithContext(ctx, msg) |
| 196 |
cancel() |
| 197 |
|
| 198 |
nc2.RequestMsg(msg, time.Second) |
| 199 |
ctx2, cancel2 := context.WithTimeout(context.Background(), time.Second) |
| 200 |
nc2.RequestMsgWithContext(ctx2, msg) |
| 201 |
cancel2() |
| 202 |
} |
| 203 |
|
| 204 |
close(ch) |
| 205 |
wg.Wait() |
| 206 |
select { |
| 207 |
case err := <-errCh: |
| 208 |
t.Fatalf("churn goroutine failed: %v", err) |
| 209 |
default: |
| 210 |
} |
| 211 |
} |
| 212 |
|
| 213 |
func TestNoHeaderSupport(t *testing.T) { |
| 214 |
c := newTester(t) |
| 215 |
inst := c.CreateServer(t, false, testservice.WithTopLevel("no_header_support: true")) |
| 216 |
t.Cleanup(func() { inst.Destroy(t) }) |
| 217 |
|
| 218 |
nc := dialInstance(t, inst) |
| 219 |
|
| 220 |
m := nats.NewMsg("foo") |
| 221 |
m.Header.Add("Authorization", "s3cr3t") |
| 222 |
m.Data = []byte("Hello Headers!") |
| 223 |
|
| 224 |
if err := nc.PublishMsg(m); err != nats.ErrHeadersNotSupported { |
| 225 |
t.Fatalf("Expected an error, got %v", err) |
| 226 |
} |
| 227 |
|
| 228 |
if _, err := nc.RequestMsg(m, time.Second); err != nats.ErrHeadersNotSupported { |
| 229 |
t.Fatalf("Expected an error, got %v", err) |
| 230 |
} |
| 231 |
} |
| 232 |
|
| 233 |
func TestMsgHeadersCasePreserving(t *testing.T) { |
| 234 |
withServer(t, func(t *testing.T, nc *nats.Conn) { |
| 235 |
subject := "headers.test" |
| 236 |
sub, err := nc.SubscribeSync(subject) |
| 237 |
if err != nil { |
| 238 |
t.Fatalf("Could not subscribe to %q: %v", subject, err) |
| 239 |
} |
| 240 |
defer sub.Unsubscribe() |
| 241 |
|
| 242 |
m := nats.NewMsg(subject) |
| 243 |
|
| 244 |
hdr := http.Header{ |
| 245 |
"CorrelationID": []string{"123"}, |
| 246 |
"Msg-ID": []string{"456"}, |
| 247 |
"X-NATS-Keys": []string{"A", "B", "C"}, |
| 248 |
"X-Test-Keys": []string{"D", "E", "F"}, |
| 249 |
} |
| 250 |
|
| 251 |
type HeaderInterface interface { |
| 252 |
Add(key, value string) |
| 253 |
Del(key string) |
| 254 |
Get(key string) string |
| 255 |
Set(key, value string) |
| 256 |
Values(key string) []string |
| 257 |
} |
| 258 |
var _ HeaderInterface = http.Header{} |
| 259 |
var _ HeaderInterface = nats.Header{} |
| 260 |
|
| 261 |
m.Header = nats.Header(hdr) |
| 262 |
http.Header(m.Header).Set("accept-encoding", "json") |
| 263 |
http.Header(m.Header).Add("AUTHORIZATION", "s3cr3t") |
| 264 |
|
| 265 |
m.Header.Set("X-Test", "First") |
| 266 |
m.Header.Add("X-Test", "Second") |
| 267 |
m.Header.Add("X-Test", "Third") |
| 268 |
|
| 269 |
m.Data = []byte("Simple Headers") |
| 270 |
nc.PublishMsg(m) |
| 271 |
msg, err := sub.NextMsg(time.Second) |
| 272 |
if err != nil { |
| 273 |
t.Fatalf("Did not receive response: %v", err) |
| 274 |
} |
| 275 |
if !m.Equal(msg) { |
| 276 |
t.Fatalf("Messages did not match! \n%+v\n%+v\n", m, msg) |
| 277 |
} |
| 278 |
|
| 279 |
for _, test := range []struct { |
| 280 |
Header string |
| 281 |
Values []string |
| 282 |
}{ |
| 283 |
{"Accept-Encoding", []string{"json"}}, |
| 284 |
{"Authorization", []string{"s3cr3t"}}, |
| 285 |
{"X-Test", []string{"First", "Second", "Third"}}, |
| 286 |
{"CorrelationID", []string{"123"}}, |
| 287 |
{"Msg-ID", []string{"456"}}, |
| 288 |
{"X-NATS-Keys", []string{"A", "B", "C"}}, |
| 289 |
{"X-Test-Keys", []string{"D", "E", "F"}}, |
| 290 |
} { |
| 291 |
v1, ok := msg.Header[test.Header] |
| 292 |
if !ok { |
| 293 |
t.Errorf("Expected %v to be present", test.Header) |
| 294 |
} |
| 295 |
if len(v1) != len(test.Values) { |
| 296 |
t.Errorf("Expected %v values in header, got: %v", len(test.Values), len(v1)) |
| 297 |
} |
| 298 |
|
| 299 |
v2 := msg.Header.Get(test.Header) |
| 300 |
if v2 == "" { |
| 301 |
t.Errorf("Expected %v to be present", test.Header) |
| 302 |
} |
| 303 |
if v1[0] != v2 { |
| 304 |
t.Errorf("Expected: %s, got: %v", v1, v2) |
| 305 |
} |
| 306 |
|
| 307 |
for k, val := range test.Values { |
| 308 |
hdr := msg.Header[test.Header] |
| 309 |
vv := hdr[k] |
| 310 |
if val != vv { |
| 311 |
t.Errorf("Expected %v values in header, got: %v", val, vv) |
| 312 |
} |
| 313 |
} |
| 314 |
if len(test.Values) > 1 { |
| 315 |
if !reflect.DeepEqual(test.Values, msg.Header.Values(test.Header)) { |
| 316 |
t.Fatalf("Headers did not match! \n%+v\n%+v\n", test.Values, msg.Header.Values(test.Header)) |
| 317 |
} |
| 318 |
} else { |
| 319 |
got := msg.Header.Get(test.Header) |
| 320 |
expected := test.Values[0] |
| 321 |
if got != expected { |
| 322 |
t.Errorf("Expected %v, got:%v", expected, got) |
| 323 |
} |
| 324 |
} |
| 325 |
} |
| 326 |
|
| 327 |
// Validate that headers processed by HTTP requests are not changed by |
| 328 |
// NATS through many hops. |
| 329 |
errCh := make(chan error, 2) |
| 330 |
msgCh := make(chan *nats.Msg, 1) |
| 331 |
sub, err = nc.Subscribe("nats.svc.A", func(msg *nats.Msg) { |
| 332 |
hdr := msg.Header["x-trace-id"] |
| 333 |
hdr = append(hdr, "A") |
| 334 |
msg.Header["x-trace-id"] = hdr |
| 335 |
msg.Header.Add("X-Result-A", "A") |
| 336 |
msg.Subject = "nats.svc.B" |
| 337 |
resp, err := nc.RequestMsg(msg, 2*time.Second) |
| 338 |
if err != nil { |
| 339 |
errCh <- err |
| 340 |
return |
| 341 |
} |
| 342 |
|
| 343 |
resp.Subject = msg.Reply |
| 344 |
if err := nc.PublishMsg(resp); err != nil { |
| 345 |
errCh <- err |
| 346 |
return |
| 347 |
} |
| 348 |
}) |
| 349 |
if err != nil { |
| 350 |
t.Fatal(err) |
| 351 |
} |
| 352 |
defer sub.Unsubscribe() |
| 353 |
|
| 354 |
sub, err = nc.Subscribe("nats.svc.B", func(msg *nats.Msg) { |
| 355 |
hdr := msg.Header["x-trace-id"] |
| 356 |
hdr = append(hdr, "B") |
| 357 |
msg.Header["x-trace-id"] = hdr |
| 358 |
msg.Header.Add("X-Result-B", "B") |
| 359 |
msg.Subject = msg.Reply |
| 360 |
msg.Data = []byte("OK!") |
| 361 |
if err := nc.PublishMsg(msg); err != nil { |
| 362 |
errCh <- err |
| 363 |
return |
| 364 |
} |
| 365 |
}) |
| 366 |
if err != nil { |
| 367 |
t.Fatal(err) |
| 368 |
} |
| 369 |
defer sub.Unsubscribe() |
| 370 |
|
| 371 |
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 372 |
msg := nats.NewMsg("nats.svc.A") |
| 373 |
msg.Header = nats.Header(r.Header.Clone()) |
| 374 |
msg.Header["x-trace-id"] = []string{"S"} |
| 375 |
msg.Header["Result-ID"] = []string{"OK"} |
| 376 |
resp, err := nc.RequestMsg(msg, 2*time.Second) |
| 377 |
if err != nil { |
| 378 |
errCh <- err |
| 379 |
return |
| 380 |
} |
| 381 |
msgCh <- resp |
| 382 |
|
| 383 |
for k, v := range resp.Header { |
| 384 |
w.Header()[k] = v |
| 385 |
} |
| 386 |
w.Header()["Date"] = nil |
| 387 |
w.WriteHeader(200) |
| 388 |
fmt.Fprintln(w, string(resp.Data)) |
| 389 |
})) |
| 390 |
defer ts.Close() |
| 391 |
|
| 392 |
req, err := http.NewRequest("GET", ts.URL, nil) |
| 393 |
if err != nil { |
| 394 |
t.Fatal(err) |
| 395 |
} |
| 396 |
|
| 397 |
client := &http.Client{Timeout: 2 * time.Second} |
| 398 |
resp, err := client.Do(req) |
| 399 |
if err != nil { |
| 400 |
t.Fatal(err) |
| 401 |
} |
| 402 |
resp.Body.Close() |
| 403 |
if result := resp.Header.Get("X-Result-A"); result != "A" { |
| 404 |
t.Errorf("Unexpected header value, got: %+v", result) |
| 405 |
} |
| 406 |
if result := resp.Header.Get("X-Result-B"); result != "B" { |
| 407 |
t.Errorf("Unexpected header value, got: %+v", result) |
| 408 |
} |
| 409 |
|
| 410 |
select { |
| 411 |
case <-time.After(1 * time.Second): |
| 412 |
t.Fatal("Timeout waiting for message.") |
| 413 |
case err = <-errCh: |
| 414 |
if err != nil { |
| 415 |
t.Fatal(err) |
| 416 |
} |
| 417 |
case msg = <-msgCh: |
| 418 |
} |
| 419 |
if len(msg.Header) != 6 { |
| 420 |
t.Errorf("Wrong number of headers in NATS message, got: %v", len(msg.Header)) |
| 421 |
} |
| 422 |
|
| 423 |
v, ok := msg.Header["x-trace-id"] |
| 424 |
if !ok { |
| 425 |
t.Fatal("Missing headers in message") |
| 426 |
} |
| 427 |
if !reflect.DeepEqual(v, []string{"S", "A", "B"}) { |
| 428 |
t.Fatal("Missing headers in message") |
| 429 |
} |
| 430 |
for _, key := range []string{"x-trace-id"} { |
| 431 |
v = msg.Header.Values(key) |
| 432 |
if v == nil { |
| 433 |
t.Fatal("Missing headers in message") |
| 434 |
} |
| 435 |
if !reflect.DeepEqual(v, []string{"S", "A", "B"}) { |
| 436 |
t.Fatal("Missing headers in message") |
| 437 |
} |
| 438 |
} |
| 439 |
|
| 440 |
t.Run("multi value header", func(t *testing.T) { |
| 441 |
getHeader := func() nats.Header { |
| 442 |
return nats.Header{ |
| 443 |
"foo": []string{"A"}, |
| 444 |
"Foo": []string{"B"}, |
| 445 |
"FOO": []string{"C"}, |
| 446 |
} |
| 447 |
} |
| 448 |
|
| 449 |
hdr := getHeader() |
| 450 |
if got := hdr.Get("foo"); got != "A" { |
| 451 |
t.Errorf("Expected: %v, got: %v", "A", got) |
| 452 |
} |
| 453 |
if got := hdr.Get("Foo"); got != "B" { |
| 454 |
t.Errorf("Expected: %v, got: %v", "B", got) |
| 455 |
} |
| 456 |
if got := hdr.Get("FOO"); got != "C" { |
| 457 |
t.Errorf("Expected: %v, got: %v", "C", got) |
| 458 |
} |
| 459 |
if got := hdr.Get("fOo"); got != "" { |
| 460 |
t.Errorf("Unexpected result, got: %v", got) |
| 461 |
} |
| 462 |
|
| 463 |
for _, test := range []struct { |
| 464 |
key string |
| 465 |
expectedValues []string |
| 466 |
}{ |
| 467 |
{"foo", []string{"A"}}, |
| 468 |
{"Foo", []string{"B"}}, |
| 469 |
{"FOO", []string{"C"}}, |
| 470 |
{"fOO", nil}, |
| 471 |
{"foO", nil}, |
| 472 |
} { |
| 473 |
t.Run("", func(t *testing.T) { |
| 474 |
hdr := getHeader() |
| 475 |
result := hdr.Values(test.key) |
| 476 |
sort.Strings(result) |
| 477 |
|
| 478 |
if !reflect.DeepEqual(result, test.expectedValues) { |
| 479 |
t.Errorf("Expected: %+v, got: %+v", test.expectedValues, result) |
| 480 |
} |
| 481 |
if hdr.Get(test.key) == "" { |
| 482 |
return |
| 483 |
} |
| 484 |
|
| 485 |
hdr.Del(test.key) |
| 486 |
|
| 487 |
if got := len(hdr); got != 2 { |
| 488 |
t.Errorf("Expected: %v, got: %v", 2, got) |
| 489 |
} |
| 490 |
if result := hdr.Values(test.key); result != nil { |
| 491 |
t.Errorf("Expected to cleanup all matching keys, got: %+v", result) |
| 492 |
} |
| 493 |
if v := hdr.Get(test.key); v != "" { |
| 494 |
t.Errorf("Expected to cleanup all matching keys, got: %v", v) |
| 495 |
} |
| 496 |
}) |
| 497 |
} |
| 498 |
}) |
| 499 |
}) |
| 500 |
} |