get.pme.sh/pnats@v0.0.0-20240304004023-26bb5a137ed0/test/client_auth_test.go (about) 1 // Copyright 2016-2019 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 "fmt" 18 "os" 19 "testing" 20 21 "github.com/nats-io/nats.go" 22 ) 23 24 func TestMultipleUserAuth(t *testing.T) { 25 srv, opts := RunServerWithConfig("./configs/multi_user.conf") 26 defer srv.Shutdown() 27 28 if opts.Users == nil { 29 t.Fatal("Expected a user array that is not nil") 30 } 31 if len(opts.Users) != 2 { 32 t.Fatal("Expected a user array that had 2 users") 33 } 34 35 // Test first user 36 url := fmt.Sprintf("nats://%s:%s@%s:%d/", 37 opts.Users[0].Username, 38 opts.Users[0].Password, 39 opts.Host, opts.Port) 40 41 nc, err := nats.Connect(url) 42 if err != nil { 43 t.Fatalf("Expected a successful connect, got %v\n", err) 44 } 45 defer nc.Close() 46 47 if !nc.AuthRequired() { 48 t.Fatal("Expected auth to be required for the server") 49 } 50 51 // Test second user 52 url = fmt.Sprintf("nats://%s:%s@%s:%d/", 53 opts.Users[1].Username, 54 opts.Users[1].Password, 55 opts.Host, opts.Port) 56 57 nc, err = nats.Connect(url) 58 if err != nil { 59 t.Fatalf("Expected a successful connect, got %v\n", err) 60 } 61 defer nc.Close() 62 } 63 64 // Resolves to "test" 65 const testToken = "$2a$05$3sSWEVA1eMCbV0hWavDjXOx.ClBjI6u1CuUdLqf22cbJjXsnzz8/." 66 67 func TestTokenInConfig(t *testing.T) { 68 content := ` 69 listen: 127.0.0.1:4567 70 authorization={ 71 token: ` + testToken + ` 72 timeout: 5 73 }` 74 confFile := createConfFile(t, []byte(content)) 75 if err := os.WriteFile(confFile, []byte(content), 0666); err != nil { 76 t.Fatalf("Error writing config file: %v", err) 77 } 78 s, opts := RunServerWithConfig(confFile) 79 defer s.Shutdown() 80 81 url := fmt.Sprintf("nats://test@%s:%d/", opts.Host, opts.Port) 82 nc, err := nats.Connect(url) 83 if err != nil { 84 t.Fatalf("Expected a successful connect, got %v\n", err) 85 } 86 defer nc.Close() 87 if !nc.AuthRequired() { 88 t.Fatal("Expected auth to be required for the server") 89 } 90 }