diff --git a/CHANGELOG.md b/CHANGELOG.md index f8583ec..fcea782 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,17 @@ ## vX.X.X (YYYY-MM-DD) +## v0.7.5 (2026-11-11) + +### Added +- `GET /admin/version` returns the running version (e.g. `{"version": "0.7.5"}`), 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 HTTP endpoint of an instance, one per line, ordered by compose service: each host of each Traefik router rule as `https:///`. Only the first container with a route was reported, so a challenge with several web services showed only one of them, depending on the order Ansible listed the containers. Without any route, the published ports of every container are listed, sorted by container port, instead of only the first container's; with `show_tcp_ports`, they follow the HTTP endpoints as before. 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.4 (2026-10-27) ### Added diff --git a/data/challenges/example/custom_compose/challenge.yml b/data/challenges/example/custom_compose/challenge.yml index a60a311..9e922dd 100644 --- a/data/challenges/example/custom_compose/challenge.yml +++ b/data/challenges/example/custom_compose/challenge.yml @@ -30,6 +30,11 @@ 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 https:/// + # endpoint, one per line, ordered by service name. Published tcp ports + # (://:) are listed when nothing is exposed over + # http, or after the http endpoints with `show_tcp_ports: true`. expose: - service: web port: 80 diff --git a/galvanize-instancer/api/openapi.yaml.in b/galvanize-instancer/api/openapi.yaml.in index 36acaf8..0d86b6f 100755 --- a/galvanize-instancer/api/openapi.yaml.in +++ b/galvanize-instancer/api/openapi.yaml.in @@ -1,7 +1,7 @@ openapi: 3.0.3 info: title: Galvanize Instancer - version: 0.7.4 + version: 0.7.5 description: API for deploying CTF challenges using Ansible paths: @@ -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/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 16b0a71..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") @@ -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; 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 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/constants.go b/galvanize-instancer/constants.go index cf99851..d81de1c 100644 --- a/galvanize-instancer/constants.go +++ b/galvanize-instancer/constants.go @@ -1,5 +1,5 @@ package main const ( - Version = "0.7.4" + Version = "0.7.5" ) diff --git a/galvanize-instancer/internal/ansible/connection_info.go b/galvanize-instancer/internal/ansible/connection_info.go index 42eab33..1f4b7b3 100644 --- a/galvanize-instancer/internal/ansible/connection_info.go +++ b/galvanize-instancer/internal/ansible/connection_info.go @@ -2,103 +2,100 @@ package ansible import ( "fmt" + "regexp" "sort" "strings" ) -// GetConnectionInfo returns the first Traefik HTTP URL found, or else the -// published ports. When showTCPPorts is set, the published ports of every -// container are listed after the HTTP URL instead of being hidden by it. +// hostRule matches each Host(`name`) of a Traefik router rule +var hostRule = regexp.MustCompile("Host\\(`([^`]+)`\\)") + +// GetConnectionInfo returns how players reach a deployed instance, one +// endpoint per line. Every container routed by Traefik gives https:/// +// for each Host() of its routers' rules, containers taken in compose service +// order so the result does not depend on the order Ansible reports them in. +// Published ports give ://:, the scheme being the port's +// protocol hint, or else the port's protocol (tcp, udp), sorted by container +// port. They are listed when no container is routed by Traefik, or after the +// HTTP URLs when showTCPPorts is set. func GetConnectionInfo(containerInfos []ContainerInfo, host string, protocolHints map[int]string, showTCPPorts bool) (string, error) { - if showTCPPorts { - return getAllConnectionInfo(containerInfos, host, protocolHints) - } - traefikLabel := "" - for _, ci := range containerInfos { - for labelKey, labelValue := range ci.Labels { - if strings.HasPrefix(labelKey, "traefik.http.routers.") { - traefikLabel = labelValue - break - } - } - // Check if we have a traefik label - if traefikLabel != "" { - labelParts := strings.Split(traefikLabel, "`") - if len(labelParts) >= 2 { - domainName := "https://" + labelParts[1] + "/" - return domainName, nil - } - } - // Check if we have published ports - ports := publishedPortURLs(ci.Publishers, host, protocolHints) - if len(ports) > 0 { - return strings.Join(ports, "\n"), nil + 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) } } - return "", fmt.Errorf("no connection info found") -} -func getAllConnectionInfo(containerInfos []ContainerInfo, host string, protocolHints map[int]string) (string, error) { - var lines []string - for _, ci := range containerInfos { - if url := traefikURL(ci.Labels); url != "" { - lines = append(lines, url) - break + for _, ci := range containers { + for _, domain := range traefikDomains(ci.Labels) { + add("https://" + domain + "/") } } - var publishers []PublisherInfo - for _, ci := range containerInfos { - publishers = append(publishers, ci.Publishers...) - } - // Docker does not guarantee publisher order; sort so the output is stable. - sort.SliceStable(publishers, func(i, j int) bool { - if publishers[i].TargetPort != publishers[j].TargetPort { - return publishers[i].TargetPort < publishers[j].TargetPort + + if len(endpoints) == 0 || showTCPPorts { + var publishers []PublisherInfo + for _, ci := range containers { + publishers = append(publishers, ci.Publishers...) } - return publishers[i].PublishedPort < publishers[j].PublishedPort - }) - seen := map[string]bool{} - for _, port := range publishedPortURLs(publishers, host, protocolHints) { - if !seen[port] { - seen[port] = true - lines = append(lines, port) + // Docker does not guarantee publisher order; sort so the output is stable + sort.SliceStable(publishers, func(i, j int) bool { + if publishers[i].TargetPort != publishers[j].TargetPort { + return publishers[i].TargetPort < publishers[j].TargetPort + } + return publishers[i].PublishedPort < publishers[j].PublishedPort + }) + for _, pub := range publishers { + // 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(lines) == 0 { + + if len(endpoints) == 0 { return "", fmt.Errorf("no connection info found") } - return strings.Join(lines, "\n"), nil + return strings.Join(endpoints, "\n"), nil } -func traefikURL(labels map[string]string) string { - for labelKey, labelValue := range labels { - if !strings.HasPrefix(labelKey, "traefik.http.routers.") { - continue - } - labelParts := strings.Split(labelValue, "`") - if len(labelParts) >= 2 { - return "https://" + labelParts[1] + "/" +// 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) } } - return "" -} + sort.Strings(ruleKeys) -func publishedPortURLs(publishers []PublisherInfo, host string, protocolHints map[int]string) []string { - var ports []string - for _, pub := range 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)) + var domains []string + for _, key := range ruleKeys { + for _, m := range hostRule.FindAllStringSubmatch(labels[key], -1) { + domains = append(domains, m[1]) } } - return ports + 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 40abacf..0257550 100644 --- a/galvanize-instancer/internal/ansible/connection_info_test.go +++ b/galvanize-instancer/internal/ansible/connection_info_test.go @@ -161,3 +161,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, false) + require.NoError(t, err) + assert.Equal(t, "https://p.challs.example.com/", conn) +} + +// A web front end and an SSH service with show_tcp_ports: both endpoints, +// whatever order Ansible reports the containers in. +func TestGetConnectionInfo_WebAndSSHServices(t *testing.T) { + web := webContainer("web", "p", "p.challs.example.com") + ssh := sshContainer("p", 40022) + want := "https://p.challs.example.com/\ntcp://challs.example.com:40022" + hints := map[int]string{} + + for _, order := range [][]ContainerInfo{{web, ssh}, {ssh, web}} { + conn, err := GetConnectionInfo(order, "challs.example.com", hints, true) + require.NoError(t, err) + assert.Equal(t, want, conn) + } + + hints[22] = "ssh" + conn, err := GetConnectionInfo([]ContainerInfo{web, ssh}, "challs.example.com", hints, true) + require.NoError(t, err) + assert.Equal(t, "https://p.challs.example.com/\nssh://challs.example.com:40022", 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, false) + 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, false) + 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, false) + 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"}, false) + 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, false) + assert.Error(t, err) +} diff --git a/galvanize-instancer/pkg/api/api.gen.go b/galvanize-instancer/pkg/api/api.gen.go index abc3891..d506002 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+jLm8NWNZ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EyVRsjpIMkwv3ulS+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", - "SH7eiHzPvFGgUDd6u0p3p21DnWJH1wJqcHM2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kkEggjkWlW0cs5EiXygQDQlCR6fdKD38VE8kmqNl0I15rTH2Xwe/w7O", + "MFd6FlNWM2mEk0buUhztZAXHkgvnHAOfCrQFamBhFCgNFnUlJLMIjPIK2VVIqLU612goPiJ434LyNLHI", + "qtMlU7iXIDhKK3KBegXPq9quwY8eBOk+c43RNFRnazU1vzZsSmYshIG7YmcSu4InaQ/5SAC3Npg7dorC", + "EfRHG4oF9CssFeNdV2CW2wEhOX7GiBd+aqoz1K4qdlqTy52laBCw3KKmZ03LxRFrLkRdxxbotINclGig", + "xNyCamxbiGkRN+dOndtrv0w36bxhm/ombLzXMG5Iq9d9UlvsXXxYxLHs37lYq1E7FMEe3PNgu+f+1W6N", + "AfpSuNfFGwl0T/Eck7rZSgzCGit1OYv6LkNxZtkZM7iC4xyksi6ELwVHnoLtdf0kyhLOnA9y1Bp5P77F", + "aZtk7seShJLl+sEwJ3ghAnyQoRrllI7mhl7zxQxxfNQCZZjcgjVjUJz4f7xEzPczSM28XjNbzLX7mdli", + "3k06kEdzk0ZmYtB5W6xB+FQUEHp1H0oKdVNGN0Vu23I82KF3pI7JdxWUBg+/7NyaWZRmOG7iV9cDth0L", + "IMsK6IYA49zAfVydr1J4nzw6qN4n7sfD4n3yYLV1NXPqcsu2FNeL+jTkCowthBlWcth7CCKHRpaiEout", + "7rz/izR96bBIUp6PRoEvcdGKRRWaNBQG2LxjdfEo1bD9OFOqRCbjvdsJsqrPclvg0a+w+6F60hNGTtJ3", + "1wpM4qWvv8ONxeLmv6jNVrbh0gvM9xBGthkhwAFesvKSSfErekzDwepvq0cPrla5XWeupEMfZo0Wdv3a", + "md7rdYZMo37a2KJ/etFG67/enjgwknRyGN72KhTW1snGTdzmgvHWnv58TA7wxnO7enbyYtgvNMb9+VQa", + "cVZSRhC2dBP3mz+WxjKZ0aqdCRNnjCfO7KpGyWqRHCaPVgerR0lKKY425v29nymZi/O9rMDsgryifH1W", + "LUF0zF2zQVLPSMjZ03uR5vnh4CDSnKiqaqTriH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ePNaVM3gjiNajF7RMcDQmeHyimuPFOjaw10fELNu", + "FRCHH7pNajid25h1dwcrbyRDOqVglBeTKOicU5dsjdqApNsgZ36Uls5VHLJSUAorkWkJnwqRFa1yKZ1h", + "jAr/ekZXGNOgScctcMHMvId9iTZc7twmUKc3TxGI9tcprYduG5vXQVtEOwep3S4Xbrk+/IGuFHa7GBh8", + "tEX2KNHid3lN0Jcf0UKEYEVX+XwZVs/p/QhWtxS4k08tYuea7lMHUgqHfES5XoTOM0/R+EGj04T7O2Ta", + "FKxSgEy7fFmxz8NvHDSyrHA0FNps9eAaGLuqEbnNouUd57/4ae2m8lGa9ggokJW2GBSpWdb+p5f4jb4f", + "3//3H35c+a3sHAivUV+KDF3N89qvp7YZmcLr7+ul33O/+tKeW8S/br8v/B1x7yXoUy2Bl8hvB4HffC5z", + "Z/fx/R9xNs6f1zlHfXsl8uZPT3dxrolWlM3m/wMAd0nbbZY1AAA=", } // 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 5749b7e..cb382bf 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 68db65a..82fb534 100644 --- a/galvanize-instancer/pkg/restserver_admin.go +++ b/galvanize-instancer/pkg/restserver_admin.go @@ -236,6 +236,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 {