MCPcopy
hub / github.com/nats-io/nats.go / TestUserInfoHandler

Function TestUserInfoHandler

test/auth_test.go:383–453  ·  view source on GitHub ↗
(t *testing.T)

Source from the content-addressed store, hash-verified

381}
382
383func TestUserInfoHandler(t *testing.T) {
384 conf := createConfFile(t, []byte(`
385 listen: 127.0.0.1:-1
386 accounts: {
387 A {
388 users: [{ user: "pp", password: "foo" }]
389 }
390 }
391`))
392 defer os.Remove(conf)
393
394 s, _ := RunServerWithConfig(conf)
395 defer s.Shutdown()
396
397 user, pass := "pp", "foo"
398 userInfoCB := func() (string, string) {
399 return user, pass
400 }
401
402 // check that we cannot set the user info twice
403 _, err := nats.Connect(s.ClientURL(), nats.UserInfo("pp", "foo"), nats.UserInfoHandler(userInfoCB))
404 if !errors.Is(err, nats.ErrUserInfoAlreadySet) {
405 t.Fatalf("Expected ErrUserInfoAlreadySet, got: %v", err)
406 }
407
408 addr, ok := s.Addr().(*net.TCPAddr)
409 if !ok {
410 t.Fatalf("Expected a TCP address, got %T", addr)
411 }
412
413 // check that user/pass from url takes precedence
414 _, err = nats.Connect(fmt.Sprintf("nats://bad:bad@localhost:%d", addr.Port),
415 nats.UserInfoHandler(userInfoCB))
416 if !errors.Is(err, nats.ErrAuthorization) {
417 t.Fatalf("Expected ErrAuthorization, got: %v", err)
418 }
419
420 // connect using the handler
421 nc, err := nats.Connect(s.ClientURL(),
422 nats.ReconnectWait(100*time.Millisecond),
423 nats.UserInfoHandler(userInfoCB))
424 if err != nil {
425 t.Fatalf("Error on connect: %v", err)
426 }
427 defer nc.Close()
428
429 // now change the password and reload the server
430 newConfig := []byte(`
431 listen: 127.0.0.1:-1
432 accounts: {
433 A {
434 users: [{ user: "dd", password: "bar" }]
435 }
436 }
437`)
438 if err := os.WriteFile(conf, newConfig, 0666); err != nil {
439 t.Fatalf("Error writing conf file: %v", err)
440 }

Callers

nothing calls this directly

Calls 8

WaitOnChannelFunction · 0.85
ConnectMethod · 0.80
FatalfMethod · 0.80
createConfFileFunction · 0.70
RunServerWithConfigFunction · 0.70
IsMethod · 0.45
CloseMethod · 0.45
StatusChangedMethod · 0.45

Tested by

no test coverage detected