|
| 1 | +//go:build integration && scylla |
| 2 | +// +build integration,scylla |
| 3 | + |
| 4 | +package gocql_test |
| 5 | + |
| 6 | +import ( |
| 7 | + "bytes" |
| 8 | + "context" |
| 9 | + "crypto/tls" |
| 10 | + "fmt" |
| 11 | + "io" |
| 12 | + "net" |
| 13 | + "os" |
| 14 | + "strings" |
| 15 | + "sync" |
| 16 | + "testing" |
| 17 | + "time" |
| 18 | + |
| 19 | + "github.com/gocql/gocql" |
| 20 | + "github.com/gocql/gocql/scyllacloud" |
| 21 | + "sigs.k8s.io/yaml" |
| 22 | +) |
| 23 | + |
| 24 | +func TestCloudConnection(t *testing.T) { |
| 25 | + if !*gocql.FlagRunSslTest { |
| 26 | + t.Skip("Skipping because SSL is not enabled on cluster") |
| 27 | + } |
| 28 | + |
| 29 | + const ( |
| 30 | + sslPort = 9142 |
| 31 | + datacenterName = "datacenter1" |
| 32 | + ) |
| 33 | + ctx, cancel := context.WithCancel(context.Background()) |
| 34 | + defer cancel() |
| 35 | + |
| 36 | + hosts := map[string]string{} |
| 37 | + |
| 38 | + cluster := gocql.CreateCluster(func(config *gocql.ClusterConfig) { |
| 39 | + config.Port = sslPort |
| 40 | + }) |
| 41 | + session, err := cluster.CreateSession() |
| 42 | + if err != nil { |
| 43 | + t.Fatal(err) |
| 44 | + } |
| 45 | + |
| 46 | + var localAddress string |
| 47 | + var localHostID gocql.UUID |
| 48 | + scanner := session.Query("SELECT broadcast_address, host_id FROM system.local").Iter().Scanner() |
| 49 | + if scanner.Next() { |
| 50 | + if err := scanner.Scan(&localAddress, &localHostID); err != nil { |
| 51 | + t.Fatal(err) |
| 52 | + } |
| 53 | + hosts[localHostID.String()] = net.JoinHostPort(localAddress, fmt.Sprintf("%d", sslPort)) |
| 54 | + } |
| 55 | + |
| 56 | + var peerAddress string |
| 57 | + var peerHostID gocql.UUID |
| 58 | + scanner = session.Query("SELECT peer, host_id FROM system.peers").Iter().Scanner() |
| 59 | + for scanner.Next() { |
| 60 | + if err := scanner.Scan(&peerAddress, &peerHostID); err != nil { |
| 61 | + t.Fatal(err) |
| 62 | + } |
| 63 | + hosts[peerHostID.String()] = net.JoinHostPort(peerAddress, fmt.Sprintf("%d", sslPort)) |
| 64 | + } |
| 65 | + |
| 66 | + session.Close() |
| 67 | + |
| 68 | + logger := gocql.TestLogger |
| 69 | + defer func() { |
| 70 | + if t.Failed() { |
| 71 | + os.Stdout.WriteString(logger.String()) |
| 72 | + } |
| 73 | + }() |
| 74 | + |
| 75 | + proxy := &sniProxy{ |
| 76 | + hosts: hosts, |
| 77 | + defaultBackend: net.JoinHostPort(localAddress, fmt.Sprintf("%d", sslPort)), |
| 78 | + logger: logger, |
| 79 | + } |
| 80 | + |
| 81 | + proxyAddress, err := proxy.Run(ctx) |
| 82 | + if err != nil { |
| 83 | + t.Fatal(err) |
| 84 | + } |
| 85 | + defer proxy.Close() |
| 86 | + |
| 87 | + cc := &scyllacloud.ConnectionConfig{ |
| 88 | + Datacenters: map[string]*scyllacloud.Datacenter{ |
| 89 | + datacenterName: { |
| 90 | + CertificateAuthorityPath: "testdata/pki/ca.crt", |
| 91 | + Server: proxyAddress, |
| 92 | + TLSServerName: "any", |
| 93 | + NodeDomain: "cloud.scylladb.com", |
| 94 | + InsecureSkipTLSVerify: true, |
| 95 | + }, |
| 96 | + }, |
| 97 | + AuthInfos: map[string]*scyllacloud.AuthInfo{ |
| 98 | + "ai-1": { |
| 99 | + Username: "username", |
| 100 | + Password: "password", |
| 101 | + ClientKeyPath: "testdata/pki/gocql.key", |
| 102 | + ClientCertificatePath: "testdata/pki/gocql.crt", |
| 103 | + }, |
| 104 | + }, |
| 105 | + Contexts: map[string]*scyllacloud.Context{ |
| 106 | + "default-context": { |
| 107 | + AuthInfoName: "ai-1", |
| 108 | + DatacenterName: datacenterName, |
| 109 | + }, |
| 110 | + }, |
| 111 | + CurrentContext: "default-context", |
| 112 | + } |
| 113 | + |
| 114 | + configPath, err := writeYamlToTempFile(cc) |
| 115 | + if err != nil { |
| 116 | + t.Fatal(err) |
| 117 | + } |
| 118 | + defer os.RemoveAll(configPath) |
| 119 | + |
| 120 | + cluster, err = scyllacloud.NewCloudCluster(configPath) |
| 121 | + if err != nil { |
| 122 | + t.Fatal(err) |
| 123 | + } |
| 124 | + // Forward connections directed to node domain to our test sni proxy. |
| 125 | + cluster.Dialer = dialerContextFunc(func(ctx context.Context, network, addr string) (net.Conn, error) { |
| 126 | + if strings.Contains(addr, cc.Datacenters[datacenterName].NodeDomain) { |
| 127 | + addr = cc.Datacenters[datacenterName].Server |
| 128 | + } |
| 129 | + return net.Dial(network, addr) |
| 130 | + }) |
| 131 | + |
| 132 | + session, err = cluster.CreateSession() |
| 133 | + if err != nil { |
| 134 | + t.Fatal(err) |
| 135 | + } |
| 136 | + |
| 137 | + if err := gocql.WaitUntilPoolsStopFilling(ctx, session, 10*time.Second); err != nil { |
| 138 | + t.Fatal(err) |
| 139 | + } |
| 140 | + |
| 141 | + ringHosts := gocql.GetRingAllHosts(session) |
| 142 | + if len(ringHosts) != len(hosts) { |
| 143 | + t.Errorf("expected %d hosts in ring, got %d", len(hosts), len(ringHosts)) |
| 144 | + } |
| 145 | + |
| 146 | + snisCount := map[string]int{} |
| 147 | + events := proxy.GetEvents() |
| 148 | + for _, event := range events { |
| 149 | + snisCount[event]++ |
| 150 | + } |
| 151 | + |
| 152 | + for hostID := range hosts { |
| 153 | + sni := fmt.Sprintf("%s.%s", hostID, cc.Datacenters[datacenterName].NodeDomain) |
| 154 | + count, ok := snisCount[sni] |
| 155 | + if !ok { |
| 156 | + t.Errorf("not found connection to host %q", hostID) |
| 157 | + } |
| 158 | + if count != cluster.NumConns { |
| 159 | + t.Errorf("expected %d connections to host %q, got %d", cluster.NumConns, sni, count) |
| 160 | + } |
| 161 | + } |
| 162 | +} |
| 163 | + |
| 164 | +func writeYamlToTempFile(obj interface{}) (string, error) { |
| 165 | + f, err := os.CreateTemp(os.TempDir(), "gocql-cloud") |
| 166 | + if err != nil { |
| 167 | + return "", fmt.Errorf("create temp file: %w", err) |
| 168 | + } |
| 169 | + if err := f.Close(); err != nil { |
| 170 | + return "", fmt.Errorf("close temp file: %w", err) |
| 171 | + } |
| 172 | + |
| 173 | + buf, err := yaml.Marshal(obj) |
| 174 | + if err != nil { |
| 175 | + return "", fmt.Errorf("marshal yaml: %w", err) |
| 176 | + } |
| 177 | + if err := os.WriteFile(f.Name(), buf, 0600); err != nil { |
| 178 | + return "", fmt.Errorf("write to file %q: %w", f.Name(), err) |
| 179 | + } |
| 180 | + |
| 181 | + return f.Name(), nil |
| 182 | +} |
| 183 | + |
| 184 | +type dialerContextFunc func(ctx context.Context, network, addr string) (net.Conn, error) |
| 185 | + |
| 186 | +func (d dialerContextFunc) DialContext(ctx context.Context, network, addr string) (net.Conn, error) { |
| 187 | + return d(ctx, network, addr) |
| 188 | +} |
| 189 | + |
| 190 | +type sniProxy struct { |
| 191 | + hosts map[string]string |
| 192 | + defaultBackend string |
| 193 | + logger gocql.StdLogger |
| 194 | + |
| 195 | + listener net.Listener |
| 196 | + events []string |
| 197 | + mu sync.Mutex |
| 198 | +} |
| 199 | + |
| 200 | +func (p *sniProxy) Run(ctx context.Context) (string, error) { |
| 201 | + listener, err := net.Listen("tcp", "127.0.0.1:0") |
| 202 | + if err != nil { |
| 203 | + return "", fmt.Errorf("failed to listen: %w", err) |
| 204 | + } |
| 205 | + |
| 206 | + p.listener = listener |
| 207 | + |
| 208 | + go func() { |
| 209 | + for { |
| 210 | + conn, err := p.listener.Accept() |
| 211 | + if err != nil { |
| 212 | + p.logger.Println("failed to accept connection", err) |
| 213 | + return |
| 214 | + } |
| 215 | + |
| 216 | + go p.handleConnection(conn) |
| 217 | + } |
| 218 | + |
| 219 | + }() |
| 220 | + |
| 221 | + return listener.Addr().String(), nil |
| 222 | +} |
| 223 | + |
| 224 | +func (p *sniProxy) handleConnection(conn net.Conn) { |
| 225 | + defer conn.Close() |
| 226 | + |
| 227 | + var hello *tls.ClientHelloInfo |
| 228 | + |
| 229 | + peekedBytes := &bytes.Buffer{} |
| 230 | + // Ignore error because TLS library returns it when nil TLSConfig is returned. |
| 231 | + _ = tls.Server(readOnlyConn{reader: io.TeeReader(conn, peekedBytes)}, &tls.Config{ |
| 232 | + GetConfigForClient: func(argHello *tls.ClientHelloInfo) (*tls.Config, error) { |
| 233 | + hello = &tls.ClientHelloInfo{} |
| 234 | + *hello = *argHello |
| 235 | + return nil, nil |
| 236 | + }, |
| 237 | + }).Handshake() |
| 238 | + |
| 239 | + if hello == nil { |
| 240 | + p.logger.Println("client hello not sent") |
| 241 | + return |
| 242 | + } |
| 243 | + |
| 244 | + p.mu.Lock() |
| 245 | + p.events = append(p.events, hello.ServerName) |
| 246 | + p.mu.Unlock() |
| 247 | + |
| 248 | + backend, ok := p.hosts[hello.ServerName] |
| 249 | + if !ok { |
| 250 | + backend = p.defaultBackend |
| 251 | + } |
| 252 | + |
| 253 | + p.logger.Println("Dialing backend", backend, "SNI", hello.ServerName) |
| 254 | + backendConn, err := net.Dial("tcp", backend) |
| 255 | + if err != nil { |
| 256 | + p.logger.Println("failed to dial backend", backend, err) |
| 257 | + return |
| 258 | + } |
| 259 | + defer backendConn.Close() |
| 260 | + |
| 261 | + var wg sync.WaitGroup |
| 262 | + wg.Add(2) |
| 263 | + |
| 264 | + go func() { |
| 265 | + _, _ = io.Copy(conn, backendConn) |
| 266 | + wg.Done() |
| 267 | + }() |
| 268 | + go func() { |
| 269 | + _, _ = io.Copy(backendConn, peekedBytes) |
| 270 | + _, _ = io.Copy(backendConn, conn) |
| 271 | + wg.Done() |
| 272 | + }() |
| 273 | + |
| 274 | + wg.Wait() |
| 275 | +} |
| 276 | + |
| 277 | +func (p *sniProxy) Close() error { |
| 278 | + return p.listener.Close() |
| 279 | +} |
| 280 | + |
| 281 | +func (p *sniProxy) GetEvents() []string { |
| 282 | + p.mu.Lock() |
| 283 | + defer p.mu.Unlock() |
| 284 | + events := make([]string, 0, len(p.events)) |
| 285 | + for _, e := range p.events { |
| 286 | + events = append(events, e) |
| 287 | + } |
| 288 | + return events |
| 289 | +} |
| 290 | + |
| 291 | +type readOnlyConn struct { |
| 292 | + reader io.Reader |
| 293 | +} |
| 294 | + |
| 295 | +var _ net.Conn = readOnlyConn{} |
| 296 | + |
| 297 | +func (conn readOnlyConn) Read(p []byte) (int, error) { return conn.reader.Read(p) } |
| 298 | +func (conn readOnlyConn) Write(p []byte) (int, error) { return 0, io.ErrClosedPipe } |
| 299 | +func (conn readOnlyConn) Close() error { return nil } |
| 300 | +func (conn readOnlyConn) LocalAddr() net.Addr { return nil } |
| 301 | +func (conn readOnlyConn) RemoteAddr() net.Addr { return nil } |
| 302 | +func (conn readOnlyConn) SetDeadline(t time.Time) error { return nil } |
| 303 | +func (conn readOnlyConn) SetReadDeadline(t time.Time) error { return nil } |
| 304 | +func (conn readOnlyConn) SetWriteDeadline(t time.Time) error { return nil } |
0 commit comments