Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
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
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@

## vX.X.X (YYYY-MM-DD)

### Fixed
- Connection info lists every endpoint of an instance, one per line, ordered by compose service: each Traefik-routed host as `https://<host>/`, then each published port as `<scheme>://<host>:<port>` (its protocol hint, or `tcp`/`udp`). Only the first container with a route or a published port was reported, so a challenge with, for example, a web front end and an SSH service showed only one of them, depending on the order Ansible listed the containers. Only routers' `.rule` labels are read, so other Traefik labels set by challenge authors (entrypoints, tls, middlewares) no longer make the route random, and containers with `traefik.enable=false` are skipped

## v0.7.3 (2026-10-01)

### Fixed
Expand Down
4 changes: 4 additions & 0 deletions data/challenges/example/custom_compose/challenge.yml
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,10 @@ deploy_parameters:
#
# You no longer need to hand-write Traefik labels, attach the external
# network, or pick host ports yourself.
#
# Several services can be exposed: players get every endpoint, one per line
# (https://<subdomain>/ for http, <scheme or tcp>://<host>:<port> for tcp),
# ordered by service name.
expose:
- service: web
port: 80
Expand Down
101 changes: 70 additions & 31 deletions galvanize-instancer/internal/ansible/connection_info.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,46 +2,85 @@ package ansible

import (
"fmt"
"regexp"
"sort"
"strings"
)

// hostRule matches each Host(`name`) of a Traefik router rule
var hostRule = regexp.MustCompile("Host\\(`([^`]+)`\\)")

// GetConnectionInfo returns how players reach a deployed instance: every
// endpoint of every container, one per line. A container routed by Traefik
// gives https://<host>/ for each Host() of its routers' rules; each port it
// publishes gives <scheme>://<host>:<port>, the scheme being the port's
// protocol hint, or else the port's protocol (tcp, udp). Containers are taken
// in compose service order, so the result does not depend on the order
// Ansible reports them in.
func GetConnectionInfo(containerInfos []ContainerInfo, host string, protocolHints map[int]string) (string, error) {
traefikLabel := ""
for _, ci := range containerInfos {
for labelKey, labelValue := range ci.Labels {
if strings.HasPrefix(labelKey, "traefik.http.routers.") {
traefikLabel = labelValue
break
}
containers := append([]ContainerInfo(nil), containerInfos...)
sort.SliceStable(containers, func(i, j int) bool {
return containerSortKey(containers[i]) < containerSortKey(containers[j])
})

var endpoints []string
seen := map[string]bool{}
add := func(endpoint string) {
if !seen[endpoint] {
seen[endpoint] = true
endpoints = append(endpoints, endpoint)
}
// Check if we have a traefik label
if traefikLabel != "" {
labelParts := strings.Split(traefikLabel, "`")
if len(labelParts) >= 2 {
domainName := "https://" + labelParts[1] + "/"
return domainName, nil
}
}

for _, ci := range containers {
for _, domain := range traefikDomains(ci.Labels) {
add("https://" + domain + "/")
}
// Check if we have published ports
var ports []string
for _, pub := range ci.Publishers {
if pub.PublishedPort != 0 {
// If IP is IPv6, continue
if strings.Contains(pub.URL, ":") {
continue
}
scheme := pub.Protocol
if protocolHints != nil {
if hintedScheme, ok := protocolHints[pub.TargetPort]; ok {
scheme = hintedScheme
}
}
ports = append(ports, fmt.Sprintf("%s://%s:%d", scheme, host, pub.PublishedPort))
// Docker lists each port for IPv4 and IPv6: keep the IPv4 one
if pub.PublishedPort == 0 || strings.Contains(pub.URL, ":") {
continue
}
scheme := pub.Protocol
if hinted, ok := protocolHints[pub.TargetPort]; ok {
scheme = hinted
}
add(fmt.Sprintf("%s://%s:%d", scheme, host, pub.PublishedPort))
}
}

if len(endpoints) == 0 {
return "", fmt.Errorf("no connection info found")
}
return strings.Join(endpoints, "\n"), nil
}

// traefikDomains returns the hosts of the container's Traefik HTTP router
// rules, sorted by router. Other router labels (entrypoints, tls,
// middlewares...) are not rules and are ignored, as are containers Traefik is
// told to leave alone.
func traefikDomains(labels map[string]string) []string {
if strings.EqualFold(labels["traefik.enable"], "false") {
return nil
}
var ruleKeys []string
for key := range labels {
if strings.HasPrefix(key, "traefik.http.routers.") && strings.HasSuffix(key, ".rule") {
ruleKeys = append(ruleKeys, key)
}
if len(ports) > 0 {
return strings.Join(ports, "\n"), nil
}
sort.Strings(ruleKeys)

var domains []string
for _, key := range ruleKeys {
for _, m := range hostRule.FindAllStringSubmatch(labels[key], -1) {
domains = append(domains, m[1])
}
}
return "", fmt.Errorf("no connection info found")
return domains
}

// containerSortKey orders containers by compose service, then by name
func containerSortKey(ci ContainerInfo) string {
return ci.Labels["com.docker.compose.service"] + "\x00" + ci.Name
}
94 changes: 94 additions & 0 deletions galvanize-instancer/internal/ansible/connection_info_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -119,3 +119,97 @@ func isRandomBindingFor(portDef string, target string) bool {
}
return defaultPortRange.contains(hostPort)
}

func webContainer(service, project, domain string) ContainerInfo {
return ContainerInfo{
Name: project + "-" + service + "-1",
Labels: map[string]string{
"com.docker.compose.service": service,
"traefik.enable": "true",
"traefik.http.routers." + project + ".rule": "Host(`" + domain + "`)",
"traefik.http.services." + project + ".loadbalancer.server.port": "80",
},
}
}

func sshContainer(project string, port int) ContainerInfo {
return ContainerInfo{
Name: project + "-ssh-1",
Labels: map[string]string{"com.docker.compose.service": "ssh"},
Publishers: []PublisherInfo{
{Protocol: "tcp", PublishedPort: port, TargetPort: 22, URL: "0.0.0.0"},
{Protocol: "tcp", PublishedPort: port, TargetPort: 22, URL: "::"},
},
}
}

func TestGetConnectionInfo_SingleWebChallengeUnchanged(t *testing.T) {
conn, err := GetConnectionInfo([]ContainerInfo{webContainer("web", "p", "p.challs.example.com")}, "challs.example.com", nil)
require.NoError(t, err)
assert.Equal(t, "https://p.challs.example.com/", conn)
}

// A web front end and an SSH service: both endpoints, whatever order Ansible
// reports the containers in. Only the first container's endpoint was returned.
func TestGetConnectionInfo_WebAndSSHServices(t *testing.T) {
web := webContainer("web", "p", "p.challs.example.com")
ssh := sshContainer("p", 40022)
want := "tcp://challs.example.com:40022\nhttps://p.challs.example.com/"
hints := map[int]string{}

for _, order := range [][]ContainerInfo{{web, ssh}, {ssh, web}} {
conn, err := GetConnectionInfo(order, "challs.example.com", hints)
require.NoError(t, err)
assert.Equal(t, want, conn, "ssh sorts before web")
}

hints[22] = "ssh"
conn, err := GetConnectionInfo([]ContainerInfo{web, ssh}, "challs.example.com", hints)
require.NoError(t, err)
assert.Equal(t, "ssh://challs.example.com:40022\nhttps://p.challs.example.com/", conn)
}

func TestGetConnectionInfo_SeveralWebServices(t *testing.T) {
conn, err := GetConnectionInfo([]ContainerInfo{
webContainer("web", "web-p", "web-p.challs.example.com"),
webContainer("api", "api-p", "api-p.challs.example.com"),
}, "challs.example.com", nil)
require.NoError(t, err)
assert.Equal(t, "https://api-p.challs.example.com/\nhttps://web-p.challs.example.com/", conn)
}

// Router labels other than rules (an author's own entrypoints, tls,
// middlewares) were picked at random among the router labels
func TestGetConnectionInfo_OnlyRouterRules(t *testing.T) {
web := webContainer("web", "p", "p.challs.example.com")
web.Labels["traefik.http.routers.p.entrypoints"] = "websecure"
web.Labels["traefik.http.routers.p.tls"] = "true"
web.Labels["traefik.http.routers.p.middlewares"] = "auth"

for range 20 {
conn, err := GetConnectionInfo([]ContainerInfo{web}, "challs.example.com", nil)
require.NoError(t, err)
require.Equal(t, "https://p.challs.example.com/", conn)
}
}

func TestGetConnectionInfo_RuleWithSeveralHosts(t *testing.T) {
web := webContainer("web", "p", "")
web.Labels["traefik.http.routers.p.rule"] = "Host(`a.challs.example.com`) || (Host(`b.challs.example.com`) && PathPrefix(`/x`))"
conn, err := GetConnectionInfo([]ContainerInfo{web}, "challs.example.com", nil)
require.NoError(t, err)
assert.Equal(t, "https://a.challs.example.com/\nhttps://b.challs.example.com/", conn)
}

func TestGetConnectionInfo_TraefikDisabledIgnored(t *testing.T) {
web := webContainer("web", "p", "p.challs.example.com")
web.Labels["traefik.enable"] = "false"
conn, err := GetConnectionInfo([]ContainerInfo{web, sshContainer("p", 40022)}, "challs.example.com", map[int]string{22: "ssh"})
require.NoError(t, err)
assert.Equal(t, "ssh://challs.example.com:40022", conn)
}

func TestGetConnectionInfo_NoEndpoint(t *testing.T) {
_, err := GetConnectionInfo([]ContainerInfo{{Name: "db", Labels: map[string]string{"com.docker.compose.service": "db"}}}, "challs.example.com", nil)
assert.Error(t, err)
}
Loading