Skip to content
Open
Show file tree
Hide file tree
Changes from 14 commits
Commits
Show all changes
29 commits
Select commit Hold shift + click to select a range
ba9ac99
Added SSL Option
MitulShah1 May 1, 2025
a87e16b
Passed tests
MitulShah1 May 2, 2025
d7c7be5
Implemented SSL Support
MitulShah1 May 2, 2025
22c2887
Implemented SSL Support
MitulShah1 May 2, 2025
dfe89e6
Implemented SSL Support
MitulShah1 May 2, 2025
59a1733
Merge branch 'main' into add-ssl-option-cassandra
MitulShah1 May 2, 2025
4e7b372
Merge branch 'main' into add-ssl-option-cassandra
MitulShah1 May 2, 2025
875e63f
Merge remote-tracking branch 'origin/add-ssl-option-cassandra' into a…
MitulShah1 May 2, 2025
8e1b349
Revert go.mod and go.sum
MitulShah1 May 2, 2025
26a38e1
Revert go.mod and go.sum
MitulShah1 May 2, 2025
7d76d50
Golint fix
MitulShah1 May 2, 2025
cc1dd06
Golint fix
MitulShah1 May 2, 2025
71100a9
Govet fix
MitulShah1 May 2, 2025
f07aea2
Merge branch 'main' into add-ssl-option-cassandra
MitulShah1 May 6, 2025
ac19eb4
reduce wait time, revert container place and removed WithTLS options
MitulShah1 May 7, 2025
5b636f7
Added SSL With option
MitulShah1 May 7, 2025
2ad9f7b
Merge branch 'main' into add-ssl-option-cassandra
May 7, 2025
7409635
Added SSL With option
MitulShah1 May 7, 2025
4c2e3dc
Devide Run function n sub function to reduce complexity
MitulShah1 May 7, 2025
6da1e1e
make Options private
MitulShah1 May 7, 2025
9a4f4f2
removed setupTls function and moved to WithSSL Options
MitulShah1 May 7, 2025
5242c32
Fix Sec warning InsecureSkipVerify
MitulShah1 May 7, 2025
18214a0
Fix lint
MitulShah1 May 7, 2025
8ba3319
Merge branch 'main' into add-ssl-option-cassandra
MitulShah1 May 9, 2025
60622d4
Merge branch 'main' into add-ssl-option-cassandra
MitulShah1 May 9, 2025
38320ac
Merge branch 'main' into add-ssl-option-cassandra
MitulShah1 Jun 3, 2025
d1724a5
Merge branch 'main' into add-ssl-option-cassandra
mdelapenya Jul 18, 2025
b05ef84
Merge branch 'testcontainers:main' into add-ssl-option-cassandra
MitulShah1 Aug 5, 2025
86f661b
Merge branch 'main' into add-ssl-option-cassandra
MitulShah1 Oct 14, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
131 changes: 114 additions & 17 deletions modules/cassandra/cassandra.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"io"
"path/filepath"
"strings"
"time"

"github.com/docker/go-connections/nat"

Expand All @@ -14,28 +15,35 @@ import (
)

const (
port = nat.Port("9042/tcp")
port = nat.Port("9042/tcp")
securePort = nat.Port("9142/tcp") // Common port for SSL/TLS connections
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

question: do we need to two ports or can it just be one which is either SSL or not?

)

// CassandraContainer represents the Cassandra container type used in the module
type CassandraContainer struct {
testcontainers.Container
useTLS bool
}

// ConnectionHost returns the host and port of the cassandra container, using the default, native 9000 port, and
// ConnectionHost returns the host and port of the cassandra container, using the default, native port,
// obtaining the host and exposed port from the container
func (c *CassandraContainer) ConnectionHost(ctx context.Context) (string, error) {
host, err := c.Host(ctx)
if err != nil {
return "", err
}

port, err := c.MappedPort(ctx, port)
// Use the secure port if TLS is enabled
portToUse := port
if c.useTLS {
portToUse = securePort
}

mappedPort, err := c.MappedPort(ctx, portToUse)
if err != nil {
return "", err
}

return host + ":" + port.Port(), nil
return host + ":" + mappedPort.Port(), nil
}

// WithConfigFile sets the YAML config file to be used for the cassandra container
Expand All @@ -49,7 +57,6 @@ func WithConfigFile(configFile string) testcontainers.CustomizeRequestOption {
FileMode: 0o755,
}
req.Files = append(req.Files, cf)

return nil
}
}
Expand All @@ -66,15 +73,72 @@ func WithInitScripts(scripts ...string) testcontainers.CustomizeRequestOption {
FileMode: 0o755,
}
initScripts = append(initScripts, cf)

execs = append(execs, initScript{File: cf.ContainerFilePath})
}

req.Files = append(req.Files, initScripts...)
return testcontainers.WithAfterReadyCommand(execs...)(req)
}
}

// SSLOptions contains the configuration options for setting up SSL/TLS
type SSLOptions struct {
KeystorePath string
KeystorePassword string
CertPath string
RequireClientAuth bool
}

// WithSSL enables SSL/TLS support on the Cassandra container
func WithSSL(sslOpts SSLOptions) testcontainers.CustomizeRequestOption {
return func(req *testcontainers.GenericContainerRequest) error {
// Add the secure port to the exposed ports
hasSecurePort := false
for _, p := range req.ExposedPorts {
if p == string(securePort) {
hasSecurePort = true
break
}
}
if !hasSecurePort {
req.ExposedPorts = append(req.ExposedPorts, string(securePort))
}

// Set SSL environment variables
if req.Env == nil {
req.Env = make(map[string]string)
}

// If keystore path is provided, copy it to the container
if sslOpts.KeystorePath != "" {
keystoreFile := testcontainers.ContainerFile{
HostFilePath: sslOpts.KeystorePath,
ContainerFilePath: "/etc/cassandra/conf/keystore.jks",
FileMode: 0o644,
}
req.Files = append(req.Files, keystoreFile)
}

if sslOpts.CertPath != "" {
certFile := testcontainers.ContainerFile{
HostFilePath: sslOpts.CertPath,
ContainerFilePath: "/etc/cassandra/conf/cassandra.crt",
FileMode: 0o644,
}
req.Files = append(req.Files, certFile)
}

// Mark that SSL is enabled for later use
req.Labels = mergeMap(req.Labels, map[string]string{"testcontainers.cassandra.ssl": "true"})
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

question: I guess this is needed to notify the Run function about the SSL addition, right? I'd choose a different pattern for this, creating an options type as in the redis module. Then, you can simply generate the SSL certs on-the-fly as in that module.


return nil
}
}

// WithTLS is an alias for WithSSL for user convenience
func WithTLS(opts SSLOptions) testcontainers.CustomizeRequestOption {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

question: why adding two flavours of the same option? I'd just choose one to avoid creating confusion on users

return WithSSL(opts)
}

// Deprecated: use Run instead
// RunContainer creates an instance of the Cassandra container type
func RunContainer(ctx context.Context, opts ...testcontainers.ContainerCustomizer) (*CassandraContainer, error) {
Expand All @@ -87,37 +151,55 @@ func Run(ctx context.Context, img string, opts ...testcontainers.ContainerCustom
Image: img,
ExposedPorts: []string{string(port)},
Env: map[string]string{
"CASSANDRA_SNITCH": "GossipingPropertyFileSnitch",
"JVM_OPTS": "-Dcassandra.skip_wait_for_gossip_to_settle=0 -Dcassandra.initial_token=0",
"HEAP_NEWSIZE": "128M",
"MAX_HEAP_SIZE": "1024M",
"CASSANDRA_ENDPOINT_SNITCH": "GossipingPropertyFileSnitch",
"CASSANDRA_DC": "datacenter1",
"CASSANDRA_SNITCH": "GossipingPropertyFileSnitch",
"JVM_OPTS": "-Dcassandra.skip_wait_for_gossip_to_settle=0 -Dcassandra.initial_token=0",
"HEAP_NEWSIZE": "128M",
"MAX_HEAP_SIZE": "1024M",
"CASSANDRA_ENDPOINT_SNITCH": "GossipingPropertyFileSnitch",
"CASSANDRA_DC": "datacenter1",
"CASSANDRA_SKIP_WAIT_FOR_GOSSIP": "1",
"CASSANDRA_START_NATIVE_TRANSPORT": "true",
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

question: are these new env vars related to the SSL options? If not, I'd separate the changes into a new PR, if possible

},
WaitingFor: wait.ForAll(
wait.ForListeningPort(port),
wait.ForExec([]string{"cqlsh", "-e", "SELECT bootstrapped FROM system.local"}).WithResponseMatcher(func(body io.Reader) bool {
data, _ := io.ReadAll(body)
return strings.Contains(string(data), "COMPLETED")
}),
}).WithStartupTimeout(2*time.Minute),
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

question: is 2 minutes too long? Can we use a shorter duration?

),
}

c := &CassandraContainer{}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion: keep this initialisation next to its usage. Seems moved here for no reasons


genericContainerReq := testcontainers.GenericContainerRequest{
ContainerRequest: req,
Started: true,
}

sslEnabled := false
for _, opt := range opts {
if err := opt.Customize(&genericContainerReq); err != nil {
return nil, err
}
// Detect if WithSSL/WithTLS was used by checking the label
if genericContainerReq.Labels != nil && genericContainerReq.Labels["testcontainers.cassandra.ssl"] == "true" {
sslEnabled = true
}
}

// If SSL is enabled, add a TLS wait strategy for the keystore file and SSL CQL port
if sslEnabled {
genericContainerReq.WaitingFor = wait.ForAll(
genericContainerReq.WaitingFor,
wait.ForListeningPort(securePort).WithStartupTimeout(3*time.Minute),
)
}

container, err := testcontainers.GenericContainer(ctx, genericContainerReq)
var c *CassandraContainer
if container != nil {
c = &CassandraContainer{Container: container}
c.Container = container
// Set useTLS based on sslEnabled
c.useTLS = sslEnabled
}

if err != nil {
Expand All @@ -126,3 +208,18 @@ func Run(ctx context.Context, img string, opts ...testcontainers.ContainerCustom

return c, nil
}

// mergeMap is a helper to merge two string maps
func mergeMap(a, b map[string]string) map[string]string {
if a == nil && b == nil {
return nil
}
result := make(map[string]string)
for k, v := range a {
result[k] = v
}
for k, v := range b {
result[k] = v
}
return result
}
105 changes: 105 additions & 0 deletions modules/cassandra/cassandra_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,14 @@ package cassandra_test

import (
"context"
"crypto/tls"
"crypto/x509"
"fmt"
"os"
"os/exec"
"path/filepath"
"testing"
"time"

"github.com/gocql/gocql"
"github.com/stretchr/testify/require"
Expand Down Expand Up @@ -117,3 +123,102 @@ func TestCassandraWithInitScripts(t *testing.T) {
require.Equal(t, Test{ID: 1, Name: "NAME"}, test)
})
}

// generateJKSKeystore generates a JKS keystore with a self-signed cert using keytool, and extracts the public cert for Go client trust.
func generateJKSKeystore(t *testing.T) (keystorePath, keystorePassword, certPath string) {
t.Helper()
tmpDir := t.TempDir()
keystorePath = filepath.Join(tmpDir, "keystore.jks")
keystorePassword = "changeit"
certPath = filepath.Join(tmpDir, "cert.pem")

cmd := exec.Command(
"keytool", "-genkeypair",
"-alias", "cassandra",
"-keyalg", "RSA",
"-keysize", "2048",
"-storetype", "JKS",
"-keystore", keystorePath,
"-storepass", keystorePassword,
"-keypass", keystorePassword,
"-dname", "CN=localhost, OU=Test, O=Test, C=US",
"-validity", "365",
)
out, err := cmd.CombinedOutput()
require.NoError(t, err, string(out))

// Export the public certificate for Go client trust
cmd = exec.Command(
"keytool", "-exportcert",
"-alias", "cassandra",
"-keystore", keystorePath,
"-storepass", keystorePassword,
"-rfc",
"-file", certPath,
)
out, err = cmd.CombinedOutput()
require.NoError(t, err, string(out))

return keystorePath, keystorePassword, certPath
}

func TestCassandraSSL(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Minute)
defer cancel()

keystorePath, keystorePassword, certPath := generateJKSKeystore(t)

// Read the certificate for client validation
certPEM, err := os.ReadFile(certPath)
if err != nil {
t.Fatalf("Failed to read certificate: %v", err)
}

// Create a certificate pool and add the certificate
certPool := x509.NewCertPool()
certPool.AppendCertsFromPEM(certPEM)

// Set up TLS configuration
tlsConfig := &tls.Config{
RootCAs: certPool,
InsecureSkipVerify: true, // For testing only
ServerName: "localhost",
MinVersion: tls.VersionTLS12,
}

container, err := cassandra.Run(ctx, "cassandra:4.1.3",
cassandra.WithConfigFile(filepath.Join("testdata", "cassandra-ssl.yaml")),
cassandra.WithSSL(cassandra.SSLOptions{
KeystorePath: keystorePath,
KeystorePassword: keystorePassword,
CertPath: certPath, // for reference, not used by server
RequireClientAuth: false,
}),
)
testcontainers.CleanupContainer(t, container)
require.NoError(t, err)

host, err := container.Host(ctx)
require.NoError(t, err)

sslPort, err := container.MappedPort(ctx, "9142/tcp")
require.NoError(t, err)

cluster := gocql.NewCluster(fmt.Sprintf("%s:%s", host, sslPort.Port()))
cluster.Consistency = gocql.Quorum
cluster.Timeout = 30 * time.Second
cluster.ConnectTimeout = 30 * time.Second
cluster.DisableInitialHostLookup = true
cluster.SslOpts = &gocql.SslOptions{
Config: tlsConfig,
EnableHostVerification: false,
}
var session *gocql.Session
session, err = cluster.CreateSession()
require.NoError(t, err)
defer session.Close()
var version string
err = session.Query("SELECT release_version FROM system.local").Scan(&version)
require.NoError(t, err)
require.NotEmpty(t, version)
}
Loading
Loading