TestTCPProxyWithTLS tests proxying an encrypted TCP connection to an unencrypted upstream TCP server. The proxy terminates the TLS connection.
(t *testing.T)
| 99 | // to an unencrypted upstream TCP server. The proxy terminates the |
| 100 | // TLS connection. |
| 101 | func TestTCPProxyWithTLS(t *testing.T) { |
| 102 | srv := tcptest.NewServer(echoHandler) |
| 103 | defer srv.Close() |
| 104 | |
| 105 | // setup cert source |
| 106 | dir := t.TempDir() |
| 107 | |
| 108 | mustWrite := func(name string, data []byte) { |
| 109 | path := filepath.Join(dir, name) |
| 110 | if err := os.WriteFile(path, data, 0644); err != nil { |
| 111 | t.Fatalf("os.WriteFile: %s", err) |
| 112 | } |
| 113 | } |
| 114 | mustWrite("example.com-key.pem", internal.LocalhostKey) |
| 115 | mustWrite("example.com-cert.pem", internal.LocalhostCert) |
| 116 | |
| 117 | // start tcp proxy |
| 118 | proxyAddr := "127.0.0.1:57779" |
| 119 | cs := config.CertSource{Name: "cs", Type: "path", CertPath: dir} |
| 120 | src, err := cert.NewSource(cs) |
| 121 | if err != nil { |
| 122 | t.Fatal("cert.NewSource: ", err) |
| 123 | } |
| 124 | tlscfg, err := cert.TLSConfig(src, false, 0, 0, nil) |
| 125 | if err != nil { |
| 126 | t.Fatal("cert.TLSConfig: ", err) |
| 127 | } |
| 128 | go func() { |
| 129 | |
| 130 | h := &tcp.Proxy{ |
| 131 | Lookup: func(string) *route.Target { |
| 132 | return &route.Target{URL: &url.URL{Host: srv.Addr}} |
| 133 | }, |
| 134 | } |
| 135 | |
| 136 | l := config.Listen{Addr: proxyAddr} |
| 137 | if err := ListenAndServeTCP(l, h, tlscfg); err != nil { |
| 138 | // closing the listener returns this error from the accept loop |
| 139 | // which we can ignore. |
| 140 | if err.Error() != "accept tcp 127.0.0.1:57779: use of closed network connection" { |
| 141 | t.Log("ListenAndServeTCP: ", err) |
| 142 | } |
| 143 | } |
| 144 | }() |
| 145 | defer Close() |
| 146 | |
| 147 | rootCAs := x509.NewCertPool() |
| 148 | if ok := rootCAs.AppendCertsFromPEM(internal.LocalhostCert); !ok { |
| 149 | t.Fatal("could not parse cert") |
| 150 | } |
| 151 | cfg := &tls.Config{ |
| 152 | RootCAs: rootCAs, |
| 153 | ServerName: "example.com", |
| 154 | } |
| 155 | |
| 156 | // connect to proxy |
| 157 | out, err := tcptest.NewTLSRetryDialer(cfg).Dial("tcp", proxyAddr) |
| 158 | if err != nil { |
nothing calls this directly
no test coverage detected