github.com/lmb/consul@v1.4.1/connect/proxy/proxy_test.go (about) 1 package proxy 2 3 import ( 4 "context" 5 "log" 6 "net" 7 "os" 8 "testing" 9 10 "github.com/hashicorp/consul/testrpc" 11 12 "github.com/hashicorp/consul/agent" 13 agConnect "github.com/hashicorp/consul/agent/connect" 14 "github.com/hashicorp/consul/api" 15 "github.com/hashicorp/consul/connect" 16 "github.com/hashicorp/consul/lib/freeport" 17 "github.com/hashicorp/consul/testutil/retry" 18 "github.com/stretchr/testify/require" 19 ) 20 21 func TestProxy_public(t *testing.T) { 22 t.Parallel() 23 24 require := require.New(t) 25 ports := freeport.GetT(t, 1) 26 27 a := agent.NewTestAgent(t.Name(), "") 28 defer a.Shutdown() 29 testrpc.WaitForTestAgent(t, a.RPC, "dc1") 30 client := a.Client() 31 32 // Register the service so we can get a leaf cert 33 _, err := client.Catalog().Register(&api.CatalogRegistration{ 34 Datacenter: "dc1", 35 Node: "local", 36 Address: "127.0.0.1", 37 Service: &api.AgentService{ 38 Service: "echo", 39 }, 40 }, nil) 41 require.NoError(err) 42 43 // Start the backend service that is being proxied 44 testApp := NewTestTCPServer(t) 45 defer testApp.Close() 46 47 // Start the proxy 48 p, err := New(client, NewStaticConfigWatcher(&Config{ 49 ProxiedServiceName: "echo", 50 PublicListener: PublicListenerConfig{ 51 BindAddress: "127.0.0.1", 52 BindPort: ports[0], 53 LocalServiceAddress: testApp.Addr().String(), 54 }, 55 }), testLogger(t)) 56 require.NoError(err) 57 defer p.Close() 58 go p.Serve() 59 60 // Create a test connection to the proxy. We retry here a few times 61 // since this is dependent on the agent actually starting up and setting 62 // up the CA. 63 var conn net.Conn 64 svc, err := connect.NewService("echo", client) 65 require.NoError(err) 66 retry.Run(t, func(r *retry.R) { 67 conn, err = svc.Dial(context.Background(), &connect.StaticResolver{ 68 Addr: TestLocalAddr(ports[0]), 69 CertURI: agConnect.TestSpiffeIDService(t, "echo"), 70 }) 71 if err != nil { 72 r.Fatalf("err: %s", err) 73 } 74 }) 75 76 // Connection works, test it is the right one 77 TestEchoConn(t, conn, "") 78 } 79 80 func testLogger(t *testing.T) *log.Logger { 81 return log.New(os.Stderr, "", log.LstdFlags) 82 }