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
9 changes: 9 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,15 @@

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

### Added
- `GET /admin/version` returns the running version (`{"version": "0.7.3"}`), e.g. for Zync to check compatibility. It requires an admin token: requests without a valid token get 401 and player tokens 403, so the version is never disclosed to players or unauthenticated clients

### Changed
- The API port no longer serves `/metrics`, which was exempt from authentication and exposed challenge names and team IDs to anyone who could reach the API. Metrics stay on the metrics server (port 5001, basic auth when `metrics.password` is set), which the provided Prometheus configuration already scrapes

### 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
28 changes: 28 additions & 0 deletions galvanize-instancer/api/openapi.yaml.in
Original file line number Diff line number Diff line change
Expand Up @@ -244,6 +244,25 @@ paths:
'500':
description: Internal server error

/admin/version:
get:
summary: Galvanize version
description: Returns the version of the running Galvanize, e.g. for Zync to check that it is compatible. Admins only, so that neither players nor unauthenticated clients learn which version, and so which known issues, a deployment has.
operationId: getVersion
security:
- bearerAuth: [ ]
responses:
'200':
description: Galvanize version
content:
application/json:
schema:
$ref: '#/components/schemas/VersionResponse'
'401':
description: Unauthorized
'403':
description: Forbidden - Admin access required

/admin/config-check:
post:
summary: Check communication with Zync
Expand Down Expand Up @@ -554,6 +573,15 @@ components:
- created_at
- updated_at

VersionResponse:
type: object
properties:
version:
type: string
description: Version of the running Galvanize (e.g. 0.7.3).
required:
- version

ReloadChallengesResponse:
type: object
properties:
Expand Down
47 changes: 47 additions & 0 deletions galvanize-instancer/cmd/metrics_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
package cmd

import (
"net/http"
"net/http/httptest"
"testing"
"time"

"github.com/golang-jwt/jwt/v5"
"github.com/stretchr/testify/assert"
)

// The API port no longer serves /metrics, which skipped authentication:
// metrics are only on the metrics server (:5001)
func TestAPIPort_NoMetrics(t *testing.T) {
e := newAPI("9.8.7")
assert.Equal(t, http.StatusUnauthorized, get(e, "/metrics", "").Code, "requires a token like any route")

admin := signed(t, jwt.SigningMethodHS256, []byte(testSecret), "admin", time.Now().Add(time.Hour))
assert.Equal(t, http.StatusNotFound, get(e, "/metrics", admin).Code, "and is not served")
}

func scrape(h http.Handler, user, pass string) int {
req := httptest.NewRequest(http.MethodGet, "/metrics", nil)
if user != "" || pass != "" {
req.SetBasicAuth(user, pass)
}
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
return rec.Code
}

// The metrics server's authentication is unchanged: none without a
// password, basic auth with one (username defaults to prometheus)
func TestMetricsHandler(t *testing.T) {
metrics := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { _, _ = w.Write([]byte("ok")) })

assert.Equal(t, http.StatusOK, scrape(metricsHandler("", "", metrics), "", ""), "open without a password")

h := metricsHandler("", "s3cret", metrics)
assert.Equal(t, http.StatusUnauthorized, scrape(h, "", ""))
assert.Equal(t, http.StatusUnauthorized, scrape(h, "prometheus", "wrong"))
assert.Equal(t, http.StatusUnauthorized, scrape(h, "admin", "s3cret"))
assert.Equal(t, http.StatusOK, scrape(h, "prometheus", "s3cret"))

assert.Equal(t, http.StatusOK, scrape(metricsHandler("scraper", "s3cret", metrics), "scraper", "s3cret"))
}
30 changes: 18 additions & 12 deletions galvanize-instancer/cmd/serve.go
Original file line number Diff line number Diff line change
Expand Up @@ -56,9 +56,9 @@ var serveCmd = &cobra.Command{
// 2. Middleware
useMiddleware(e)

// 3. Prometheus
// 3. Prometheus: request metrics are gathered here and served by the
// metrics server on :5001 only, never on the API port
e.Use(echoprometheus.NewMiddleware("instancer")) // register middleware to gather metrics from requests
e.GET("/metrics", echoprometheus.NewHandler())

// JWT secret from env (for security);
jwtSecret := os.Getenv("JWT_SECRET")
Expand All @@ -83,16 +83,7 @@ var serveCmd = &cobra.Command{
cfg.Instancer.AnsibleDir = ansiblePath

// 4. Auth
jwtConfig := echojwt.Config{
NewClaimsFunc: func(c echo.Context) jwt.Claims {
return new(auth.Claims)
},
SigningKey: []byte(jwtSecret),
Skipper: func(c echo.Context) bool {
return c.Path() == "/health" || c.Path() == "/metrics"
},
}
e.Use(echojwt.WithConfig(jwtConfig))
e.Use(jwtMiddleware(jwtSecret))

if err := utils.RegisterSSHHosts(cfg); err != nil {
zap.S().Fatalf("Failed to register SSH hosts: %v", err)
Expand Down Expand Up @@ -191,6 +182,7 @@ var serveCmd = &cobra.Command{
TeamDeployer: teamDeployer,
ExpiryScheduler: expirySched,
JobQueue: jobQueue,
Version: rootCmd.Version,
})
api.RegisterHandlers(e, srv)

Expand Down Expand Up @@ -280,6 +272,20 @@ func configureQueueless(cfg *config.Config, jobQueue *worker.Queue, expirySched
return teamDeployer
}

// jwtMiddleware requires a valid HS256 token signed with secret on every
// route but /health; handlers then check the claims' role.
func jwtMiddleware(secret string) echo.MiddlewareFunc {
return echojwt.WithConfig(echojwt.Config{
NewClaimsFunc: func(c echo.Context) jwt.Claims {
return new(auth.Claims)
},
SigningKey: []byte(secret),
Skipper: func(c echo.Context) bool {
return c.Path() == "/health"
},
})
}

// useMiddleware installs the request logger, panic recovery and CORS.
//
// Recover turns a panic in a handler into a 500 response, logged with its
Expand Down
82 changes: 82 additions & 0 deletions galvanize-instancer/cmd/version_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
package cmd

import (
"net/http"
"net/http/httptest"
"testing"
"time"

"github.com/28Pollux28/galvanize/internal/auth"
server "github.com/28Pollux28/galvanize/pkg"
"github.com/28Pollux28/galvanize/pkg/api"
"github.com/golang-jwt/jwt/v5"
"github.com/labstack/echo/v4"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)

const testSecret = "test-jwt-secret"

// newAPI serves Galvanize's API behind the same JWT middleware as serve
func newAPI(version string) *echo.Echo {
e := echo.New()
e.Use(jwtMiddleware(testSecret))
api.RegisterHandlers(e, server.NewServerWithOpts(server.ServerOpts{Version: version}))
return e
}

func signed(t *testing.T, method jwt.SigningMethod, key interface{}, role string, expires time.Time) string {
t.Helper()
claims := &auth.Claims{Role: role, TeamID: "team1", RegisteredClaims: jwt.RegisteredClaims{ExpiresAt: jwt.NewNumericDate(expires)}}
token, err := jwt.NewWithClaims(method, claims).SignedString(key)
require.NoError(t, err)
return token
}

func get(e *echo.Echo, path, token string) *httptest.ResponseRecorder {
req := httptest.NewRequest(http.MethodGet, path, nil)
if token != "" {
req.Header.Set("Authorization", "Bearer "+token)
}
rec := httptest.NewRecorder()
e.ServeHTTP(rec, req)
return rec
}

func TestVersion_OnlyForAdmins(t *testing.T) {
e := newAPI("9.8.7")
hour := time.Now().Add(time.Hour)

rec := get(e, "/admin/version", signed(t, jwt.SigningMethodHS256, []byte(testSecret), "admin", hour))
assert.Equal(t, http.StatusOK, rec.Code)
assert.JSONEq(t, `{"version":"9.8.7"}`, rec.Body.String())

for name, tc := range map[string]struct {
token string
code int
}{
"no token": {"", http.StatusUnauthorized},
"wrong key": {signed(t, jwt.SigningMethodHS256, []byte("another-secret"), "admin", hour), http.StatusUnauthorized},
"unsigned (none)": {signed(t, jwt.SigningMethodNone, jwt.UnsafeAllowNoneSignatureType, "admin", hour), http.StatusUnauthorized},
"expired admin": {signed(t, jwt.SigningMethodHS256, []byte(testSecret), "admin", time.Now().Add(-time.Minute)), http.StatusUnauthorized},
"player": {signed(t, jwt.SigningMethodHS256, []byte(testSecret), "player", hour), http.StatusForbidden},
"no role": {signed(t, jwt.SigningMethodHS256, []byte(testSecret), "", hour), http.StatusForbidden},
} {
t.Run(name, func(t *testing.T) {
rec := get(e, "/admin/version", tc.token)
assert.Equal(t, tc.code, rec.Code)
assert.NotContains(t, rec.Body.String(), "9.8.7", "the version is not disclosed")
})
}
}

func TestVersion_NotInHealth(t *testing.T) {
rec := get(newAPI("9.8.7"), "/health", "")
assert.Equal(t, http.StatusOK, rec.Code)
assert.NotContains(t, rec.Body.String(), "9.8.7")
}

func TestVersion_UnknownWhenUnset(t *testing.T) {
rec := get(newAPI(""), "/admin/version", signed(t, jwt.SigningMethodHS256, []byte(testSecret), "admin", time.Now().Add(time.Hour)))
assert.JSONEq(t, `{"version":"unknown"}`, rec.Body.String())
}
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
}
Loading
Loading