Debian Codegraph @

test/auth_test.go

raw
1 // Copyright 2012-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 "errors"
18 "fmt"
19 "io/fs"
20 "strings"
21 "sync/atomic"
22 "testing"
23 "time"
24
25 "github.com/nats-io/nats.go"
26 testservice "github.com/synadia-io/orbit.go/ntf-client"
27 )
28
29 func TestAuth(t *testing.T) {
30 c := newTester(t)
31 authBody := `authorization {
32 user: derek
33 password: foo
34 }`
35 inst := c.CreateServer(t, false, singleUserPassOpts(authBody)...)
36 t.Cleanup(func() { inst.Destroy(t) })
37
38 url := inst.Servers[0].URL
39 hostPort := hostPortFromURL(url)
40
41 _, err := nats.Connect(url)
42 if err == nil {
43 t.Fatal("Should have received an error while trying to connect")
44 }
45
46 // This test may be a bit too strict for the future, but for now makes
47 // sure that we correctly process the -ERR content on connect.
48 if strings.ToLower(err.Error()) != nats.ErrAuthorization.Error() {
49 t.Fatalf("Expected error '%v', got '%v'", nats.ErrAuthorization, err)
50 }
51
52 if !errors.Is(err, nats.ErrAuthorization) {
53 t.Fatalf("Expected error '%v', got '%v'", nats.ErrAuthorization, err)
54 }
55
56 nc, err := nats.Connect(fmt.Sprintf("nats://derek:foo@%s", hostPort))
57 if err != nil {
58 t.Fatal("Should have connected successfully with a token")
59 }
60 nc.Close()
61
62 // Use Options
63 nc, err = nats.Connect(url, nats.UserInfo("derek", "foo"))
64 if err != nil {
65 t.Fatalf("Should have connected successfully with a token: %v", err)
66 }
67 nc.Close()
68 // Verify that credentials in URL take precedence.
69 nc, err = nats.Connect(fmt.Sprintf("nats://derek:foo@%s", hostPort), nats.UserInfo("foo", "bar"))
70 if err != nil {
71 t.Fatalf("Should have connected successfully with a token: %v", err)
72 }
73 nc.Close()
74 }
75
76 func TestAuthFailNoDisconnectErrCB(t *testing.T) {
77 c := newTester(t)
78 authBody := `authorization {
79 user: derek
80 password: foo
81 }`
82 inst := c.CreateServer(t, false, singleUserPassOpts(authBody)...)
83 t.Cleanup(func() { inst.Destroy(t) })
84
85 copts := nats.GetDefaultOptions()
86 copts.Url = inst.Servers[0].URL
87 receivedDisconnectErrCB := int32(0)
88 copts.DisconnectedErrCB = func(nc *nats.Conn, _ error) {
89 atomic.AddInt32(&receivedDisconnectErrCB, 1)
90 }
91
92 _, err := copts.Connect()
93 if err == nil {
94 t.Fatal("Should have received an error while trying to connect")
95 }
96 if atomic.LoadInt32(&receivedDisconnectErrCB) > 0 {
97 t.Fatal("Should not have received a disconnect callback on auth failure")
98 }
99 }
100
101 func TestAuthFailAllowReconnect(t *testing.T) {
102 c := newTester(t)
103
104 ts := c.CreateServer(t, false)
105 t.Cleanup(func() { ts.Destroy(t) })
106
107 authBody := `authorization {
108 user: ivan
109 password: foo
110 }`
111 ts2 := c.CreateServer(t, false, singleUserPassOpts(authBody)...)
112 t.Cleanup(func() { ts2.Destroy(t) })
113
114 ts3 := c.CreateServer(t, false)
115 t.Cleanup(func() { ts3.Destroy(t) })
116
117 servers := []string{
118 ts.Servers[0].URL,
119 ts2.Servers[0].URL,
120 ts3.Servers[0].URL,
121 }
122
123 reconnectch := make(chan bool)
124 defer close(reconnectch)
125
126 copts := nats.GetDefaultOptions()
127 copts.Servers = servers
128 copts.AllowReconnect = true
129 copts.NoRandomize = true
130 copts.MaxReconnect = 10
131 copts.ReconnectWait = 100 * time.Millisecond
132 nats.ReconnectJitter(0, 0)(&copts)
133
134 copts.ReconnectedCB = func(_ *nats.Conn) {
135 reconnectch <- true
136 }
137
138 // Connect
139 nc, err := copts.Connect()
140 if err != nil {
141 t.Fatalf("Should have connected ok: %v", err)
142 }
143 defer nc.Close()
144
145 // Override default handler for test.
146 nc.SetErrorHandler(func(_ *nats.Conn, _ *nats.Subscription, _ error) {})
147
148 // Stop the server
149 ts.StopServer(t, ts.Servers[0])
150
151 // The client will try to connect to the second server, and that
152 // should fail. It should then try to connect to the third and succeed.
153
154 // Wait for the reconnect CB.
155 if e := Wait(reconnectch); e != nil {
156 t.Fatal("Reconnect callback should have been triggered")
157 }
158
159 if nc.IsClosed() {
160 t.Fatal("Should have reconnected")
161 }
162
163 if nc.ConnectedUrl() != servers[2] {
164 t.Fatalf("Should have reconnected to %s, reconnected to %s instead", servers[2], nc.ConnectedUrl())
165 }
166 }
167
168 func TestTokenHandlerReconnect(t *testing.T) {
169 c := newTester(t)
170
171 // Server 1 has no authorization at all — neutralize the default
172 // accounts/system_account/no_auth_user so any client (including ones
173 // sending a token) is allowed in.
174 ts := c.CreateServer(t, false, singleUserPassOpts(`# no authorization required`)...)
175 t.Cleanup(func() { ts.Destroy(t) })
176
177 secret := "S3Cr3T0k3n!"
178 authBody := fmt.Sprintf(`authorization {
179 token: %q
180 }`, secret)
181 ts2 := c.CreateServer(t, false, singleUserPassOpts(authBody)...)
182 t.Cleanup(func() { ts2.Destroy(t) })
183
184 servers := []string{
185 ts.Servers[0].URL,
186 ts2.Servers[0].URL,
187 }
188
189 reconnectch := make(chan bool)
190 defer close(reconnectch)
191
192 copts := nats.GetDefaultOptions()
193 copts.Servers = servers
194 copts.AllowReconnect = true
195 copts.NoRandomize = true
196 copts.MaxReconnect = 10
197 copts.ReconnectWait = 100 * time.Millisecond
198 nats.ReconnectJitter(0, 0)(&copts)
199
200 copts.TokenHandler = func() string {
201 return secret
202 }
203
204 copts.ReconnectedCB = func(_ *nats.Conn) {
205 reconnectch <- true
206 }
207
208 // Connect
209 nc, err := copts.Connect()
210 if err != nil {
211 t.Fatalf("Should have connected ok: %v", err)
212 }
213 defer nc.Close()
214
215 // Stop the server
216 ts.StopServer(t, ts.Servers[0])
217
218 // The client will try to connect to the second server and succeed.
219
220 // Wait for the reconnect CB.
221 if e := Wait(reconnectch); e != nil {
222 t.Fatal("Reconnect callback should have been triggered")
223 }
224
225 if nc.IsClosed() {
226 t.Fatal("Should have reconnected")
227 }
228
229 if nc.ConnectedUrl() != servers[1] {
230 t.Fatalf("Should have reconnected to %s, reconnected to %s instead", servers[1], nc.ConnectedUrl())
231 }
232 }
233
234 func TestTokenAuth(t *testing.T) {
235 c := newTester(t)
236 secret := "S3Cr3T0k3n!"
237 authBody := fmt.Sprintf(`authorization {
238 token: %q
239 }`, secret)
240 inst := c.CreateServer(t, false, singleUserPassOpts(authBody)...)
241 t.Cleanup(func() { inst.Destroy(t) })
242
243 url := inst.Servers[0].URL
244 hostPort := hostPortFromURL(url)
245
246 _, err := nats.Connect(url)
247 if err == nil {
248 t.Fatal("Should have received an error while trying to connect")
249 }
250
251 tokenURL := fmt.Sprintf("nats://%s@%s", secret, hostPort)
252 nc, err := nats.Connect(tokenURL)
253 if err != nil {
254 t.Fatal("Should have connected successfully")
255 }
256 nc.Close()
257
258 // Use Options
259 nc, err = nats.Connect(url, nats.Token(secret))
260 if err != nil {
261 t.Fatalf("Should have connected successfully: %v", err)
262 }
263 nc.Close()
264 // Verify that token cannot be set when token handler is provided.
265 _, err = nats.Connect(url, nats.TokenHandler(func() string { return secret }), nats.Token(secret))
266 if err == nil {
267 t.Fatal("Should have received an error while trying to connect")
268 }
269 // Verify that token handler cannot be provided when token is set.
270 _, err = nats.Connect(url, nats.Token(secret), nats.TokenHandler(func() string { return secret }))
271 if err == nil {
272 t.Fatal("Should have received an error while trying to connect")
273 }
274 // Verify that token in the URL takes precedence.
275 nc, err = nats.Connect(tokenURL, nats.Token("badtoken"))
276 if err != nil {
277 t.Fatalf("Should have connected successfully: %v", err)
278 }
279 nc.Close()
280 }
281
282 func TestTokenHandlerAuth(t *testing.T) {
283 c := newTester(t)
284 secret := "S3Cr3T0k3n!"
285 authBody := fmt.Sprintf(`authorization {
286 token: %q
287 }`, secret)
288 inst := c.CreateServer(t, false, singleUserPassOpts(authBody)...)
289 t.Cleanup(func() { inst.Destroy(t) })
290
291 url := inst.Servers[0].URL
292 hostPort := hostPortFromURL(url)
293
294 _, err := nats.Connect(url)
295 if err == nil {
296 t.Fatal("Should have received an error while trying to connect")
297 }
298
299 tokenURL := fmt.Sprintf("nats://%s@%s", secret, hostPort)
300 nc, err := nats.Connect(tokenURL)
301 if err != nil {
302 t.Fatal("Should have connected successfully")
303 }
304 nc.Close()
305
306 // Use Options
307 nc, err = nats.Connect(url, nats.TokenHandler(func() string { return secret }))
308 if err != nil {
309 t.Fatalf("Should have connected successfully: %v", err)
310 }
311 nc.Close()
312 // Verify that token cannot be set when token handler is provided.
313 _, err = nats.Connect(url, nats.TokenHandler(func() string { return secret }), nats.Token(secret))
314 if err == nil {
315 t.Fatal("Should have received an error while trying to connect")
316 }
317 // Verify that token handler cannot be provided when token is set.
318 _, err = nats.Connect(url, nats.Token(secret), nats.TokenHandler(func() string { return secret }))
319 if err == nil {
320 t.Fatal("Should have received an error while trying to connect")
321 }
322 // Verify that token handler cannot be provided when token is in URL.
323 _, err = nats.Connect(tokenURL, nats.TokenHandler(func() string { return secret }))
324 if err == nil {
325 t.Fatal("Should have received an error while trying to connect")
326 }
327 }
328
329 func TestPermViolation(t *testing.T) {
330 c := newTester(t)
331 authBody := `authorization {
332 users: [
333 {
334 user: "ivan"
335 password: "pwd"
336 permissions: {
337 publish: { allow: ["Foo"] }
338 subscribe: { allow: ["Bar"] }
339 }
340 }
341 ]
342 }`
343 inst := c.CreateServer(t, false, singleUserPassOpts(authBody)...)
344 t.Cleanup(func() { inst.Destroy(t) })
345
346 hostPort := hostPortFromURL(inst.Servers[0].URL)
347
348 errCh := make(chan error, 2)
349 errCB := func(_ *nats.Conn, _ *nats.Subscription, err error) {
350 errCh <- err
351 }
352 nc, err := nats.Connect(
353 fmt.Sprintf("nats://ivan:pwd@%s", hostPort),
354 nats.ErrorHandler(errCB))
355 if err != nil {
356 t.Fatalf("Error on connect: %v", err)
357 }
358 defer nc.Close()
359
360 // Cause a publish error
361 nc.Publish("Bar", []byte("fail"))
362 // Cause a subscribe error
363 nc.Subscribe("Foo", func(_ *nats.Msg) {})
364
365 expectedErrorTypes := []string{"publish", "subscription"}
366 for _, expectedErr := range expectedErrorTypes {
367 select {
368 case e := <-errCh:
369 if !strings.Contains(strings.ToLower(e.Error()), nats.PERMISSIONS_ERR) {
370 t.Fatalf("Did not receive error about permissions")
371 }
372 if !strings.Contains(strings.ToLower(e.Error()), expectedErr) {
373 t.Fatalf("Did not receive error about %q, got %v", expectedErr, e.Error())
374 }
375 // Make sure subject is not converted to lower case
376 if expectedErr == "publish" && !strings.Contains(e.Error(), "Bar") {
377 t.Fatalf("Subject Bar not found in error: %v", e)
378 } else if expectedErr == "subscribe" && !strings.Contains(e.Error(), "Foo") {
379 t.Fatalf("Subject Foo not found in error: %v", e)
380 }
381 case <-time.After(2 * time.Second):
382 t.Fatalf("Did not get the permission error")
383 }
384 }
385 // Make sure connection has not been closed
386 if nc.IsClosed() {
387 t.Fatal("Connection should be not be closed")
388 }
389 }
390
391 func TestConnectMissingCreds(t *testing.T) {
392 withServerInstance(t, func(t *testing.T, _ *nats.Conn, inst *testservice.Instance) {
393 // Using TEST-NET sample address from RFC 5737.
394 testnetaddr := "nats://192.0.2.2:4222"
395 _, err := nats.Connect(fmt.Sprintf("%s,%s", inst.Servers[0].URL, testnetaddr), nats.UserCredentials("missing"), nats.DontRandomize())
396 if !errors.Is(err, fs.ErrNotExist) {
397 t.Fatalf("Expected not exists error, got: %v", err)
398 }
399 })
400 }
401
402 func TestUserInfoHandler(t *testing.T) {
403 c := newTester(t)
404 initialAccounts := `accounts: {
405 A {
406 users: [{ user: "pp", password: "foo" }]
407 }
408 }`
409 inst := c.CreateServer(t, false,
410 testservice.WithAccounts(initialAccounts),
411 testservice.WithAuthorization("# no_auth_user intentionally unset"),
412 testservice.WithSystemAccount(noSystemAccountBody()),
413 )
414 t.Cleanup(func() { inst.Destroy(t) })
415
416 user, pass := "pp", "foo"
417 userInfoCB := func() (string, string) {
418 return user, pass
419 }
420
421 // cannot set the user info twice
422 _, err := nats.Connect(inst.Servers[0].URL, nats.UserInfo("pp", "foo"), nats.UserInfoHandler(userInfoCB))
423 if !errors.Is(err, nats.ErrUserInfoAlreadySet) {
424 t.Fatalf("Expected ErrUserInfoAlreadySet, got: %v", err)
425 }
426
427 // user/pass from url takes precedence
428 badURL := fmt.Sprintf("nats://bad:bad@%s:%d", testerHost(t), inst.Servers[0].Port)
429 _, err = nats.Connect(badURL, nats.UserInfoHandler(userInfoCB))
430 if !errors.Is(err, nats.ErrAuthorization) {
431 t.Fatalf("Expected ErrAuthorization, got: %v", err)
432 }
433
434 nc, err := nats.Connect(inst.Servers[0].URL,
435 nats.ReconnectWait(100*time.Millisecond),
436 nats.UserInfoHandler(userInfoCB))
437 if err != nil {
438 t.Fatalf("Error on connect: %v", err)
439 }
440 defer nc.Close()
441
442 // swap the user via UpdateServer + ReloadServer (SIGHUP)
443 newAccounts := `accounts: {
444 A {
445 users: [{ user: "dd", password: "bar" }]
446 }
447 }`
448 inst.UpdateServer(t, inst.Servers[0],
449 testservice.WithAccounts(newAccounts),
450 testservice.WithAuthorization("# no_auth_user intentionally unset"),
451 testservice.WithSystemAccount(noSystemAccountBody()),
452 )
453
454 user, pass = "dd", "bar"
455 status := nc.StatusChanged(nats.CONNECTED)
456 inst.ReloadServer(t, inst.Servers[0])
457 WaitOnChannel(t, status, nats.CONNECTED)
458 }