Skip to content

Commit

Permalink
fix: docker containers listening on ipv6 (#616)
Browse files Browse the repository at this point in the history
  • Loading branch information
atzoum authored Aug 30, 2024
1 parent 9cca578 commit 76a6758
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 7 deletions.
27 changes: 20 additions & 7 deletions testhelper/docker/resource/internal/ports.go
Original file line number Diff line number Diff line change
@@ -1,22 +1,35 @@
package internal

import (
"runtime"

"github.com/ory/dockertest/v3/docker"
)

const BindHostIP = "0.0.0.0"
const (
BindHostIP = "127.0.0.1"
BindInternalHost = "host.docker.internal"
)

// IPv4PortBindings returns the port bindings for the given exposed ports forcing ipv4 address.
func IPv4PortBindings(exposedPorts []string) map[docker.Port][]docker.PortBinding {
portBindings := make(map[docker.Port][]docker.PortBinding)

bindings := []docker.PortBinding{
{
HostIP: BindHostIP,
HostPort: "0",
},
}
if runtime.GOOS == "linux" {
bindings = append(bindings, docker.PortBinding{
HostIP: BindInternalHost,
HostPort: "0",
})
}

for _, exposedPort := range exposedPorts {
portBindings[docker.Port(exposedPort)+"/tcp"] = []docker.PortBinding{
{
HostIP: BindHostIP,
HostPort: "0",
},
}
portBindings[docker.Port(exposedPort)+"/tcp"] = bindings
}

return portBindings
Expand Down
36 changes: 36 additions & 0 deletions testhelper/docker/resource/postgres/postgres_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,42 @@ func TestPostgres(t *testing.T) {
require.Contains(t, cl.logs, "postgres container state: {Status:exited")
require.Contains(t, cl.logs, "postgres container logs:")
})

t.Run("only ipv4 bindings", func(t *testing.T) {
postgresContainer, err := postgres.Setup(pool, t)
require.NoError(t, err)
defer func() { _ = postgresContainer.DB.Close() }()

{
ipv4DSN := fmt.Sprintf(
"postgres://%s:%s@%s:%s/%s?sslmode=disable",
postgresContainer.User,
postgresContainer.Password,
"127.0.0.1",
postgresContainer.Port,
postgresContainer.Database,
)
db, err := sql.Open("postgres", ipv4DSN)
require.NoError(t, err, "it should be able to open the sql db with an ipv4 address")
require.NoError(t, db.Ping(), "it should be able to ping the db with an ipv4 address")
require.NoError(t, db.Close(), "it should be able to close the sql db")
}

{
ipv6DSN := fmt.Sprintf(
"postgres://%s:%s@%s:%s/%s?sslmode=disable",
postgresContainer.User,
postgresContainer.Password,
"::1",
postgresContainer.Port,
postgresContainer.Database,
)
db, err := sql.Open("postgres", ipv6DSN)
require.NoError(t, err, "it should be able to open the sql db even with an ipv6 address")
require.Error(t, db.Ping(), "it should not be able to ping the db with an ipv6 address")
require.NoError(t, db.Close(), "it should be able to close the sql db")
}
})
}

type testCleaner struct {
Expand Down

0 comments on commit 76a6758

Please sign in to comment.