Skip to content
Merged
Show file tree
Hide file tree
Changes from 30 commits
Commits
Show all changes
35 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
879e285
Merge branch 'main' into add-ssl-option-cassandra
MitulShah1 Dec 5, 2025
fd5772d
added cassandra ssl option
MitulShah1 Dec 5, 2025
545a00e
removed InsecureSkipVerify variable
MitulShah1 Dec 5, 2025
19f4879
Merge branch 'main' into add-ssl-option-cassandra
MitulShah1 Dec 8, 2025
50579f9
added mising docs and modify TlsConfig method
MitulShah1 Dec 8, 2025
42f32ec
doc changes
MitulShah1 Dec 12, 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
37 changes: 26 additions & 11 deletions modules/cassandra/cassandra.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,28 +2,38 @@ package cassandra

import (
"context"
"crypto/tls"
"fmt"
"io"
"path/filepath"
"strings"
"time"

"github.com/testcontainers/testcontainers-go"
"github.com/testcontainers/testcontainers-go/wait"
)

const (
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
settings Options
}

// ConnectionHost returns the host and port of the cassandra container, using the default, native 9042 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) {
return c.PortEndpoint(ctx, port, "")
// Use the secure port if TLS is enabled
portToUse := port
if c.settings.tlsConfig != nil {
portToUse = securePort
}

return c.PortEndpoint(ctx, portToUse, "")
}

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

return nil
}
}
Expand All @@ -54,10 +63,8 @@ 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)
}
Expand All @@ -71,9 +78,9 @@ func RunContainer(ctx context.Context, opts ...testcontainers.ContainerCustomize

// Run creates an instance of the Cassandra container type
func Run(ctx context.Context, img string, opts ...testcontainers.ContainerCustomizer) (*CassandraContainer, error) {
moduleOpts := []testcontainers.ContainerCustomizer{
testcontainers.WithExposedPorts(port),
testcontainers.WithEnv(map[string]string{
req := testcontainers.ContainerRequest{
Image: img,
Env: map[string]string{
"CASSANDRA_SNITCH": "GossipingPropertyFileSnitch",
"JVM_OPTS": "-Dcassandra.skip_wait_for_gossip_to_settle=0 -Dcassandra.initial_token=0",
"HEAP_NEWSIZE": "128M",
Expand All @@ -94,8 +101,8 @@ func Run(ctx context.Context, img string, opts ...testcontainers.ContainerCustom

ctr, err := testcontainers.Run(ctx, img, moduleOpts...)
var c *CassandraContainer
if ctr != nil {
c = &CassandraContainer{Container: ctr}
if container != nil {
c = &CassandraContainer{Container: container, settings: settings}
}

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

return c, nil
}

// TLSConfig returns the TLS configuration for the Cassandra container, nil if TLS is not enabled.
func (c *CassandraContainer) TLSConfig() *tls.Config {
Copy link
Contributor

Choose a reason for hiding this comment

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

@mdelapenya quite a common pattern in modules, we should consider returning an error instead.

Copy link
Member

Choose a reason for hiding this comment

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

You mean the pointer to the config and the error, right? I think we changed the tlscert library precisely for that, so good to me to change it

Copy link
Contributor

Choose a reason for hiding this comment

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

Nope, these container methods, have them return an error if the config is nil vs just returning nil as the caller should know if they enabled TLS or not.

func (c *CassandraContainer) TLSConfig() (*tls.Config, error) {
	if c.settings.tlsConfig == nil {
		return nil, errors.New("tls not enabled")
	}
	return c.settings.tlsConfig.Config, nil
}

Copy link
Member

Choose a reason for hiding this comment

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

Oh I see, the recently added methods for Redis and Valkey. For Valkey, we are in the same release cycle, we can change it without BC, for Redis, it's a BC

if c.settings.tlsConfig == nil {
return nil
}
return c.settings.tlsConfig.Config
}
51 changes: 47 additions & 4 deletions modules/cassandra/cassandra_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,10 @@ package cassandra_test

import (
"context"
"fmt"
"path/filepath"
"testing"
"time"

"github.com/gocql/gocql"
"github.com/stretchr/testify/require"
Expand All @@ -12,6 +14,8 @@ import (
"github.com/testcontainers/testcontainers-go/modules/cassandra"
)

const cassandraImage = "cassandra:4.1.3"

type Test struct {
ID uint64
Name string
Expand All @@ -20,7 +24,7 @@ type Test struct {
func TestCassandra(t *testing.T) {
ctx := context.Background()

ctr, err := cassandra.Run(ctx, "cassandra:4.1.3")
ctr, err := cassandra.Run(ctx, cassandraImage)
testcontainers.CleanupContainer(t, ctr)
require.NoError(t, err)

Expand Down Expand Up @@ -52,7 +56,7 @@ func TestCassandra(t *testing.T) {
func TestCassandraWithConfigFile(t *testing.T) {
ctx := context.Background()

ctr, err := cassandra.Run(ctx, "cassandra:4.1.3", cassandra.WithConfigFile(filepath.Join("testdata", "config.yaml")))
ctr, err := cassandra.Run(ctx, cassandraImage, cassandra.WithConfigFile(filepath.Join("testdata", "config.yaml")))
testcontainers.CleanupContainer(t, ctr)
require.NoError(t, err)

Expand All @@ -75,7 +79,7 @@ func TestCassandraWithInitScripts(t *testing.T) {
ctx := context.Background()

// withInitScripts {
ctr, err := cassandra.Run(ctx, "cassandra:4.1.3", cassandra.WithInitScripts(filepath.Join("testdata", "init.cql")))
ctr, err := cassandra.Run(ctx, cassandraImage, cassandra.WithInitScripts(filepath.Join("testdata", "init.cql")))
// }
testcontainers.CleanupContainer(t, ctr)
require.NoError(t, err)
Expand All @@ -99,7 +103,7 @@ func TestCassandraWithInitScripts(t *testing.T) {
t.Run("with init bash script", func(t *testing.T) {
ctx := context.Background()

ctr, err := cassandra.Run(ctx, "cassandra:4.1.3", cassandra.WithInitScripts(filepath.Join("testdata", "init.sh")))
ctr, err := cassandra.Run(ctx, cassandraImage, cassandra.WithInitScripts(filepath.Join("testdata", "init.sh")))
testcontainers.CleanupContainer(t, ctr)
require.NoError(t, err)

Expand All @@ -117,3 +121,42 @@ func TestCassandraWithInitScripts(t *testing.T) {
require.Equal(t, Test{ID: 1, Name: "NAME"}, test)
})
}

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

container, err := cassandra.Run(ctx, cassandraImage,
cassandra.WithConfigFile(filepath.Join("testdata", "cassandra-ssl.yaml")),
cassandra.WithSSL(),
)
testcontainers.CleanupContainer(t, container)
require.NoError(t, err)

// Get TLS configurations
tlsConfig := container.TLSConfig()

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)
}
62 changes: 62 additions & 0 deletions modules/cassandra/examples_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"fmt"
"log"
"path/filepath"
"time"

"github.com/gocql/gocql"

Expand Down Expand Up @@ -67,3 +68,64 @@ func ExampleRun() {
// true
// 4.1.3
}

func ExampleRun_withSSL() {
ctx := context.Background()

cassandraContainer, err := cassandra.Run(ctx,
"cassandra:4.1.3",
cassandra.WithConfigFile(filepath.Join("testdata", "cassandra-ssl.yaml")),
cassandra.WithSSL(),
)
defer func() {
if err := testcontainers.TerminateContainer(cassandraContainer); err != nil {
log.Printf("failed to terminate container: %s", err)
}
}()
if err != nil {
log.Printf("failed to start container: %s", err)
return
}

host, err := cassandraContainer.Host(ctx)
if err != nil {
log.Printf("failed to get host: %s", err)
return
}

sslPort, err := cassandraContainer.MappedPort(ctx, "9142/tcp")
if err != nil {
log.Printf("failed to get SSL port: %s", err)
return
}

// Get TLS config
tlsConfig := cassandraContainer.TLSConfig()

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,
}
session, err := cluster.CreateSession()
if err != nil {
log.Printf("failed to create session: %s", err)
return
}
defer session.Close()

var version string
err = session.Query("SELECT release_version FROM system.local").Scan(&version)
if err != nil {
log.Printf("failed to query: %s", err)
return
}

fmt.Println(version)
// Output:
// 4.1.3
}
127 changes: 127 additions & 0 deletions modules/cassandra/options.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
package cassandra

import (
"crypto/tls"
"crypto/x509"
"errors"
"fmt"
"os"
"os/exec"
"path/filepath"

"github.com/testcontainers/testcontainers-go"
)

// TLSConfig represents the TLS configuration for Cassandra
type TLSConfig struct {
Copy link
Contributor

Choose a reason for hiding this comment

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

question: are the paths needed? If not we can just return *tls.Config. I suspect the answer is dependent on eliminating the need for keytool

KeystorePath string
CertificatePath string
Config *tls.Config
}

// Options represents the configuration options for the Cassandra container
type Options struct {
tlsConfig *TLSConfig
}

// Option is an option for the Cassandra container.
type Option func(*testcontainers.GenericContainerRequest, *Options) error

// Customize implements the testcontainers.ContainerCustomizer interface
func (o Option) Customize(req *testcontainers.GenericContainerRequest) error {
return o(req, &Options{})
Copy link
Contributor

Choose a reason for hiding this comment

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

bug: while this will run there options won't be accessible, so should still be just a noop.

We're looking to refactor how this works in a future version to avoid this, but that will be a bit.

}

// WithSSL enables SSL/TLS support on the Cassandra container
func WithSSL() Option {
return func(req *testcontainers.GenericContainerRequest, settings *Options) error {
req.ExposedPorts = append(req.ExposedPorts, string(securePort))

keystorePath, certPath, err := GenerateJKSKeystore()
if err != nil {
return fmt.Errorf("create SSL certs: %w", err)
}

req.Files = append(req.Files,
testcontainers.ContainerFile{
HostFilePath: keystorePath,
ContainerFilePath: "/etc/cassandra/conf/keystore.jks",
FileMode: 0o644,
},
testcontainers.ContainerFile{
HostFilePath: certPath,
ContainerFilePath: "/etc/cassandra/conf/cassandra.crt",
FileMode: 0o644,
})

certPEM, err := os.ReadFile(certPath)
if err != nil {
return fmt.Errorf("error while read certificate: %w", err)
}

certPool := x509.NewCertPool()
if !certPool.AppendCertsFromPEM(certPEM) {
return errors.New("failed to append certificate to pool")
}

settings.tlsConfig = &TLSConfig{
KeystorePath: keystorePath,
CertificatePath: certPath,
Config: &tls.Config{
RootCAs: certPool,
ServerName: "localhost",
MinVersion: tls.VersionTLS12,
},
}

return nil
}
}

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

// Remove existing keystore if it exists
os.Remove(keystorePath)

// Generate keystore with self-signed certificate
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",
)
if err := cmd.Run(); err != nil {
return "", "", fmt.Errorf("failed to generate keystore: %w", err)
}

// Export the public certificate for Go client trust
cmd = exec.Command(
"keytool", "-exportcert",
"-alias", "cassandra",
"-keystore", keystorePath,
"-storepass", keystorePassword,
"-rfc",
"-file", certPath,
)
if err := cmd.Run(); err != nil {
return "", "", fmt.Errorf("failed to export certificate: %w", err)
}

return keystorePath, certPath, nil
}

// TLSConfig returns the TLS configuration
func (o *Options) TLSConfig() *TLSConfig {
return o.tlsConfig
}
Loading
Loading