From a8cf10adcc17c41605a72981854ffc7010a152e8 Mon Sep 17 00:00:00 2001 From: CorentinFelten Date: Thu, 1 Oct 2026 21:53:25 -0400 Subject: [PATCH 1/3] fix: report every endpoint of an instance in its connection info GetConnectionInfo returned at the first container that had a Traefik router label or a published port, so an instance with several user-facing services (e.g. a web front end and an SSH service, both exposed with expose:) reported only one of them, whichever Ansible listed first. To find a route, it also took the first traefik.http.routers.* label of a map, in random order: with author-written router labels besides the rule (entrypoints, tls, middlewares), the route was found or missed at random. It now goes through every container, ordered by compose service then name, and lists each Host() of each router rule as https:///, then each published IPv4 port as ://: (the port's protocol hint, or its protocol), one per line without duplicates. Only .rule labels are read, and containers with traefik.enable=false are skipped. An instance with a single endpoint reports it as before. --- CHANGELOG.md | 3 + .../example/custom_compose/challenge.yml | 4 + .../internal/ansible/connection_info.go | 101 ++++++++++++------ .../internal/ansible/connection_info_test.go | 94 ++++++++++++++++ 4 files changed, 171 insertions(+), 31 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 066120f..a7cc652 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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:///`, then each published port as `://:` (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 diff --git a/data/challenges/example/custom_compose/challenge.yml b/data/challenges/example/custom_compose/challenge.yml index a60a311..0af2866 100644 --- a/data/challenges/example/custom_compose/challenge.yml +++ b/data/challenges/example/custom_compose/challenge.yml @@ -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:/// for http, ://: for tcp), + # ordered by service name. expose: - service: web port: 80 diff --git a/galvanize-instancer/internal/ansible/connection_info.go b/galvanize-instancer/internal/ansible/connection_info.go index 1891138..d0fdc1f 100644 --- a/galvanize-instancer/internal/ansible/connection_info.go +++ b/galvanize-instancer/internal/ansible/connection_info.go @@ -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:/// for each Host() of its routers' rules; each port it +// publishes gives ://:, 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 } diff --git a/galvanize-instancer/internal/ansible/connection_info_test.go b/galvanize-instancer/internal/ansible/connection_info_test.go index 793fef2..cc20c37 100644 --- a/galvanize-instancer/internal/ansible/connection_info_test.go +++ b/galvanize-instancer/internal/ansible/connection_info_test.go @@ -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) +} From 41eb3a51f2f6d3b61c64be16691e02c7b58c6eec Mon Sep 17 00:00:00 2001 From: CorentinFelten Date: Fri, 2 Oct 2026 00:28:24 -0400 Subject: [PATCH 2/3] feat: report the version to admins on /admin/version Zync needs Galvanize's version to check that the two are compatible. The project is open source, so a version also tells anyone which known issues a deployment has: it is reported to admins only. GET /admin/version returns {"version": "..."}, the version set at startup (ServerOpts.Version, from the binary's Version). Like every route but /health and /metrics, it requires a valid HS256 token signed with the JWT secret, and the handler refuses any role but admin, so requests without a valid token get 401 and player tokens 403, without the version. /health is unchanged. The JWT middleware setup moves to jwtMiddleware, so tests send real requests through it: no token, a wrong key, an unsigned (alg none) token, an expired admin token, player and role-less tokens. --- CHANGELOG.md | 3 + galvanize-instancer/api/openapi.yaml.in | 28 ++++++ galvanize-instancer/cmd/serve.go | 26 +++-- galvanize-instancer/cmd/version_test.go | 82 ++++++++++++++++ galvanize-instancer/pkg/api/api.gen.go | 100 ++++++++++++-------- galvanize-instancer/pkg/restserver.go | 4 + galvanize-instancer/pkg/restserver_admin.go | 19 ++++ 7 files changed, 214 insertions(+), 48 deletions(-) create mode 100644 galvanize-instancer/cmd/version_test.go diff --git a/CHANGELOG.md b/CHANGELOG.md index a7cc652..1f9c7f3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,9 @@ ## 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 + ### Fixed - Connection info lists every endpoint of an instance, one per line, ordered by compose service: each Traefik-routed host as `https:///`, then each published port as `://:` (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 diff --git a/galvanize-instancer/api/openapi.yaml.in b/galvanize-instancer/api/openapi.yaml.in index 2edaf5b..9fb5134 100755 --- a/galvanize-instancer/api/openapi.yaml.in +++ b/galvanize-instancer/api/openapi.yaml.in @@ -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 @@ -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: diff --git a/galvanize-instancer/cmd/serve.go b/galvanize-instancer/cmd/serve.go index 16b0a71..c052589 100755 --- a/galvanize-instancer/cmd/serve.go +++ b/galvanize-instancer/cmd/serve.go @@ -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) @@ -191,6 +182,7 @@ var serveCmd = &cobra.Command{ TeamDeployer: teamDeployer, ExpiryScheduler: expirySched, JobQueue: jobQueue, + Version: rootCmd.Version, }) api.RegisterHandlers(e, srv) @@ -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 and /metrics; 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" || c.Path() == "/metrics" + }, + }) +} + // useMiddleware installs the request logger, panic recovery and CORS. // // Recover turns a panic in a handler into a 500 response, logged with its diff --git a/galvanize-instancer/cmd/version_test.go b/galvanize-instancer/cmd/version_test.go new file mode 100644 index 0000000..462d1d7 --- /dev/null +++ b/galvanize-instancer/cmd/version_test.go @@ -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()) +} diff --git a/galvanize-instancer/pkg/api/api.gen.go b/galvanize-instancer/pkg/api/api.gen.go index 9831889..10866ae 100755 --- a/galvanize-instancer/pkg/api/api.gen.go +++ b/galvanize-instancer/pkg/api/api.gen.go @@ -189,6 +189,12 @@ type TeamDeploymentsResponse struct { TeamId string `json:"team_id"` } +// VersionResponse defines model for VersionResponse. +type VersionResponse struct { + // Version Version of the running Galvanize (e.g. 0.7.3). + Version string `json:"version"` +} + // DeployAdminInstanceJSONRequestBody defines body for DeployAdminInstance for application/json ContentType. type DeployAdminInstanceJSONRequestBody = AdminDeployRequest @@ -236,6 +242,9 @@ type ServerInterface interface { // Terminate all unique challenges (admin only) // (POST /admin/terminate-all) TerminateAllAdminInstances(ctx echo.Context) error + // Galvanize version + // (GET /admin/version) + GetVersion(ctx echo.Context) error // Deploy a challenge instance // (POST /deploy) DeployInstance(ctx echo.Context) error @@ -368,6 +377,17 @@ func (w *ServerInterfaceWrapper) TerminateAllAdminInstances(ctx echo.Context) er return err } +// GetVersion converts echo context to params. +func (w *ServerInterfaceWrapper) GetVersion(ctx echo.Context) error { + var err error + + ctx.Set(BearerAuthScopes, []string{}) + + // Invoke the callback with all the unmarshaled arguments + err = w.Handler.GetVersion(ctx) + return err +} + // DeployInstance converts echo context to params. func (w *ServerInterfaceWrapper) DeployInstance(ctx echo.Context) error { var err error @@ -459,6 +479,7 @@ func RegisterHandlersWithBaseURL(router EchoRouter, si ServerInterface, baseURL router.GET(baseURL+"/admin/team-deployments", wrapper.ListTeamDeployments) router.POST(baseURL+"/admin/terminate", wrapper.TerminateAdminInstance) router.POST(baseURL+"/admin/terminate-all", wrapper.TerminateAllAdminInstances) + router.GET(baseURL+"/admin/version", wrapper.GetVersion) router.POST(baseURL+"/deploy", wrapper.DeployInstance) router.POST(baseURL+"/extend", wrapper.ExtendInstance) router.GET(baseURL+"/health", wrapper.GetHealth) @@ -470,44 +491,47 @@ func RegisterHandlersWithBaseURL(router EchoRouter, si ServerInterface, baseURL // Base64 encoded, gzipped, json marshaled Swagger object var swaggerSpec = []string{ - "H4sIAAAAAAAC/+xabW/cNvL/KgP9/0ASQF47TYrD+V6lcZLbw6FXJA4CXBIsuOJoxVoiFZJysg32ux84", - "1LOo9Tq13bjou5U0JIczv3ngj/s1SlRRKonSmuj0a2SSDAtGP5/xQsgzLHO1fY2fKjTWvS21KlFbgSST", - "MIsbpbfuN0eTaFFaoWR0Gp1nCM1XUClY95yxPEe5QbAKOM28iOLIbkuMTiNjtZCbaBdHrdxKsgLDc7sv", - "15t3F0caP1VCI49O33eqT9b72A5V618xsU6ln6r84j8lauZUeI2mVNJgwB7NTPQkLBb04/81ptFp9H/H", - "nbGPa0sfP2+GPK8VamfftXowrdl2YBmzSlQlySO1jJAWN6idVIHGsA32Ps7YoBEMTNx/FbTIvN57UXKA", - "s2/Sb3/ht2+HAqVdylTdtIviKFFSYuL2txL1AhMZvzPkK175OFoZTJTkZmqhs1oChIRaCIyQCQJvNwLG", - "Mm2R90zVi4F2MRoW9oEVBZIDepN+ZgYSjayeOFW6YDY6jTizeOQGhByOX0qh0ayYnS70LkM5XqSWX8DP", - "VZ5DqjRUUnyq+jLm8NWNZbYiI6KsCocNsoz7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S+9KmGe1lyV8dJ6jkJOet66NA8P5ycBOq+KopKumbTVxqb", - "wX+3MgFTJQkak1a50+7pyePp0LeSVTZTWvyG3As9mQq9VHotOEcJR0C0GTCaGFrH7+Lox5BmS2lRS5aD", - "QX2J2rfGA+dHp++Hbn//cfcxjkxVFMwdaiIyAyThLdJUtW3rijhrVR80pH/jx8hjF439SfFtnawteuKJ", - "lWVeL3j8a11PfABeFZ4BanE3jBOrK9xNXPtDgCno8k+tKdm+tI27gka/ZLngUK8Nx/BWXkj1WULXIC7P", - "7gAST0/+vndHLNfI+BbwizDW9EB0I154UWNtF480uAFQ+k10ZaJrSh76nEn92hSdRyzPr0Rong9AaqIw", - "UG7ESGHiN2A0Jxhgp+5xYml8mOcTL5pZN9I6R6OavcFAK/QKLc3dk/V5q27zaaYYhEzyirvCMyBAnNOH", - "4Pi3MHZECJmZ6nAwMg5qNkIs1PQoOAGM05caQdpW32J3BpnvPo2QjcYgEbK2WXMenIFiLow98sg9IuT2", - "sTjFzluS7AiMO8HONW5/5hE0ic57nHRajwc21bnWsz89rzb1YqiP56SGbJKjkYha4MJcAJO8JtxqAqjA", - "wt34eCYIxoSRzZiFhEmprOMqSqaNozHo6MYs8MoDAoFJReeldukHpr1OOpaswBiYxuaUTWo4uCJv+K4G", - "ev+gp9FkhgbXdBLRKsODPxcaE+v20emqkdWES1JpjdLWthAGLrC0pMKPJyfuWaOttPTHzWGcjEm+3xsj", - "+0JjllAMRELt6D9FPz8D2iH8rd72iuy+CHBEHxsQVg6pYpJGF/CmxESk24aQY6ajDJXuE4QhXAw4y1s6", - "Nswwo996dPC22XNquO3y6E8hjQKDJoB40pGH7uRA8vT2N3423GWqKnmvmpImpias+GwnYpEVN9ITNxxe", - "DDXFB4QOz/HFsNGqcuVkvfUUFg3t6dfwnMHeeUTI3Un7M0cCXqP56ZuqRE0b/6uD3t9Bj3Eyj9vm6mT2", - "SH7eiHzPvFGgUDd6u0p3p21DnWJH1wJqcHM2yog3Dorz7m79cIKmB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AtGUJHh80oHex0fxSKo1XgrVmNMeZ/N5/Ds4", + "w1zpWUxZzaQRThq5S3G0kxUcSy6ccwx8KtAWqIGFUaA0WNSVkMwiMMorZFchodbqXKOh+IjgfQvK08Qi", + "q06XTOFeguAorcgF6hU8r2q7Bj96EKT7zDVG01CdrdXU/NqwKZmxEAbuip1J7AqepD3kIwHc2mDu2CkK", + "R9AfbSgW0K+wVIx3XYFZbgeE5PgZI174qanOULuq2GlNLneWokHAcouanjUtF0esuRB1HVug0w5yUaKB", + "EnMLqrFtIaZF3Jw7dW6v/TLdpPOGbeqbsPFew7ghrV73SW2xd/FhEceyf+dirUbtUAR78MCD7YH7V7s1", + "BuhL4UEXbyTQPcVzTOpmKzEIa6zU5SzquwzFmWVnzOAKjnOQyroQvhQceQq21/WTKEs4cz7IUWvk/fgW", + "p22S+S6WJJQs1w+HOcELEeCDDNUop3Q0N/SaL2aI46MWKMPkFqwZg+LE/+MlYr6fQWrm9ZrZYq7dz8wW", + "827SgTyamzQyE4PO22INwqeigNCr+1BSqJsyuily25bjwQ69I3VMvqugNHj4ZefWzKI0w3ETv7oesO1Y", + "AFlWQDcEGOcGvsPV+SqF98njg+p94n48Kt4nD1dbVzOnLrdsS3G9qE9DrsDYQphhJYe9RyByaGQpKrHY", + "6s77v0jTlw6LJOX5aBT4EhetWFShSUNhgM07VhePUg3bjzOlSmQy3rudIKv6LLcFHv0Kux+qJz1h5CR9", + "d63AJF76+jvcWCxu/ovabGUbLr3AfA9hZJsRAhzgJSsvmRS/osc0HKz+tnr88GqV23XmSjr0YdZoYdev", + "nem9XmfINOqnjS36pxdttP7r7YkDI0knh+Ftr0JhbZ1s3MRtLhhv7enPx+QAbzy3q2cnL4b9QmPcn0+l", + "EWclZQRhSzdxv/ljaSyTGa3amTAhYzizqxolq0VymDxeHaweJymlONqY9/d+pmQuzveyArML8ory9Vm1", + "BNExd80GST0jIWdP70Wa5/uDg0hzoqqqka4j9uXQFvC/tczANFmGxuRN6bR7cvBoPvSN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V1x4p0LWHuz4gZt0q", + "IA4/dJvUcDq3MevuDlbeSIZ0SsEoLyZR0DmnLtkatQFJt0HO/Cgtnas4ZKWgFFYi0xI+FSIrWuVSOsMY", + "Ff71jK4wpkGTjlvggpl5D/sSbbjcuU2gTm+eIhDtr1NaD902Nq+Dtoh2DlK7XS7ccn34A10p7HYxMPho", + "i+xRosV7eU3Qlx/RQoRgRVf5fBlWz+n9CFa3FLiTTy1i55ruUwdSCod8RLlehM4zT9H4QaPThPs7ZNoU", + "rFKATLt8WbHPw28cNLKscDQU2mz18BoYu6oRuc2i5R3nv/hp7abyUZr2CCiQlbYYFKlZ1v6nl/iNvh/f", + "//cfflz5rewcCK9RX4oMXc3z2q+nthmZwuvv66Xfc7/60p5bxL9uvy/8HXHvJehTLYGXyG8Hgd98LnNn", + "9/H9H3E2zp/XOUd9eyXy5k9Pd3GuiVaUzeb/AwCCe0XjljUAAA==", } // GetSwagger returns the content of the embedded swagger specification file diff --git a/galvanize-instancer/pkg/restserver.go b/galvanize-instancer/pkg/restserver.go index 8d2a564..a9458f3 100755 --- a/galvanize-instancer/pkg/restserver.go +++ b/galvanize-instancer/pkg/restserver.go @@ -35,6 +35,7 @@ type Server struct { kmu keymutex.KeyMutex wg sync.WaitGroup jobQueue *worker.Queue // Redis job queue (optional, nil means use direct goroutines) + version string // reported to admins only } // ServerOpts holds the dependencies needed to construct a Server. @@ -50,6 +51,8 @@ type ServerOpts struct { ExpiryScheduler *scheduler.ExpiryScheduler KeyMutex keymutex.KeyMutex JobQueue *worker.Queue // Optional: if provided, jobs are queued to Redis + // Version of the running Galvanize, reported to admins only + Version string } var _ api.ServerInterface = (*Server)(nil) @@ -79,6 +82,7 @@ func NewServerWithOpts(opts ServerOpts) *Server { expirySched: opts.ExpiryScheduler, kmu: kmu, jobQueue: opts.JobQueue, + version: opts.Version, } } diff --git a/galvanize-instancer/pkg/restserver_admin.go b/galvanize-instancer/pkg/restserver_admin.go index 1c7c2ec..c5c300a 100644 --- a/galvanize-instancer/pkg/restserver_admin.go +++ b/galvanize-instancer/pkg/restserver_admin.go @@ -231,6 +231,25 @@ func (s *Server) TerminateAdminInstance(ctx echo.Context) error { return ctx.NoContent(200) } +// GetVersion reports the running Galvanize version, to admins only: the +// project is open source, so a version tells anyone its known issues. +// Requests without a valid token never get here (the JWT middleware rejects +// them); player tokens are refused. +func (s *Server) GetVersion(ctx echo.Context) error { + claims, err := auth.GetClaims(ctx) + if err != nil { + return ctx.JSON(401, api.Error{Message: utils.Ptr("Unauthorized")}) + } + if claims.Role != "admin" { + return ctx.JSON(403, api.Error{Message: utils.Ptr("Forbidden - Admin access required")}) + } + version := s.version + if version == "" { + version = "unknown" + } + return ctx.JSON(200, api.VersionResponse{Version: version}) +} + func (s *Server) DeployAllAdminInstances(ctx echo.Context) error { claims, err := auth.GetClaims(ctx) if err != nil { From 09f4eabc0595ab81585202f878950a3a577dab84 Mon Sep 17 00:00:00 2001 From: CorentinFelten Date: Fri, 2 Oct 2026 00:30:04 -0400 Subject: [PATCH 3/3] fix: stop serving metrics on the API port The API served /metrics on its own port, skipped by the JWT middleware, so anyone who could reach the API read every metric: challenge names, team IDs, deployment counts. The route predates the metrics server on :5001 (basic auth when metrics.password is set), added later with the Prometheus and Grafana stack, which scrapes instancer:5001 as the README documents. Nothing else uses the API port's route: not the monitoring stack, the load test, Zync, nor ctfd-management, whose Traefik router already excludes /metrics. It is removed, along with its JWT exemption: the API port now answers /metrics with 401, or 404 with a token. Request metrics are still gathered and served on :5001, unchanged. --- CHANGELOG.md | 3 ++ galvanize-instancer/cmd/metrics_test.go | 47 +++++++++++++++++++++++++ galvanize-instancer/cmd/serve.go | 8 ++--- 3 files changed, 54 insertions(+), 4 deletions(-) create mode 100644 galvanize-instancer/cmd/metrics_test.go diff --git a/CHANGELOG.md b/CHANGELOG.md index 1f9c7f3..3c4ce6a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,9 @@ ### 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:///`, then each published port as `://:` (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 diff --git a/galvanize-instancer/cmd/metrics_test.go b/galvanize-instancer/cmd/metrics_test.go new file mode 100644 index 0000000..8dc9247 --- /dev/null +++ b/galvanize-instancer/cmd/metrics_test.go @@ -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")) +} diff --git a/galvanize-instancer/cmd/serve.go b/galvanize-instancer/cmd/serve.go index c052589..ff50c7f 100755 --- a/galvanize-instancer/cmd/serve.go +++ b/galvanize-instancer/cmd/serve.go @@ -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") @@ -273,7 +273,7 @@ func configureQueueless(cfg *config.Config, jobQueue *worker.Queue, expirySched } // jwtMiddleware requires a valid HS256 token signed with secret on every -// route but /health and /metrics; handlers then check the claims' role. +// 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 { @@ -281,7 +281,7 @@ func jwtMiddleware(secret string) echo.MiddlewareFunc { }, SigningKey: []byte(secret), Skipper: func(c echo.Context) bool { - return c.Path() == "/health" || c.Path() == "/metrics" + return c.Path() == "/health" }, }) }