From d28a79fd4dade93643d0f753f96e81c0c2946fd9 Mon Sep 17 00:00:00 2001 From: CorentinFelten Date: Thu, 1 Oct 2026 16:58:35 -0400 Subject: [PATCH 1/5] fix: set the PID limit under deploy.resources.limits Docker Compose 2.38 and later reject a service that sets the service-level pids_limit next to deploy.resources.limits: services.web: can't set distinct values on 'pids_limit' and 'deploy.resources.limits.pids': invalid compose project BuildResourceOverrides emitted exactly that whenever a PID limit and a CPU or memory limit were configured, which is the default (default_resource_limits in config.example.yaml), so every deployment failed on current Docker installs. The PID limit is now emitted as deploy.resources.limits.pids, next to cpus and memory. The pids_limit setting in config.yaml and challenge.yml keeps its name. The custom_compose playbook also drops a pids_limit set in the challenge's own compose file when Galvanize sets the PID limit, as it would otherwise hit the same error; Galvanize's limit applies, as it did when it overwrote pids_limit. The services are replaced as a whole, since a recursive combine cannot remove a key. --- CHANGELOG.md | 3 ++ data/playbooks/custom_compose.yaml | 20 ++++++++- .../internal/ansible/playbook.go | 12 +++-- .../internal/ansible/playbook_test.go | 44 +++++++++++++++++++ galvanize-instancer/pkg/config/config.go | 2 +- 5 files changed, 76 insertions(+), 5 deletions(-) create mode 100644 galvanize-instancer/internal/ansible/playbook_test.go diff --git a/CHANGELOG.md b/CHANGELOG.md index 4fdeb97..e057b0c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,9 @@ ## vX.X.X (YYYY-MM-DD) +### Fixed +- Deployments failing on Docker Compose 2.38+ with `can't set distinct values on 'pids_limit' and 'deploy.resources.limits.pids'`: the PID limit is now set as `deploy.resources.limits.pids`, next to the CPU and memory limits, instead of the service-level `pids_limit`. The `custom_compose` playbook drops a `pids_limit` set in the challenge's own compose file, so Galvanize's limit applies as before + ## v0.7.1 (2026-06-02) ### Added diff --git a/data/playbooks/custom_compose.yaml b/data/playbooks/custom_compose.yaml index c0efb0e..f493fb7 100644 --- a/data/playbooks/custom_compose.yaml +++ b/data/playbooks/custom_compose.yaml @@ -16,9 +16,19 @@ - create - delete + # The PID limit is set as deploy.resources.limits.pids. Docker Compose + # 2.38+ rejects a service that also sets the service-level pids_limit, so + # a pids_limit from the challenge's own compose file is dropped and + # Galvanize's limit applies, as it did when it was set as pids_limit. + # The services are then replaced as a whole: a recursive combine into + # compose_dict could not remove that key. - name: Apply resource limits to each service ansible.builtin.set_fact: - compose_dict: "{{ compose_dict | combine({'services': {item.key: item.value | combine(resource_overrides, recursive=True)}}, recursive=True) }}" + _limited_services: >- + {{ _limited_services | default({}) | combine({item.key: + ((item.value | dict2items | rejectattr('key', 'equalto', 'pids_limit') | items2dict) + if resource_overrides.deploy.resources.limits.pids is defined else item.value) + | combine(resource_overrides, recursive=True)}) }} loop: "{{ _original_services | dict2items }}" loop_control: label: "{{ item.key }}" @@ -27,6 +37,14 @@ - create - delete + - name: Use the limited services + ansible.builtin.set_fact: + compose_dict: "{{ compose_dict | combine({'services': _limited_services}) }}" + when: resource_overrides is defined and resource_overrides | length > 0 + tags: + - create + - delete + - name: Déploiement du docker-compose community.docker.docker_compose_v2: definition: "{{ compose_dict }}" diff --git a/galvanize-instancer/internal/ansible/playbook.go b/galvanize-instancer/internal/ansible/playbook.go index 7a35578..4b95750 100644 --- a/galvanize-instancer/internal/ansible/playbook.go +++ b/galvanize-instancer/internal/ansible/playbook.go @@ -27,6 +27,12 @@ func generateRandomID() string { // BuildResourceOverrides converts merged ResourceLimits into a map suitable // for Ansible's combine filter. The resulting dict is merged into each Docker // Compose service definition by the playbooks. +// +// All limits, the PID limit included, go under deploy.resources.limits. +// Docker Compose 2.38 and later reject a service that sets the service-level +// pids_limit next to deploy.resources.limits ("can't set distinct values on +// 'pids_limit' and 'deploy.resources.limits.pids'"), which made every +// deployment with a PID limit and a CPU or memory limit fail. func BuildResourceOverrides(rl config.ResourceLimits) map[string]interface{} { limits := map[string]interface{}{} if rl.CPUs != "" { @@ -35,6 +41,9 @@ func BuildResourceOverrides(rl config.ResourceLimits) map[string]interface{} { if rl.Memory != "" { limits["memory"] = rl.Memory } + if rl.PidsLimit > 0 { + limits["pids"] = rl.PidsLimit + } overrides := map[string]interface{}{} if len(limits) > 0 { @@ -44,9 +53,6 @@ func BuildResourceOverrides(rl config.ResourceLimits) map[string]interface{} { }, } } - if rl.PidsLimit > 0 { - overrides["pids_limit"] = rl.PidsLimit - } return overrides } diff --git a/galvanize-instancer/internal/ansible/playbook_test.go b/galvanize-instancer/internal/ansible/playbook_test.go new file mode 100644 index 0000000..e75a478 --- /dev/null +++ b/galvanize-instancer/internal/ansible/playbook_test.go @@ -0,0 +1,44 @@ +package ansible + +import ( + "testing" + + "github.com/28Pollux28/galvanize/pkg/config" + "github.com/stretchr/testify/assert" +) + +func limitsOf(overrides map[string]interface{}) map[string]interface{} { + deploy, _ := overrides["deploy"].(map[string]interface{}) + resources, _ := deploy["resources"].(map[string]interface{}) + limits, _ := resources["limits"].(map[string]interface{}) + return limits +} + +func TestBuildResourceOverrides_AllLimitsUnderDeployResources(t *testing.T) { + overrides := BuildResourceOverrides(config.ResourceLimits{CPUs: "1", Memory: "512M", PidsLimit: 256}) + + assert.Equal(t, map[string]interface{}{"cpus": "1", "memory": "512M", "pids": 256}, limitsOf(overrides)) + // Docker Compose 2.38+ rejects pids_limit next to deploy.resources.limits + assert.NotContains(t, overrides, "pids_limit") + assert.Len(t, overrides, 1) +} + +func TestBuildResourceOverrides_PidsOnly(t *testing.T) { + overrides := BuildResourceOverrides(config.ResourceLimits{PidsLimit: 128}) + + assert.Equal(t, map[string]interface{}{"pids": 128}, limitsOf(overrides)) + assert.NotContains(t, overrides, "pids_limit") +} + +func TestBuildResourceOverrides_NoLimits(t *testing.T) { + assert.Empty(t, BuildResourceOverrides(config.ResourceLimits{})) +} + +func TestBuildResourceOverrides_MergedChallengeOverride(t *testing.T) { + merged := config.MergeResourceLimits( + config.ResourceLimits{CPUs: "1", Memory: "512M", PidsLimit: 256}, + config.ResourceLimits{PidsLimit: 512}, + ) + + assert.Equal(t, map[string]interface{}{"cpus": "1", "memory": "512M", "pids": 512}, limitsOf(BuildResourceOverrides(merged))) +} diff --git a/galvanize-instancer/pkg/config/config.go b/galvanize-instancer/pkg/config/config.go index c876d15..847d009 100755 --- a/galvanize-instancer/pkg/config/config.go +++ b/galvanize-instancer/pkg/config/config.go @@ -74,7 +74,7 @@ type AnsibleConfig struct { } // ResourceLimits defines container resource constraints applied via Docker Compose. -// CPUs and Memory map to deploy.resources.limits; PidsLimit maps to the service-level pids_limit. +// All three map to deploy.resources.limits (cpus, memory, pids) in Docker Compose. type ResourceLimits struct { CPUs string `mapstructure:"cpus" yaml:"cpus,omitempty"` // e.g. "0.5", "1", "2" Memory string `mapstructure:"memory" yaml:"memory,omitempty"` // e.g. "256M", "512M", "1G" From 7c26e0d4037133164746513f8ce3c20eec60dd64 Mon Sep 17 00:00:00 2001 From: CorentinFelten Date: Thu, 1 Oct 2026 17:25:50 -0400 Subject: [PATCH 2/5] fix: keep same-named challenges in different categories apart Challenge names are only unique within a category, but three places used the name alone: - DeployInstance and TerminateInstance compared only the challenge name of the request with the JWT's, so a token for web/login could deploy or terminate pwn/login; - the per-instance deploy lock was keyed on name + team; - BuildComposeProject built the Docker Compose project name, which also names the instance's Traefik router and subdomain, from the name and team, so two such instances shared one project. Its suffix did not help either: sha1.New().Sum(name) appends the hash of nothing to name instead of hashing it, so hexSum[:6] was always the hex of "pol", 706f6c. The JWT check and the lock key now include the category, and project names are the sanitized category, name and team, cut to fit a 63-character DNS label, plus 8 hex characters of a SHA-1 of the instance's identity. Instances started before an upgrade keep their old project name: PreparePlaybook passes it as legacy_compose_project when it differs, and the http, tcp and custom_compose playbooks' delete tasks also run docker compose -p down, a no-op when nothing exists and never failing the run, so terminating them leaves nothing behind. --- CHANGELOG.md | 5 ++ data/challenges/example/http/challenge.yml | 2 +- data/playbooks/custom_compose.yaml | 11 +++ data/playbooks/http.yaml | 11 +++ data/playbooks/tcp.yaml | 11 +++ .../internal/ansible/compose_expose.go | 2 +- .../internal/ansible/playbook.go | 9 +- .../internal/docker/compose.go | 55 +++++++++--- .../internal/docker/compose_test.go | 89 +++++++++++++++++++ galvanize-instancer/pkg/restserver.go | 18 ++-- galvanize-instancer/pkg/restserver_admin.go | 2 +- galvanize-instancer/pkg/restserver_test.go | 43 +++++++++ 12 files changed, 239 insertions(+), 19 deletions(-) create mode 100644 galvanize-instancer/internal/docker/compose_test.go diff --git a/CHANGELOG.md b/CHANGELOG.md index e057b0c..832d284 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,8 +2,13 @@ ## vX.X.X (YYYY-MM-DD) +### Changed +- Docker Compose project names, which also name the subdomains of instances, now include the category and a hash of the instance's identity (e.g. `polypwn-web-login-team1-`). Instances already running when upgrading keep their previous name: terminating them also removes the project under that name, so no containers are left behind + ### Fixed - Deployments failing on Docker Compose 2.38+ with `can't set distinct values on 'pids_limit' and 'deploy.resources.limits.pids'`: the PID limit is now set as `deploy.resources.limits.pids`, next to the CPU and memory limits, instead of the service-level `pids_limit`. The `custom_compose` playbook drops a `pids_limit` set in the challenge's own compose file, so Galvanize's limit applies as before +- Same-named challenges in different categories no longer collide: the category is now part of the deploy and terminate check against the JWT (a token for `web/login` cannot deploy or terminate `pwn/login`), of the per-instance lock, and of the Docker Compose project name +- Compose project names end with a real hash of the instance's identity: the previous suffix was always `706f6c`, since `sha1.New().Sum(name)` appended the hash of nothing to the name instead of hashing it. Names are also cut to fit a 63-character DNS label ## v0.7.1 (2026-06-02) diff --git a/data/challenges/example/http/challenge.yml b/data/challenges/example/http/challenge.yml index 15939c9..d4f4b8c 100644 --- a/data/challenges/example/http/challenge.yml +++ b/data/challenges/example/http/challenge.yml @@ -6,7 +6,7 @@ type: zync # The 'http' playbook deploys a single container behind Traefik. # Traefik routes traffic based on a generated subdomain: -# . (e.g. polypwn-example-http-team1-a3f2c1.challs.example.com) +# . (e.g. polypwn-web-example-http-team1-9448f1e7.challs.example.com) playbook_name: http deploy_parameters: diff --git a/data/playbooks/custom_compose.yaml b/data/playbooks/custom_compose.yaml index f493fb7..b1706ea 100644 --- a/data/playbooks/custom_compose.yaml +++ b/data/playbooks/custom_compose.yaml @@ -65,3 +65,14 @@ state: absent tags: - delete + + # Instances started by Galvanize v0.7.1 or earlier have another project + # name (legacy_compose_project, set when it differs): remove such a + # leftover too. A no-op when there is none, and never fails the run. + - name: Remove an instance left under its previous project name + ansible.builtin.command: "docker compose -p {{ legacy_compose_project }} down --remove-orphans" + when: legacy_compose_project is defined + changed_when: false + failed_when: false + tags: + - delete diff --git a/data/playbooks/http.yaml b/data/playbooks/http.yaml index 58d2909..2330005 100644 --- a/data/playbooks/http.yaml +++ b/data/playbooks/http.yaml @@ -61,3 +61,14 @@ project_name: "{{ compose_project }}" state: absent tags: delete + + # Instances started by Galvanize v0.7.1 or earlier have another project + # name (legacy_compose_project, set when it differs): remove such a + # leftover too. A no-op when there is none, and never fails the run. + - name: Remove an instance left under its previous project name + ansible.builtin.command: "docker compose -p {{ legacy_compose_project }} down --remove-orphans" + when: legacy_compose_project is defined + changed_when: false + failed_when: false + tags: + - delete diff --git a/data/playbooks/tcp.yaml b/data/playbooks/tcp.yaml index 69aa9c5..b64efda 100755 --- a/data/playbooks/tcp.yaml +++ b/data/playbooks/tcp.yaml @@ -45,3 +45,14 @@ project_name: "{{ compose_project }}" state: absent tags: delete + + # Instances started by Galvanize v0.7.1 or earlier have another project + # name (legacy_compose_project, set when it differs): remove such a + # leftover too. A no-op when there is none, and never fails the run. + - name: Remove an instance left under its previous project name + ansible.builtin.command: "docker compose -p {{ legacy_compose_project }} down --remove-orphans" + when: legacy_compose_project is defined + changed_when: false + failed_when: false + tags: + - delete diff --git a/galvanize-instancer/internal/ansible/compose_expose.go b/galvanize-instancer/internal/ansible/compose_expose.go index 527c904..f2cd699 100644 --- a/galvanize-instancer/internal/ansible/compose_expose.go +++ b/galvanize-instancer/internal/ansible/compose_expose.go @@ -66,7 +66,7 @@ func applyComposeExposures(conf *config.Config, chall *challenge.Challenge, team return nil, fmt.Errorf("compose definition has no services map") } - project := docker.BuildComposeProject(chall.Unique, chall.Name, teamID) + project := docker.BuildComposeProject(chall.Unique, chall.Category, chall.Name, teamID) domainRoot := conf.Instancer.InstancerHost traefikNetwork, _ := conf.Instancer.ExtraDeploymentParameters[traefikNetworkParam].(string) diff --git a/galvanize-instancer/internal/ansible/playbook.go b/galvanize-instancer/internal/ansible/playbook.go index 4b95750..1e55809 100644 --- a/galvanize-instancer/internal/ansible/playbook.go +++ b/galvanize-instancer/internal/ansible/playbook.go @@ -57,7 +57,7 @@ func BuildResourceOverrides(rl config.ResourceLimits) map[string]interface{} { } func PreparePlaybook(conf *config.Config, tag string, challenge *challenge.Challenge, teamID string, params map[string]interface{}) (execute.Executor, *bytes.Buffer) { - composeProject := docker.BuildComposeProject(challenge.Unique, challenge.Name, teamID) + composeProject := docker.BuildComposeProject(challenge.Unique, challenge.Category, challenge.Name, teamID) // Ansible playbook options playbookOpts := &playbook.AnsiblePlaybookOptions{ @@ -80,6 +80,13 @@ func PreparePlaybook(conf *config.Config, tag string, challenge *challenge.Chall maps.Copy(playbookOpts.ExtraVars, params) maps.Copy(playbookOpts.ExtraVars, conf.Instancer.ExtraDeploymentParameters) + // Instances started by Galvanize v0.7.1 or earlier used another project + // name. The playbooks' delete tasks also remove a project left under that + // name, so upgrading does not leave running instances behind. + if legacy := docker.LegacyComposeProject(challenge.Unique, challenge.Name, teamID); legacy != composeProject { + playbookOpts.ExtraVars["legacy_compose_project"] = legacy + } + // Merge resource limits (challenge overrides config defaults) and pass to Ansible merged := config.MergeResourceLimits(conf.Instancer.DefaultResourceLimits, challenge.ResourceLimits) if resourceOverrides := BuildResourceOverrides(merged); len(resourceOverrides) > 0 { diff --git a/galvanize-instancer/internal/docker/compose.go b/galvanize-instancer/internal/docker/compose.go index 6559558..2b6214b 100644 --- a/galvanize-instancer/internal/docker/compose.go +++ b/galvanize-instancer/internal/docker/compose.go @@ -34,17 +34,52 @@ func SanitizeProjectName(name string) string { return s } -func BuildComposeProject(unique bool, challengeName, teamID string) string { - var composeProject string +// projectSuffixLen is the number of hex characters of the identity hash +// appended to project names. +const projectSuffixLen = 8 + +// maxProjectNameLen keeps a project name usable as a single DNS label: it is +// also the instance's subdomain (.). +const maxProjectNameLen = 63 + +// BuildComposeProject returns the Docker Compose project name of a challenge +// instance, which also names its Traefik router and subdomain. It is made of +// a readable part (category, challenge name and team), truncated so the whole +// name fits a 63-character DNS label, and the first 8 hex characters of a +// SHA-1 of the instance's identity. The hash keeps apart instances whose +// readable parts are equal: same-named challenges in different categories, +// names that only differ in characters sanitization removes, or names cut by +// the truncation. +func BuildComposeProject(unique bool, category, challengeName, teamID string) string { + var readable, identity string if unique { - composeProject = "global-" + challengeName - composeProject = SanitizeProjectName(composeProject) + readable = "global-" + category + "-" + challengeName + identity = "unique\x00" + category + "\x00" + challengeName } else { - composeProject = "polypwn-" + challengeName + "-" + teamID - composeProject = SanitizeProjectName(composeProject) - sum := sha1.New().Sum([]byte(composeProject)) - hexSum := hex.EncodeToString(sum) - composeProject = composeProject + "-" + hexSum[:6] + readable = "polypwn-" + category + "-" + challengeName + "-" + teamID + identity = "team\x00" + category + "\x00" + challengeName + "\x00" + teamID + } + + sum := sha1.Sum([]byte(identity)) + suffix := hex.EncodeToString(sum[:])[:projectSuffixLen] + + readable = SanitizeProjectName(readable) + if maxReadable := maxProjectNameLen - 1 - projectSuffixLen; len(readable) > maxReadable { + readable = strings.TrimRight(readable[:maxReadable], "-_") + } + return readable + "-" + suffix +} + +// LegacyComposeProject returns the project name Galvanize v0.7.1 and earlier +// gave an instance. It ignored the category, and its suffix was constant: +// sha1.New().Sum(b) appends the hash of nothing to b instead of hashing b, +// so the first 6 hex characters were always those of "pol". It is kept only +// so instances started before an upgrade can still be terminated. +func LegacyComposeProject(unique bool, challengeName, teamID string) string { + if unique { + return SanitizeProjectName("global-" + challengeName) } - return composeProject + composeProject := SanitizeProjectName("polypwn-" + challengeName + "-" + teamID) + sum := sha1.New().Sum([]byte(composeProject)) + return composeProject + "-" + hex.EncodeToString(sum)[:6] } diff --git a/galvanize-instancer/internal/docker/compose_test.go b/galvanize-instancer/internal/docker/compose_test.go new file mode 100644 index 0000000..708fbf7 --- /dev/null +++ b/galvanize-instancer/internal/docker/compose_test.go @@ -0,0 +1,89 @@ +package docker + +import ( + "regexp" + "strings" + "testing" + + "github.com/stretchr/testify/assert" +) + +// A Docker Compose project name that is also a valid DNS label +var validProject = regexp.MustCompile(`^[a-z0-9][a-z0-9_-]{0,62}$`) + +func TestBuildComposeProject_SameNameDifferentCategories(t *testing.T) { + web := BuildComposeProject(false, "web", "login", "team1") + pwn := BuildComposeProject(false, "pwn", "login", "team1") + + assert.NotEqual(t, web, pwn) + assert.True(t, strings.HasPrefix(web, "polypwn-web-login-team1-"), web) + assert.True(t, strings.HasPrefix(pwn, "polypwn-pwn-login-team1-"), pwn) + + assert.NotEqual(t, + BuildComposeProject(true, "web", "login", ""), + BuildComposeProject(true, "pwn", "login", "")) +} + +func TestBuildComposeProject_Format(t *testing.T) { + // The example in data/challenges/example/http/challenge.yml + assert.Equal(t, "polypwn-web-example-http-team1-9448f1e7", BuildComposeProject(false, "web", "example-http", "team1")) +} + +func TestBuildComposeProject_SuffixDependsOnIdentity(t *testing.T) { + a := BuildComposeProject(false, "web", "login", "team1") + assert.Equal(t, a, BuildComposeProject(false, "web", "login", "team1"), "deterministic") + assert.NotEqual(t, a, BuildComposeProject(false, "web", "login", "team2")) + + // Readable parts equal after sanitization: only the hash keeps them apart + assert.NotEqual(t, + BuildComposeProject(false, "web", "Login!", "team1"), + BuildComposeProject(false, "web", "login?", "team1")) + + // The v0.7.1 suffix was always "706f6c" + assert.False(t, strings.HasSuffix(a, "-706f6c"), a) +} + +func TestBuildComposeProject_UniqueAndTeamInstancesDiffer(t *testing.T) { + assert.NotEqual(t, + BuildComposeProject(true, "web", "login", ""), + BuildComposeProject(false, "web", "login", "")) + assert.True(t, strings.HasPrefix(BuildComposeProject(true, "web", "login", ""), "global-web-login-")) +} + +func TestBuildComposeProject_FitsOneDNSLabel(t *testing.T) { + long := strings.Repeat("very-long-challenge-name-", 6) + a := BuildComposeProject(false, "reverse-engineering", long+"a", "team-with-a-long-identifier") + b := BuildComposeProject(false, "reverse-engineering", long+"b", "team-with-a-long-identifier") + + for _, p := range []string{a, b} { + assert.LessOrEqual(t, len(p), 63, p) + assert.Regexp(t, validProject, p) + } + // Truncated to the same readable part, still distinct + assert.NotEqual(t, a, b) +} + +func TestBuildComposeProject_ValidForAnyName(t *testing.T) { + for _, p := range []string{ + BuildComposeProject(false, "Wéb", "Ünïcode Chall", "Team 1"), + BuildComposeProject(false, "", "", ""), + BuildComposeProject(true, "!!!", "???", ""), + } { + assert.Regexp(t, validProject, p) + } + // Nothing readable left after sanitization but the prefix: still unique + assert.Regexp(t, `^global-[0-9a-f]{8}$`, BuildComposeProject(true, "中文", "挑战", "")) + assert.NotEqual(t, BuildComposeProject(true, "中文", "挑战", ""), BuildComposeProject(true, "日本", "語", "")) +} + +func TestLegacyComposeProject_MatchesV071(t *testing.T) { + // What Galvanize v0.7.1 named these instances + assert.Equal(t, "polypwn-login-team1-706f6c", LegacyComposeProject(false, "login", "team1")) + assert.Equal(t, "polypwn-my-chall-team-2-706f6c", LegacyComposeProject(false, "My Chall", "Team 2")) + assert.Equal(t, "global-login", LegacyComposeProject(true, "login", "")) +} + +func TestLegacyComposeProject_DiffersFromNewName(t *testing.T) { + assert.NotEqual(t, LegacyComposeProject(false, "login", "team1"), BuildComposeProject(false, "web", "login", "team1")) + assert.NotEqual(t, LegacyComposeProject(true, "login", ""), BuildComposeProject(true, "web", "login", "")) +} diff --git a/galvanize-instancer/pkg/restserver.go b/galvanize-instancer/pkg/restserver.go index ec814bc..35515c0 100755 --- a/galvanize-instancer/pkg/restserver.go +++ b/galvanize-instancer/pkg/restserver.go @@ -126,6 +126,13 @@ func (s *Server) Wait(ctx context.Context) error { // log.Printf("Metrics synced. Found %.0f active challenge containers.", count) //} +// instanceLockKey identifies a challenge instance for the deploy lock. +// Challenge names are only unique within a category, so the category is part +// of it; teamID is empty for unique (shared) instances. +func instanceLockKey(category, challengeName, teamID string) string { + return category + "/" + challengeName + ":" + teamID +} + func (s *Server) GetHealth(ctx echo.Context) error { return ctx.JSON(200, map[string]string{"status": "ok"}) } @@ -141,8 +148,9 @@ func (s *Server) DeployInstance(ctx echo.Context) error { return ctx.JSON(400, api.Error{Message: utils.Ptr("Invalid request")}) } zap.S().Infof("Deploy request received for challenge %s for team %s", req.ChallengeName, claims.TeamID) - // Check if challenge is valid for team - if req.ChallengeName != claims.ChallengeName && claims.Role != "admin" { + // Check if challenge is valid for team. Challenge names are only unique + // within a category, so the category must match too. + if (req.ChallengeName != claims.ChallengeName || req.Category != claims.Category) && claims.Role != "admin" { zap.S().Errorf("Unauthorized attempt to deploy challenge %s for team %s", req.ChallengeName, claims.TeamID) pkgmetrics.UnauthorizedDeployRequestsTotal.WithLabelValues(claims.TeamID).Inc() return ctx.JSON(403, api.Error{Message: utils.Ptr("Unauthorized")}) @@ -156,7 +164,7 @@ func (s *Server) DeployInstance(ctx echo.Context) error { zap.S().Errorf("Attempt to deploy unique challenge %s for team %s", req.ChallengeName, claims.TeamID) return ctx.JSON(403, api.Error{Message: utils.Ptr("Unauthorized")}) } - id := chall.Name + claims.TeamID + id := instanceLockKey(chall.Category, chall.Name, claims.TeamID) s.kmu.LockKey(id) existingDeployment, err := models.GetDeployment(s.db, chall.Category, chall.Name, claims.TeamID, false) if err == nil && existingDeployment != nil { @@ -345,8 +353,8 @@ func (s *Server) TerminateInstance(ctx echo.Context) error { if err := ctx.Bind(&req); err != nil { return ctx.JSON(400, api.Error{Message: utils.Ptr("Invalid request")}) } - // Check if challenge is valid for team - if req.ChallengeName != claims.ChallengeName && claims.Role != "admin" { + // Check if challenge is valid for team (name and category, see DeployInstance) + if (req.ChallengeName != claims.ChallengeName || req.Category != claims.Category) && claims.Role != "admin" { zap.S().Errorf("Unauthorized attempt to terminate challenge %s for team %s", req.ChallengeName, claims.TeamID) pkgmetrics.UnauthorizedDeployRequestsTotal.WithLabelValues(claims.TeamID).Inc() return ctx.JSON(403, api.Error{Message: utils.Ptr("Unauthorized")}) diff --git a/galvanize-instancer/pkg/restserver_admin.go b/galvanize-instancer/pkg/restserver_admin.go index 9fd871d..8f1e669 100644 --- a/galvanize-instancer/pkg/restserver_admin.go +++ b/galvanize-instancer/pkg/restserver_admin.go @@ -96,7 +96,7 @@ func (s *Server) DeployAdminInstance(ctx echo.Context) error { return ctx.JSON(400, api.Error{Message: utils.Ptr("Challenge is not unique")}) } - id := chall.Name + "_unique" + id := instanceLockKey(chall.Category, chall.Name, "") s.kmu.LockKey(id) existingDeployment, err := models.GetUniqueDeployment(s.db, chall.Category, chall.Name, false) if err == nil && existingDeployment != nil { diff --git a/galvanize-instancer/pkg/restserver_test.go b/galvanize-instancer/pkg/restserver_test.go index 5466c6d..ae66a33 100644 --- a/galvanize-instancer/pkg/restserver_test.go +++ b/galvanize-instancer/pkg/restserver_test.go @@ -279,6 +279,36 @@ func TestDeployInstance_Forbidden_WrongChallenge(t *testing.T) { assert.Equal(t, http.StatusForbidden, rec.Code) } +func TestDeployInstance_Forbidden_WrongCategory(t *testing.T) { + deployer := &mockDeployer{} + srv := newTestServerWithMock(t, deployer, newMockIndexer(httpChallenge())) + + // Same challenge name, but the token is for another category's challenge + claims := &auth.Claims{TeamID: "team1", ChallengeName: "http", Category: "pwn", Role: "user"} + body := `{"challenge_name":"http","category":"web"}` + ctx, rec := echoCtxWithClaimsAndBody(http.MethodPost, "/deploy", claims, body) + + err := srv.DeployInstance(ctx) + require.NoError(t, err) + assert.Equal(t, http.StatusForbidden, rec.Code) + assert.Empty(t, deployer.deployCalls) +} + +func TestDeployInstance_AdminCanDeployOtherCategory(t *testing.T) { + deployer := &mockDeployer{} + srv := newTestServerWithMock(t, deployer, newMockIndexer(httpChallenge())) + + claims := &auth.Claims{TeamID: "team1", ChallengeName: "http", Category: "pwn", Role: "admin"} + body := `{"challenge_name":"http","category":"web"}` + ctx, rec := echoCtxWithClaimsAndBody(http.MethodPost, "/deploy", claims, body) + + err := srv.DeployInstance(ctx) + require.NoError(t, err) + assert.Equal(t, http.StatusAccepted, rec.Code) + waitForBackground(t, srv) + assert.Len(t, deployer.deployCalls, 1) +} + func TestDeployInstance_AdminCanDeployAnychallenge(t *testing.T) { deployer := &mockDeployer{} chall := httpChallenge() @@ -723,6 +753,19 @@ func TestTerminateInstance_Forbidden_WrongChallenge(t *testing.T) { assert.Equal(t, http.StatusForbidden, rec.Code) } +func TestTerminateInstance_Forbidden_WrongCategory(t *testing.T) { + deployer := &mockDeployer{} + srv := newTestServerWithMock(t, deployer, newMockIndexer(httpChallenge())) + + claims := &auth.Claims{TeamID: "team1", ChallengeName: "http", Category: "pwn", Role: "user"} + body := `{"challenge_name":"http","category":"web"}` + ctx, rec := echoCtxWithClaimsAndBody(http.MethodPost, "/terminate", claims, body) + + err := srv.TerminateInstance(ctx) + require.NoError(t, err) + assert.Equal(t, http.StatusForbidden, rec.Code) +} + func TestTerminateInstance_NotFound(t *testing.T) { deployer := &mockDeployer{} srv := newTestServerWithMock(t, deployer, newMockIndexer(httpChallenge())) From f6dfb1c1bc6898f43016065d11578cdecc8d2065 Mon Sep 17 00:00:00 2001 From: CorentinFelten Date: Thu, 1 Oct 2026 17:29:27 -0400 Subject: [PATCH 3/5] fix: skip invalid challenge files instead of failing the whole index BuildIndex returned on the first challenge.yml it could not parse, so one broken file stopped Galvanize from starting (Fatalf in serve) or made every /admin/reload-challs fail. It also panicked instead of returning an error when the challenge directory did not exist, since WalkDir then calls back with a nil DirEntry, and it emptied the index before walking, so a failed reload left no challenges at all. Now: - files that cannot be parsed (a bad compose file included), unreadable directories, and challenges declaring a category/name already indexed are skipped and logged, and the other challenges are indexed; - the index is built aside and swapped in only on success: an unreadable challenge directory returns an error and keeps the current index; - Skipped() lists the files the last build left out; serve warns about them at startup, and /admin/reload-challs returns {"indexed": n, "skipped": [{"path", "reason"}]} (Zync only checks the status, so it is unaffected). --- CHANGELOG.md | 3 + galvanize-instancer/api/openapi.yaml.in | 34 ++++- galvanize-instancer/cmd/serve.go | 3 + .../internal/challenge/challenge.go | 80 +++++++++-- .../internal/challenge/challenge_test.go | 131 ++++++++++++++++-- galvanize-instancer/pkg/api/api.gen.go | 91 +++++++----- galvanize-instancer/pkg/restserver_admin.go | 19 ++- .../pkg/restserver_admin_test.go | 45 +++++- galvanize-instancer/pkg/restserver_test.go | 3 +- 9 files changed, 340 insertions(+), 69 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 832d284..cb4aa76 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,11 +4,14 @@ ### Changed - Docker Compose project names, which also name the subdomains of instances, now include the category and a hash of the instance's identity (e.g. `polypwn-web-login-team1-`). Instances already running when upgrading keep their previous name: terminating them also removes the project under that name, so no containers are left behind +- `/admin/reload-challs` returns `{"indexed": , "skipped": [{"path", "reason"}]}` instead of an empty body ### Fixed - Deployments failing on Docker Compose 2.38+ with `can't set distinct values on 'pids_limit' and 'deploy.resources.limits.pids'`: the PID limit is now set as `deploy.resources.limits.pids`, next to the CPU and memory limits, instead of the service-level `pids_limit`. The `custom_compose` playbook drops a `pids_limit` set in the challenge's own compose file, so Galvanize's limit applies as before - Same-named challenges in different categories no longer collide: the category is now part of the deploy and terminate check against the JWT (a token for `web/login` cannot deploy or terminate `pwn/login`), of the per-instance lock, and of the Docker Compose project name - Compose project names end with a real hash of the instance's identity: the previous suffix was always `706f6c`, since `sha1.New().Sum(name)` appended the hash of nothing to the name instead of hashing it. Names are also cut to fit a 63-character DNS label +- One invalid `challenge.yml` no longer takes every challenge down: it stopped Galvanize from starting, or made `/admin/reload-challs` fail. Files that cannot be parsed (including a bad compose file), unreadable directories and challenges declaring an already indexed `category/name` are now skipped and logged, and the other challenges are indexed +- A missing or unreadable challenge directory makes `BuildIndex` return an error instead of panicking; a failed reload keeps the current index ## v0.7.1 (2026-06-02) diff --git a/galvanize-instancer/api/openapi.yaml.in b/galvanize-instancer/api/openapi.yaml.in index 5fac798..c817ee7 100755 --- a/galvanize-instancer/api/openapi.yaml.in +++ b/galvanize-instancer/api/openapi.yaml.in @@ -263,13 +263,17 @@ paths: /admin/reload-challs: post: summary: Reload challenges index - description: Reload challenges index from disk and update the inmemory index + description: Reload challenges index from disk and update the inmemory index. Challenge files that cannot be parsed, or that duplicate another challenge's category/name, are skipped and listed in the response; the other challenges are indexed. If the challenge directory cannot be read, the current index is kept and 500 is returned. operationId: reloadChallenges security: - bearerAuth: [ ] responses: '200': description: Reload successful + content: + application/json: + schema: + $ref: '#/components/schemas/ReloadChallengesResponse' '401': description: Unauthorized '403': @@ -550,6 +554,34 @@ components: - created_at - updated_at + ReloadChallengesResponse: + type: object + properties: + indexed: + type: integer + description: Number of challenges in the index after the reload. + skipped: + type: array + description: Challenge files left out of the index. + items: + $ref: '#/components/schemas/SkippedChallenge' + required: + - indexed + - skipped + + SkippedChallenge: + type: object + properties: + path: + type: string + description: Path of the challenge file. + reason: + type: string + description: Why it was skipped. + required: + - path + - reason + RetryDeploymentRequest: type: object required: diff --git a/galvanize-instancer/cmd/serve.go b/galvanize-instancer/cmd/serve.go index 2b138a1..5ea7d2f 100755 --- a/galvanize-instancer/cmd/serve.go +++ b/galvanize-instancer/cmd/serve.go @@ -146,6 +146,9 @@ var serveCmd = &cobra.Command{ if err != nil { zap.S().Fatalf("Failed to initialize challenge index: %v", err) } + if skipped := challIdx.Skipped(); len(skipped) > 0 { + zap.S().Warnf("%d challenge file(s) skipped (see the errors above); the other challenges are available", len(skipped)) + } // Seed the challenge index gauge with the initial count. { challs := challIdx.GetAll() diff --git a/galvanize-instancer/internal/challenge/challenge.go b/galvanize-instancer/internal/challenge/challenge.go index 2ed8c74..273da03 100644 --- a/galvanize-instancer/internal/challenge/challenge.go +++ b/galvanize-instancer/internal/challenge/challenge.go @@ -112,14 +112,23 @@ type ChallengeIndexer interface { GetAllUnique() []*Challenge GetAll() []*Challenge BuildIndex(baseDir string) error + // Skipped lists the challenge files the last BuildIndex left out. + Skipped() []SkippedChallenge +} + +// SkippedChallenge is a challenge file left out of the index, and why. +type SkippedChallenge struct { + Path string + Reason string } // Compile-time check that ChallengeIndex implements ChallengeIndexer. var _ ChallengeIndexer = (*ChallengeIndex)(nil) type ChallengeIndex struct { - mu sync.RWMutex - challs map[string]*Challenge + mu sync.RWMutex + challs map[string]*Challenge + skipped []SkippedChallenge } type Challenge struct { @@ -144,32 +153,79 @@ func NewChallengeIndex(baseDir string) (*ChallengeIndex, error) { return idx, nil } +// BuildIndex (re)builds the index from the challenge files under baseDir. +// +// A challenge file that cannot be read or parsed, or that declares the same +// category/name as one already indexed, is skipped and reported (Skipped and +// the logs) instead of failing the whole index: one bad challenge.yml would +// otherwise stop Galvanize from starting, or make every reload fail. +// baseDir itself must be readable; otherwise an error is returned and the +// current index is kept as it is. func (idx *ChallengeIndex) BuildIndex(baseDir string) error { - idx.mu.Lock() - defer idx.mu.Unlock() - idx.challs = make(map[string]*Challenge) + challs := make(map[string]*Challenge) + paths := make(map[string]string) + var skipped []SkippedChallenge + skip := func(path, reason string) { + skipped = append(skipped, SkippedChallenge{Path: path, Reason: reason}) + zap.S().Errorf("Skipping challenge %s: %s", path, reason) + } + err := filepath.WalkDir(baseDir, func(path string, d fs.DirEntry, err error) error { - if d.IsDir() && (d.Name() == ".git" || d.Name() == "node_modules" || d.Name() == "example") { - return filepath.SkipDir + if err != nil { + if path == baseDir { + return err + } + skip(path, err.Error()) + if d != nil && d.IsDir() { + return filepath.SkipDir + } + return nil + } + if d.IsDir() { + if d.Name() == ".git" || d.Name() == "node_modules" || d.Name() == "example" { + return filepath.SkipDir + } + return nil } - if err != nil || d.IsDir() || (d.Name() != "challenge.yml" && d.Name() != "challenge.yaml") { - return err + if d.Name() != "challenge.yml" && d.Name() != "challenge.yaml" { + return nil } // Parse challenge.yml to get category and name chall, err := parseChallenge(path) if err != nil { - return fmt.Errorf("parse %s: %w", path, err) + skip(path, err.Error()) + return filepath.SkipDir } if chall.Type != "zync" { return filepath.SkipDir } key := chall.Category + "/" + chall.Name - idx.challs[key] = chall + if first, ok := paths[key]; ok { + skip(path, fmt.Sprintf("duplicate of %s (both declare %s)", first, key)) + return filepath.SkipDir + } + challs[key] = chall + paths[key] = path zap.S().Infof("Registered challenge: %s", key) return filepath.SkipDir }) - return err + if err != nil { + return fmt.Errorf("index %s: %w", baseDir, err) + } + + idx.mu.Lock() + idx.challs = challs + idx.skipped = skipped + idx.mu.Unlock() + return nil +} + +// Skipped returns the challenge files the last successful BuildIndex left out. +func (idx *ChallengeIndex) Skipped() []SkippedChallenge { + idx.mu.RLock() + defer idx.mu.RUnlock() + return append([]SkippedChallenge(nil), idx.skipped...) } func (idx *ChallengeIndex) Get(category, name string) (*Challenge, error) { diff --git a/galvanize-instancer/internal/challenge/challenge_test.go b/galvanize-instancer/internal/challenge/challenge_test.go index bba072d..1c28b78 100644 --- a/galvanize-instancer/internal/challenge/challenge_test.go +++ b/galvanize-instancer/internal/challenge/challenge_test.go @@ -1,6 +1,7 @@ package challenge import ( + "fmt" "os" "path/filepath" "testing" @@ -152,11 +153,113 @@ deploy_parameters: } func TestBuildIndex_InvalidDir(t *testing.T) { - // WalkDir passes a nil DirEntry when the root path doesn't exist, - // which causes a panic in BuildIndex before the error can be returned. - assert.Panics(t, func() { - _, _ = NewChallengeIndex("/nonexistent/path/that/does/not/exist") - }) + _, err := NewChallengeIndex("/nonexistent/path/that/does/not/exist") + assert.Error(t, err) +} + +const validChall = ` +name: %s +category: %s +playbook_name: http +type: zync +deploy_parameters: + unique: false +` + +func TestBuildIndex_SkipsInvalidFile(t *testing.T) { + dir := t.TempDir() + writeChallenge(t, dir, "web/ok", fmt.Sprintf(validChall, "ok", "web")) + writeChallenge(t, dir, "web/broken", "name: [unterminated\n") + writeChallenge(t, dir, "pwn/ok", fmt.Sprintf(validChall, "ok", "pwn")) + + idx, err := NewChallengeIndex(dir) + require.NoError(t, err) + + assert.Len(t, idx.GetAll(), 2) + _, err = idx.Get("web", "ok") + assert.NoError(t, err) + _, err = idx.Get("pwn", "ok") + assert.NoError(t, err) + + skipped := idx.Skipped() + require.Len(t, skipped, 1) + assert.Equal(t, filepath.Join(dir, "web/broken/challenge.yml"), skipped[0].Path) + assert.NotEmpty(t, skipped[0].Reason) +} + +func TestBuildIndex_SkipsDuplicate(t *testing.T) { + dir := t.TempDir() + writeChallenge(t, dir, "a", fmt.Sprintf(validChall, "login", "web")) + writeChallenge(t, dir, "b", fmt.Sprintf(validChall, "login", "web")) + + idx, err := NewChallengeIndex(dir) + require.NoError(t, err) + + // WalkDir is lexical: a is indexed, b is the duplicate + assert.Len(t, idx.GetAll(), 1) + skipped := idx.Skipped() + require.Len(t, skipped, 1) + assert.Equal(t, filepath.Join(dir, "b/challenge.yml"), skipped[0].Path) + assert.Contains(t, skipped[0].Reason, filepath.Join(dir, "a/challenge.yml")) + assert.Contains(t, skipped[0].Reason, "web/login") +} + +func TestBuildIndex_SameNameDifferentCategories(t *testing.T) { + dir := t.TempDir() + writeChallenge(t, dir, "web", fmt.Sprintf(validChall, "login", "web")) + writeChallenge(t, dir, "pwn", fmt.Sprintf(validChall, "login", "pwn")) + + idx, err := NewChallengeIndex(dir) + require.NoError(t, err) + assert.Len(t, idx.GetAll(), 2) + assert.Empty(t, idx.Skipped()) +} + +func TestBuildIndex_UnreadableSubdirSkipped(t *testing.T) { + if os.Geteuid() == 0 { + t.Skip("root ignores directory permissions") + } + dir := t.TempDir() + writeChallenge(t, dir, "web", fmt.Sprintf(validChall, "ok", "web")) + locked := filepath.Join(dir, "locked") + require.NoError(t, os.MkdirAll(locked, 0o755)) + require.NoError(t, os.Chmod(locked, 0)) + t.Cleanup(func() { _ = os.Chmod(locked, 0o755) }) + + idx, err := NewChallengeIndex(dir) + require.NoError(t, err) + assert.Len(t, idx.GetAll(), 1) + require.Len(t, idx.Skipped(), 1) + assert.Equal(t, locked, idx.Skipped()[0].Path) +} + +func TestBuildIndex_FailedRebuildKeepsIndex(t *testing.T) { + dir := t.TempDir() + writeChallenge(t, dir, "web", fmt.Sprintf(validChall, "ok", "web")) + writeChallenge(t, dir, "broken", "name: [unterminated\n") + + idx, err := NewChallengeIndex(dir) + require.NoError(t, err) + require.Len(t, idx.GetAll(), 1) + + assert.Error(t, idx.BuildIndex("/nonexistent/path/that/does/not/exist")) + assert.Len(t, idx.GetAll(), 1, "the previous index is kept") + assert.Len(t, idx.Skipped(), 1, "and so is its skipped list") +} + +func TestBuildIndex_RebuildClearsSkipped(t *testing.T) { + dir := t.TempDir() + writeChallenge(t, dir, "web", fmt.Sprintf(validChall, "ok", "web")) + writeChallenge(t, dir, "broken", "name: [unterminated\n") + + idx, err := NewChallengeIndex(dir) + require.NoError(t, err) + require.Len(t, idx.Skipped(), 1) + + writeChallenge(t, dir, "broken", fmt.Sprintf(validChall, "fixed", "web")) + require.NoError(t, idx.BuildIndex(dir)) + assert.Len(t, idx.GetAll(), 2) + assert.Empty(t, idx.Skipped()) } func TestGet_ExistingChallenge(t *testing.T) { @@ -373,9 +476,12 @@ deploy_parameters: compose_file: nope.yaml `) - _, err := NewChallengeIndex(dir) - require.Error(t, err) - assert.Contains(t, err.Error(), "compose_file") + // The challenge is skipped, with the reason, instead of failing the index + idx, err := NewChallengeIndex(dir) + require.NoError(t, err) + assert.Empty(t, idx.GetAll()) + require.Len(t, idx.Skipped(), 1) + assert.Contains(t, idx.Skipped()[0].Reason, "compose_file") } func TestLoadComposeDefinition_NoServicesSectionErrors(t *testing.T) { @@ -390,9 +496,12 @@ deploy_parameters: `) writeFile(t, dir, "web", "docker-compose.yml", "version: \"3\"\nnetworks:\n default: {}\n") - _, err := NewChallengeIndex(dir) - require.Error(t, err) - assert.Contains(t, err.Error(), "services") + // The challenge is skipped, with the reason, instead of failing the index + idx, err := NewChallengeIndex(dir) + require.NoError(t, err) + assert.Empty(t, idx.GetAll()) + require.Len(t, idx.Skipped(), 1) + assert.Contains(t, idx.Skipped()[0].Reason, "services") } func TestLoadComposeDefinition_NoComposeFileLeavesHTTPUntouched(t *testing.T) { diff --git a/galvanize-instancer/pkg/api/api.gen.go b/galvanize-instancer/pkg/api/api.gen.go index 1837052..36d16a8 100755 --- a/galvanize-instancer/pkg/api/api.gen.go +++ b/galvanize-instancer/pkg/api/api.gen.go @@ -132,6 +132,15 @@ type ErrorDeploymentInfo struct { // ErrorDeploymentInfoPreviousStatus The status before the deployment transitioned to error. Indicates whether a deploy or terminate action was in progress. type ErrorDeploymentInfoPreviousStatus string +// ReloadChallengesResponse defines model for ReloadChallengesResponse. +type ReloadChallengesResponse struct { + // Indexed Number of challenges in the index after the reload. + Indexed int `json:"indexed"` + + // Skipped Challenge files left out of the index. + Skipped []SkippedChallenge `json:"skipped"` +} + // RetryDeploymentRequest defines model for RetryDeploymentRequest. type RetryDeploymentRequest struct { // Action The action to perform - 'deploy' to retry deployment, 'terminate' to terminate the failed deployment, 'delete' to remove the deployment from the database. If not provided, the action will be inferred from the previous status (deploy or terminate only). @@ -144,6 +153,15 @@ type RetryDeploymentRequest struct { // RetryDeploymentRequestAction The action to perform - 'deploy' to retry deployment, 'terminate' to terminate the failed deployment, 'delete' to remove the deployment from the database. If not provided, the action will be inferred from the previous status (deploy or terminate only). type RetryDeploymentRequestAction string +// SkippedChallenge defines model for SkippedChallenge. +type SkippedChallenge struct { + // Path Path of the challenge file. + Path string `json:"path"` + + // Reason Why it was skipped. + Reason string `json:"reason"` +} + // StatusResponse defines model for StatusResponse. type StatusResponse struct { ConnectionInfo *string `json:"connection_info,omitempty"` @@ -452,41 +470,44 @@ func RegisterHandlersWithBaseURL(router EchoRouter, si ServerInterface, baseURL // Base64 encoded, gzipped, json marshaled Swagger object var swaggerSpec = []string{ - "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", - "//+18jdZDy8AAA==", + "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", } // GetSwagger returns the content of the embedded swagger specification file diff --git a/galvanize-instancer/pkg/restserver_admin.go b/galvanize-instancer/pkg/restserver_admin.go index 8f1e669..02009a1 100644 --- a/galvanize-instancer/pkg/restserver_admin.go +++ b/galvanize-instancer/pkg/restserver_admin.go @@ -28,13 +28,26 @@ func (s *Server) ReloadChallenges(ctx echo.Context) error { conf := s.confProv.GetConfig() if err := s.challIdx.BuildIndex(conf.Instancer.ChallengeDir); err != nil { - zap.S().Errorf("Failed to reload challenges: %v", err) + // BuildIndex keeps the current index when it fails + zap.S().Errorf("Failed to reload challenges, keeping the current index: %v", err) return ctx.JSON(500, api.Error{Message: utils.HTTP500Debug(fmt.Sprintf("Failed to reload challenges: %v", err))}) } updateChallengeIndexMetrics(s.challIdx) - zap.S().Infof("Challenges reloaded successfully") - return ctx.NoContent(200) + + response := api.ReloadChallengesResponse{ + Indexed: len(s.challIdx.GetAll()), + Skipped: make([]api.SkippedChallenge, 0), + } + for _, sk := range s.challIdx.Skipped() { + response.Skipped = append(response.Skipped, api.SkippedChallenge{Path: sk.Path, Reason: sk.Reason}) + } + if len(response.Skipped) > 0 { + zap.S().Warnf("Challenges reloaded: %d indexed, %d skipped (see the errors above)", response.Indexed, len(response.Skipped)) + } else { + zap.S().Infof("Challenges reloaded: %d indexed", response.Indexed) + } + return ctx.JSON(200, response) } func (s *Server) ConfigCheck(ctx echo.Context) error { diff --git a/galvanize-instancer/pkg/restserver_admin_test.go b/galvanize-instancer/pkg/restserver_admin_test.go index a8885ea..145f3f5 100644 --- a/galvanize-instancer/pkg/restserver_admin_test.go +++ b/galvanize-instancer/pkg/restserver_admin_test.go @@ -1,6 +1,7 @@ package pkg import ( + "encoding/json" "net/http" "net/http/httptest" "os" @@ -9,6 +10,7 @@ import ( "github.com/28Pollux28/galvanize/internal/auth" "github.com/28Pollux28/galvanize/internal/challenge" + "github.com/28Pollux28/galvanize/pkg/api" "github.com/28Pollux28/galvanize/pkg/config" "github.com/golang-jwt/jwt/v5" "github.com/labstack/echo/v4" @@ -100,6 +102,7 @@ deploy_parameters: err := srv.ReloadChallenges(ctx) require.NoError(t, err) assert.Equal(t, http.StatusOK, rec.Code) + assert.JSONEq(t, `{"indexed":1,"skipped":[]}`, rec.Body.String()) } func TestReloadChallenges_Unauthorized(t *testing.T) { @@ -162,13 +165,43 @@ deploy_parameters: cfg.Instancer.ChallengeDir = "/nonexistent/path/that/does/not/exist" claims := &auth.Claims{Role: "admin"} - ctx, _ := createEchoContextWithClaims(http.MethodPost, "/admin/reload-challenges", claims) + ctx, rec := createEchoContextWithClaims(http.MethodPost, "/admin/reload-challenges", claims) - // BuildIndex panics on a non-existent root dir because WalkDir passes - // a nil DirEntry when it can't stat the root path. - assert.Panics(t, func() { - _ = srv.ReloadChallenges(ctx) - }) + err := srv.ReloadChallenges(ctx) + require.NoError(t, err) + assert.Equal(t, http.StatusInternalServerError, rec.Code) + + // The index built at startup is kept + _, err = srv.challIdx.Get("web", "http") + assert.NoError(t, err) +} + +func TestReloadChallenges_ReportsSkipped(t *testing.T) { + dir := t.TempDir() + writeChallenge(t, dir, "web", ` +name: http +category: web +playbook_name: http +type: zync +deploy_parameters: + unique: false +`) + srv, _ := newTestServer(t, dir) + writeChallenge(t, dir, "broken", "name: [unterminated\n") + + claims := &auth.Claims{Role: "admin"} + ctx, rec := createEchoContextWithClaims(http.MethodPost, "/admin/reload-challenges", claims) + + err := srv.ReloadChallenges(ctx) + require.NoError(t, err) + assert.Equal(t, http.StatusOK, rec.Code) + + var resp api.ReloadChallengesResponse + require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &resp)) + assert.Equal(t, 1, resp.Indexed) + require.Len(t, resp.Skipped, 1) + assert.Equal(t, filepath.Join(dir, "broken/challenge.yml"), resp.Skipped[0].Path) + assert.NotEmpty(t, resp.Skipped[0].Reason) } func TestReloadChallenges_RefreshesIndex(t *testing.T) { diff --git a/galvanize-instancer/pkg/restserver_test.go b/galvanize-instancer/pkg/restserver_test.go index ae66a33..f61d6f6 100644 --- a/galvanize-instancer/pkg/restserver_test.go +++ b/galvanize-instancer/pkg/restserver_test.go @@ -113,7 +113,8 @@ func (m *mockChallengeIndexer) GetAll() []*challenge.Challenge { return challs } -func (m *mockChallengeIndexer) BuildIndex(_ string) error { return nil } +func (m *mockChallengeIndexer) BuildIndex(_ string) error { return nil } +func (m *mockChallengeIndexer) Skipped() []challenge.SkippedChallenge { return nil } var _ challenge.ChallengeIndexer = (*mockChallengeIndexer)(nil) From c129c6f1a8a1848657eaf3746e4a140f1e02486a Mon Sep 17 00:00:00 2001 From: CorentinFelten Date: Thu, 1 Oct 2026 17:34:11 -0400 Subject: [PATCH 4/5] fix: honor randomized_port_min and randomized_port_max The randomized host port range was read from the config but never used: both allocators, the port bindings store used for deployments and the in-memory one, hard-coded 20000-60999. - InstancerConfig.RandomizedPortRange returns the configured range, each bound defaulting to 20000 and 60999 when unset, and Validate rejects a range outside 1-65535 or with the minimum above the maximum; Load calls it, so startup fails on an invalid range and a reload with one keeps the current config. - Both allocators pick from that range. The store tries 128 random ports, then takes the first port no binding uses, so a nearly full range is still used up. - A deployment that cannot get a host port (no free port left, or the store cannot be opened) now fails with an error naming the range, instead of leaving the container port to an ephemeral host port outside it. --- CHANGELOG.md | 2 + config.example.yaml | 4 +- .../internal/ansible/connection_info_test.go | 9 +- .../internal/ansible/deployer.go | 11 ++- .../internal/ansible/port_bindings_store.go | 91 ++++++++++-------- .../internal/ansible/port_range_test.go | 96 +++++++++++++++++++ .../internal/ansible/published_ports.go | 60 ++++++++---- galvanize-instancer/pkg/config/config.go | 38 +++++++- galvanize-instancer/pkg/config/config_test.go | 56 +++++++++++ 9 files changed, 302 insertions(+), 65 deletions(-) create mode 100644 galvanize-instancer/internal/ansible/port_range_test.go create mode 100644 galvanize-instancer/pkg/config/config_test.go diff --git a/CHANGELOG.md b/CHANGELOG.md index cb4aa76..04ebf1a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,7 @@ ### Changed - Docker Compose project names, which also name the subdomains of instances, now include the category and a hash of the instance's identity (e.g. `polypwn-web-login-team1-`). Instances already running when upgrading keep their previous name: terminating them also removes the project under that name, so no containers are left behind - `/admin/reload-challs` returns `{"indexed": , "skipped": [{"path", "reason"}]}` instead of an empty body +- A deployment that cannot get a randomized host port (no free port left in the range, or the port bindings store cannot be opened) now fails with a clear error, instead of publishing the port on an ephemeral host port outside the range ### Fixed - Deployments failing on Docker Compose 2.38+ with `can't set distinct values on 'pids_limit' and 'deploy.resources.limits.pids'`: the PID limit is now set as `deploy.resources.limits.pids`, next to the CPU and memory limits, instead of the service-level `pids_limit`. The `custom_compose` playbook drops a `pids_limit` set in the challenge's own compose file, so Galvanize's limit applies as before @@ -12,6 +13,7 @@ - Compose project names end with a real hash of the instance's identity: the previous suffix was always `706f6c`, since `sha1.New().Sum(name)` appended the hash of nothing to the name instead of hashing it. Names are also cut to fit a 63-character DNS label - One invalid `challenge.yml` no longer takes every challenge down: it stopped Galvanize from starting, or made `/admin/reload-challs` fail. Files that cannot be parsed (including a bad compose file), unreadable directories and challenges declaring an already indexed `category/name` are now skipped and logged, and the other challenges are indexed - A missing or unreadable challenge directory makes `BuildIndex` return an error instead of panicking; a failed reload keeps the current index +- `randomized_port_min` and `randomized_port_max` are now honored: randomized host ports were always picked from 20000-60999. Each bound still defaults (20000 and 60999) when unset; an invalid range (outside 1-65535, or a minimum above the maximum) fails startup, and a config reload with one keeps the current config. When random picks keep colliding, a free port of the range is taken in order, so a nearly full range is still used up ## v0.7.1 (2026-06-02) diff --git a/config.example.yaml b/config.example.yaml index 325d57e..dbfa0b0 100755 --- a/config.example.yaml +++ b/config.example.yaml @@ -11,8 +11,8 @@ instancer: deployment_extension_window: "30m" # Time window to extend deployments before expiration (default: 30m) deployment_max_extensions: 3 # Maximum number of extensions allowed per deployment (-1 for unlimited) (default: 3) randomize_published_ports: false # TCP only: randomize host ports for non-fixed published_ports (e.g., "22" -> "34721:22") - randomized_port_min: 20000 # Lower bound for randomized host ports (default: 20000) - randomized_port_max: 60999 # Upper bound for randomized host ports (default: 60999) + randomized_port_min: 20000 # Lower bound for randomized host ports, included (default: 20000) + randomized_port_max: 60999 # Upper bound for randomized host ports, included (default: 60999) num_workers: 10 # Number of Ansible workers for processing jobs (default: 10) max_concurrent_ansible: 5 # Fallback: max concurrent Ansible when Redis not configured (default: 5) metrics: diff --git a/galvanize-instancer/internal/ansible/connection_info_test.go b/galvanize-instancer/internal/ansible/connection_info_test.go index 224ac18..793fef2 100644 --- a/galvanize-instancer/internal/ansible/connection_info_test.go +++ b/galvanize-instancer/internal/ansible/connection_info_test.go @@ -5,6 +5,7 @@ import ( "strings" "testing" + "github.com/28Pollux28/galvanize/pkg/config" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -20,7 +21,7 @@ func TestNormalizePublishedPorts_ExtractsOptionalProtocolHints(t *testing.T) { }, } - normalized, hints, bindings := normalizePublishedPortsWithState(params, false, nil, false) + normalized, hints, bindings := normalizePublishedPortsWithState(params, false, nil, false, defaultPortRange) assert.Equal(t, "example:latest", normalized["image"]) assert.Empty(t, bindings) @@ -76,7 +77,7 @@ func TestNormalizePublishedPorts_RandomizeHostPorts_WhenEnabled(t *testing.T) { }, } - normalized, hints, bindings := normalizePublishedPortsWithState(params, true, nil, true) + normalized, hints, bindings := normalizePublishedPortsWithState(params, true, nil, true, defaultPortRange) ports, ok := normalized["published_ports"].([]interface{}) require.True(t, ok) require.Len(t, ports, 4) @@ -102,6 +103,8 @@ func TestNormalizePublishedPorts_RandomizeHostPorts_WhenEnabled(t *testing.T) { assert.NotEmpty(t, bindings) } +var defaultPortRange = portRange{lo: config.DefaultRandomizedPortMin, hi: config.DefaultRandomizedPortMax} + func isRandomBindingFor(portDef string, target string) bool { parts := strings.Split(portDef, ":") if len(parts) != 2 { @@ -114,5 +117,5 @@ func isRandomBindingFor(portDef string, target string) bool { if err != nil { return false } - return hostPort >= 20000 && hostPort <= 60999 + return defaultPortRange.contains(hostPort) } diff --git a/galvanize-instancer/internal/ansible/deployer.go b/galvanize-instancer/internal/ansible/deployer.go index f6f5305..0ebd7cd 100644 --- a/galvanize-instancer/internal/ansible/deployer.go +++ b/galvanize-instancer/internal/ansible/deployer.go @@ -42,14 +42,19 @@ func (a *AnsibleDeployer) Deploy(ctx context.Context, conf *config.Config, chall var lastErr error key := deploymentKey(chall, teamID) randomizePorts := conf.Instancer.RandomizePublishedPorts + ports := randomizedPortRange(conf) for attempt := 1; attempt <= maxRetries; attempt++ { existingBindings := loadPortBindingsFromDB(conf.Instancer.DBPath, key) if randomizePorts { randomizable := randomizableContainerPorts(chall.DeployParameters) randomizable = append(randomizable, exposeTCPContainerPorts(chall.DeployParameters)...) - existingBindings = ensureRandomPortBindingsInDB(conf.Instancer.DBPath, key, randomizable) + reserved, err := ensureRandomPortBindingsInDB(conf.Instancer.DBPath, key, randomizable, ports) + if err != nil { + return "", fmt.Errorf("failed to reserve host ports: %w", err) + } + existingBindings = reserved } - normalizedParams, protocolHints, _ := normalizePublishedPortsWithState(chall.DeployParameters, randomizePorts, existingBindings, false) + normalizedParams, protocolHints, _ := normalizePublishedPortsWithState(chall.DeployParameters, randomizePorts, existingBindings, false, ports) if randomizePorts { savePortBindingsToDB(conf.Instancer.DBPath, key, existingBindings) } @@ -105,7 +110,7 @@ func (a *AnsibleDeployer) Terminate(ctx context.Context, conf *config.Config, ch randomizePorts := conf.Instancer.RandomizePublishedPorts for attempt := 1; attempt <= maxRetries; attempt++ { existingBindings := loadPortBindingsFromDB(conf.Instancer.DBPath, key) - normalizedParams, _, _ := normalizePublishedPortsWithState(chall.DeployParameters, randomizePorts, existingBindings, false) + normalizedParams, _, _ := normalizePublishedPortsWithState(chall.DeployParameters, randomizePorts, existingBindings, false, randomizedPortRange(conf)) if _, err := applyComposeExposures(conf, chall, teamID, normalizedParams, existingBindings); err != nil { return fmt.Errorf("failed to apply compose exposures: %w", err) } diff --git a/galvanize-instancer/internal/ansible/port_bindings_store.go b/galvanize-instancer/internal/ansible/port_bindings_store.go index cd2c99f..6c32bfb 100644 --- a/galvanize-instancer/internal/ansible/port_bindings_store.go +++ b/galvanize-instancer/internal/ansible/port_bindings_store.go @@ -1,6 +1,7 @@ package ansible import ( + "fmt" "sync" "time" @@ -48,9 +49,14 @@ func loadPortBindingsFromDB(dbPath, deploymentKey string) map[string]int { return bindings } -func ensureRandomPortBindingsInDB(dbPath, deploymentKey string, containerPorts []string) map[string]int { +// ensureRandomPortBindingsInDB returns the host ports of the deployment's +// randomized container ports, reserving a free one of ports for each container +// port that has none yet. It fails when the store cannot be opened or ports +// has no free port left, rather than leaving the container port to an +// ephemeral host port outside the configured range. +func ensureRandomPortBindingsInDB(dbPath, deploymentKey string, containerPorts []string, ports portRange) (map[string]int, error) { if dbPath == "" || deploymentKey == "" || len(containerPorts) == 0 { - return map[string]int{} + return map[string]int{}, nil } portBindingDBMu.Lock() @@ -58,7 +64,7 @@ func ensureRandomPortBindingsInDB(dbPath, deploymentKey string, containerPorts [ db, err := openPortBindingDB(dbPath) if err != nil { - return map[string]int{} + return nil, fmt.Errorf("open port bindings store: %w", err) } result := map[string]int{} @@ -74,16 +80,20 @@ func ensureRandomPortBindingsInDB(dbPath, deploymentKey string, containerPorts [ continue } - hostPort := reserveRandomHostPort(db, deploymentKey, containerPort) - if hostPort > 0 { - result[containerPort] = hostPort + hostPort := reserveRandomHostPort(db, deploymentKey, containerPort, ports) + if hostPort == 0 { + return nil, fmt.Errorf("no free host port left in the randomized port range %s for container port %s", ports, containerPort) } + result[containerPort] = hostPort } - return result + return result, nil } -func reserveRandomHostPort(db *gorm.DB, deploymentKey, containerPort string) int { +// reserveRandomHostPort records a host port of ports for the container port +// and returns it, or 0 if none is free. Ports are tried at random, then in +// order, so a nearly full range is still used up. +func reserveRandomHostPort(db *gorm.DB, deploymentKey, containerPort string, ports portRange) int { if db == nil || deploymentKey == "" || containerPort == "" { return 0 } @@ -95,49 +105,54 @@ func reserveRandomHostPort(db *gorm.DB, deploymentKey, containerPort string) int } for range 128 { - hostPort := randomHostPortFromDB(db) - if hostPort == 0 { - continue - } - record := portBindingRecord{ - DeploymentKey: deploymentKey, - ContainerPort: containerPort, - HostPort: hostPort, + if hostPort := tryReserveHostPort(db, deploymentKey, containerPort, ports.random()); hostPort != 0 { + return hostPort } - res := db.Clauses(clause.OnConflict{DoNothing: true}).Create(&record) - if res.Error != nil { + } + + // Random picks kept colliding: take the first port no binding uses + var used []int + if err := db.Model(&portBindingRecord{}).Where("host_port BETWEEN ? AND ?", ports.lo, ports.hi).Pluck("host_port", &used).Error; err != nil { + return 0 + } + taken := make(map[int]struct{}, len(used)) + for _, p := range used { + taken[p] = struct{}{} + } + for port := ports.lo; port <= ports.hi; port++ { + if _, ok := taken[port]; ok { continue } - if res.RowsAffected == 1 { + if hostPort := tryReserveHostPort(db, deploymentKey, containerPort, port); hostPort != 0 { return hostPort } - - // If insert was ignored, check whether our target mapping now exists. - var mapped portBindingRecord - if err := db.First(&mapped, "deployment_key = ? AND container_port = ?", deploymentKey, containerPort).Error; err == nil { - return mapped.HostPort - } } - return 0 } -func randomHostPortFromDB(db *gorm.DB) int { - if db == nil { +// tryReserveHostPort records hostPort for the container port unless another +// binding uses it. It returns the container port's host port, which another +// worker may have recorded meanwhile, or 0. +func tryReserveHostPort(db *gorm.DB, deploymentKey, containerPort string, hostPort int) int { + if hostPort == 0 { return 0 } - const minPort = 20000 - const maxPort = 60999 - const rangeSize = maxPort - minPort + 1 - - var hostPort int - if err := db.Raw("SELECT CAST((ABS(RANDOM()) % ?) + ? AS INTEGER)", rangeSize, minPort).Scan(&hostPort).Error; err != nil { - return 0 + record := portBindingRecord{ + DeploymentKey: deploymentKey, + ContainerPort: containerPort, + HostPort: hostPort, } - if hostPort < minPort || hostPort > maxPort { - return 0 + res := db.Clauses(clause.OnConflict{DoNothing: true}).Create(&record) + if res.Error == nil && res.RowsAffected == 1 { + return hostPort } - return hostPort + + // If insert was ignored, check whether our target mapping now exists. + var mapped portBindingRecord + if err := db.First(&mapped, "deployment_key = ? AND container_port = ?", deploymentKey, containerPort).Error; err == nil { + return mapped.HostPort + } + return 0 } func savePortBindingsToDB(dbPath, deploymentKey string, bindings map[string]int) { diff --git a/galvanize-instancer/internal/ansible/port_range_test.go b/galvanize-instancer/internal/ansible/port_range_test.go new file mode 100644 index 0000000..0215e0b --- /dev/null +++ b/galvanize-instancer/internal/ansible/port_range_test.go @@ -0,0 +1,96 @@ +package ansible + +import ( + "fmt" + "path/filepath" + "strconv" + "strings" + "testing" + + "github.com/28Pollux28/galvanize/pkg/config" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestRandomizedPortRange_FromConfig(t *testing.T) { + conf := &config.Config{} + assert.Equal(t, portRange{lo: 20000, hi: 60999}, randomizedPortRange(conf), "defaults") + + conf.Instancer.RandomizedPortMin = 30000 + conf.Instancer.RandomizedPortMax = 30009 + assert.Equal(t, portRange{lo: 30000, hi: 30009}, randomizedPortRange(conf)) +} + +func TestPortRange_Random(t *testing.T) { + r := portRange{lo: 30000, hi: 30002} + seen := map[int]bool{} + for range 300 { + p := r.random() + require.True(t, r.contains(p), p) + seen[p] = true + } + assert.Len(t, seen, 3, "every port of the range is picked") + + assert.Equal(t, 40000, portRange{lo: 40000, hi: 40000}.random()) + assert.Zero(t, portRange{lo: 2, hi: 1}.random(), "empty range") +} + +func TestNormalizePublishedPorts_UsesConfiguredRange(t *testing.T) { + params := map[string]interface{}{"published_ports": []interface{}{"22", "53/udp", 443}} + r := portRange{lo: 31000, hi: 31002} + + normalized, _, bindings := normalizePublishedPortsWithState(params, true, nil, true, r) + require.Len(t, bindings, 3) + used := map[int]bool{} + for _, def := range normalized["published_ports"].([]interface{}) { + host, err := strconv.Atoi(strings.SplitN(def.(string), ":", 2)[0]) + require.NoError(t, err) + assert.True(t, r.contains(host), def) + used[host] = true + } + assert.Len(t, used, 3, "distinct host ports") +} + +func TestEnsureRandomPortBindingsInDB_UsesConfiguredRange(t *testing.T) { + dbPath := filepath.Join(t.TempDir(), "galvanize.db") + r := portRange{lo: 32000, hi: 32004} + + bindings, err := ensureRandomPortBindingsInDB(dbPath, "web/a:team1", []string{"22", "80"}, r) + require.NoError(t, err) + require.Len(t, bindings, 2) + for _, p := range bindings { + assert.True(t, r.contains(p), p) + } + assert.NotEqual(t, bindings["22"], bindings["80"]) + + // Asking again returns the same reservation + again, err := ensureRandomPortBindingsInDB(dbPath, "web/a:team1", []string{"22", "80"}, r) + require.NoError(t, err) + assert.Equal(t, bindings, again) +} + +func TestEnsureRandomPortBindingsInDB_FillsRangeThenFails(t *testing.T) { + dbPath := filepath.Join(t.TempDir(), "galvanize.db") + r := portRange{lo: 33000, hi: 33004} + + // Five deployments use up the five ports, the later ones through the + // in-order fallback once random picks keep colliding + used := map[int]bool{} + for i := range 5 { + b, err := ensureRandomPortBindingsInDB(dbPath, fmt.Sprintf("web/a:team%d", i), []string{"22"}, r) + require.NoError(t, err) + require.True(t, r.contains(b["22"]), b["22"]) + used[b["22"]] = true + } + assert.Len(t, used, 5) + + _, err := ensureRandomPortBindingsInDB(dbPath, "web/a:team5", []string{"22"}, r) + require.Error(t, err) + assert.Contains(t, err.Error(), "33000-33004") + + // Freeing a deployment's bindings makes its port available again + clearPortBindingsFromDB(dbPath, "web/a:team0") + b, err := ensureRandomPortBindingsInDB(dbPath, "web/a:team5", []string{"22"}, r) + require.NoError(t, err) + assert.True(t, r.contains(b["22"])) +} diff --git a/galvanize-instancer/internal/ansible/published_ports.go b/galvanize-instancer/internal/ansible/published_ports.go index abb8c30..b6a8dc7 100644 --- a/galvanize-instancer/internal/ansible/published_ports.go +++ b/galvanize-instancer/internal/ansible/published_ports.go @@ -2,9 +2,12 @@ package ansible import ( "crypto/rand" + "fmt" "math/big" "strconv" "strings" + + "github.com/28Pollux28/galvanize/pkg/config" ) var knownDockerProtocols = map[string]struct{}{ @@ -46,7 +49,7 @@ func randomizableContainerPorts(params map[string]interface{}) []string { // // existingBindings and resulting bindings use container port specs as keys, // for example "22", "53/udp", "8080:80". -func normalizePublishedPortsWithState(params map[string]interface{}, randomizePorts bool, existingBindings map[string]int, createState bool) (map[string]interface{}, map[int]string, map[string]int) { +func normalizePublishedPortsWithState(params map[string]interface{}, randomizePorts bool, existingBindings map[string]int, createState bool, portRng portRange) (map[string]interface{}, map[int]string, map[string]int) { normalized := make(map[string]interface{}, len(params)) for k, v := range params { normalized[k] = v @@ -78,27 +81,27 @@ func normalizePublishedPortsWithState(params map[string]interface{}, randomizePo switch v := p.(type) { case int: if randomizePorts { - normalizedPorts = append(normalizedPorts, withPersistentRandomBinding(strconv.Itoa(v), deploymentBindings, usedHostPorts, createState, &stateDirty)) + normalizedPorts = append(normalizedPorts, withPersistentRandomBinding(strconv.Itoa(v), deploymentBindings, usedHostPorts, createState, &stateDirty, portRng)) } else { normalizedPorts = append(normalizedPorts, v) } case int64: if randomizePorts { - normalizedPorts = append(normalizedPorts, withPersistentRandomBinding(strconv.FormatInt(v, 10), deploymentBindings, usedHostPorts, createState, &stateDirty)) + normalizedPorts = append(normalizedPorts, withPersistentRandomBinding(strconv.FormatInt(v, 10), deploymentBindings, usedHostPorts, createState, &stateDirty, portRng)) } else { normalizedPorts = append(normalizedPorts, v) } case float64: intPort := int(v) if randomizePorts { - normalizedPorts = append(normalizedPorts, withPersistentRandomBinding(strconv.Itoa(intPort), deploymentBindings, usedHostPorts, createState, &stateDirty)) + normalizedPorts = append(normalizedPorts, withPersistentRandomBinding(strconv.Itoa(intPort), deploymentBindings, usedHostPorts, createState, &stateDirty, portRng)) } else { normalizedPorts = append(normalizedPorts, intPort) } case string: composePort, targetPort, hint := splitPortHint(v) if randomizePorts && !hasExplicitHostPortMapping(composePort) { - composePort = withPersistentRandomBinding(composePort, deploymentBindings, usedHostPorts, createState, &stateDirty) + composePort = withPersistentRandomBinding(composePort, deploymentBindings, usedHostPorts, createState, &stateDirty, portRng) } normalizedPorts = append(normalizedPorts, composePort) if targetPort > 0 && hint != "" { @@ -169,9 +172,12 @@ func hasExplicitHostPortMapping(portDef string) bool { return strings.Contains(portDef, ":") } -func randomPortBinding(containerPort string, usedHostPorts map[int]struct{}) string { +func randomPortBinding(containerPort string, usedHostPorts map[int]struct{}, portRng portRange) string { for range 128 { - hostPort := randomHighPort() + hostPort := portRng.random() + if hostPort == 0 { + continue + } if _, used := usedHostPorts[hostPort]; used { continue } @@ -180,7 +186,7 @@ func randomPortBinding(containerPort string, usedHostPorts map[int]struct{}) str } // Extremely unlikely fallback if random generation keeps colliding. - for port := 20000; port <= 60999; port++ { + for port := portRng.lo; port <= portRng.hi; port++ { if _, used := usedHostPorts[port]; used { continue } @@ -192,7 +198,7 @@ func randomPortBinding(containerPort string, usedHostPorts map[int]struct{}) str return containerPort } -func withPersistentRandomBinding(containerPort string, deploymentBindings map[string]int, usedHostPorts map[int]struct{}, createState bool, stateDirty *bool) string { +func withPersistentRandomBinding(containerPort string, deploymentBindings map[string]int, usedHostPorts map[int]struct{}, createState bool, stateDirty *bool, portRng portRange) string { if deploymentBindings != nil { if existingHostPort, ok := deploymentBindings[containerPort]; ok { usedHostPorts[existingHostPort] = struct{}{} @@ -202,7 +208,7 @@ func withPersistentRandomBinding(containerPort string, deploymentBindings map[st if !createState { return containerPort } - binding := randomPortBinding(containerPort, usedHostPorts) + binding := randomPortBinding(containerPort, usedHostPorts, portRng) parts := strings.Split(binding, ":") if len(parts) == 2 && deploymentBindings != nil { hostPort, err := strconv.Atoi(parts[0]) @@ -214,14 +220,34 @@ func withPersistentRandomBinding(containerPort string, deploymentBindings map[st return binding } -func randomHighPort() int { - const minPort = 20000 - const maxPort = 60999 - const rangeSize = maxPort - minPort + 1 +// portRange is the range, bounds included, randomized host ports are +// picked from (instancer.randomized_port_min and randomized_port_max). +type portRange struct { + lo, hi int +} - v, err := rand.Int(rand.Reader, big.NewInt(rangeSize)) +func randomizedPortRange(conf *config.Config) portRange { + lo, hi := conf.Instancer.RandomizedPortRange() + return portRange{lo: lo, hi: hi} +} + +func (r portRange) contains(port int) bool { + return port >= r.lo && port <= r.hi +} + +func (r portRange) String() string { + return fmt.Sprintf("%d-%d", r.lo, r.hi) +} + +// random returns a port of the range picked at random, or 0 if the range is +// empty or the system's random source fails. +func (r portRange) random() int { + if r.lo > r.hi { + return 0 + } + v, err := rand.Int(rand.Reader, big.NewInt(int64(r.hi-r.lo+1))) if err != nil { - return minPort + return 0 } - return int(v.Int64()) + minPort + return int(v.Int64()) + r.lo } diff --git a/galvanize-instancer/pkg/config/config.go b/galvanize-instancer/pkg/config/config.go index 847d009..fe92f29 100755 --- a/galvanize-instancer/pkg/config/config.go +++ b/galvanize-instancer/pkg/config/config.go @@ -1,6 +1,7 @@ package config import ( + "fmt" "sync" "time" @@ -52,8 +53,8 @@ type InstancerConfig struct { DeploymentMaxExtensions int `mapstructure:"deployment_max_extensions,omitempty"` // Maximum number of TTL extensions allowed DeploymentExtensionWindow time.Duration `mapstructure:"deployment_extension_window,omitempty"` // Time window before expiration when extension is allowed RandomizePublishedPorts bool `mapstructure:"randomize_published_ports,omitempty"` // Randomize host ports for non-fixed TCP published_ports - RandomizedPortMin int `mapstructure:"randomized_port_min,omitempty"` // Lower bound for randomized host ports (default: 20000) - RandomizedPortMax int `mapstructure:"randomized_port_max,omitempty"` // Upper bound for randomized host ports (default: 60999) + RandomizedPortMin int `mapstructure:"randomized_port_min,omitempty"` // Lower bound for randomized host ports, included (default: 20000) + RandomizedPortMax int `mapstructure:"randomized_port_max,omitempty"` // Upper bound for randomized host ports, included (default: 60999) MaxConcurrentAnsible int `mapstructure:"max_concurrent_ansible,omitempty"` // Maximum concurrent Ansible executions (default: 5) - deprecated, use NumWorkers Redis RedisConfig `mapstructure:"redis"` // Redis configuration for job queue NumWorkers int `mapstructure:"num_workers,omitempty"` // Number of Ansible workers (default: 10) @@ -97,6 +98,36 @@ func MergeResourceLimits(defaults, overrides ResourceLimits) ResourceLimits { return result } +// Default range of randomized host ports, bounds included +const ( + DefaultRandomizedPortMin = 20000 + DefaultRandomizedPortMax = 60999 +) + +// RandomizedPortRange returns the range, bounds included, randomized host +// ports are picked from: randomized_port_min and randomized_port_max, each +// replaced by its default when unset. +func (ic InstancerConfig) RandomizedPortRange() (lo, hi int) { + lo, hi = ic.RandomizedPortMin, ic.RandomizedPortMax + if lo == 0 { + lo = DefaultRandomizedPortMin + } + if hi == 0 { + hi = DefaultRandomizedPortMax + } + return lo, hi +} + +// Validate checks the instancer settings that have no safe fallback. +func (ic InstancerConfig) Validate() error { + lo, hi := ic.RandomizedPortRange() + if lo < 1 || hi > 65535 || lo > hi { + return fmt.Errorf("invalid randomized port range %d-%d: randomized_port_min and randomized_port_max must be between 1 and 65535, the minimum not above the maximum (defaults: %d-%d)", + lo, hi, DefaultRandomizedPortMin, DefaultRandomizedPortMax) + } + return nil +} + var ( current *Config mu sync.RWMutex @@ -111,6 +142,9 @@ func Load() error { if err := viper.Unmarshal(cfg); err != nil { return err } + if err := cfg.Instancer.Validate(); err != nil { + return fmt.Errorf("instancer: %w", err) + } zap.S().Info("Config loaded successfully") current = cfg return nil diff --git a/galvanize-instancer/pkg/config/config_test.go b/galvanize-instancer/pkg/config/config_test.go new file mode 100644 index 0000000..9d80eb4 --- /dev/null +++ b/galvanize-instancer/pkg/config/config_test.go @@ -0,0 +1,56 @@ +package config + +import ( + "testing" + + "github.com/spf13/viper" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestRandomizedPortRange_Defaults(t *testing.T) { + lo, hi := InstancerConfig{}.RandomizedPortRange() + assert.Equal(t, 20000, lo) + assert.Equal(t, 60999, hi) + + lo, hi = InstancerConfig{RandomizedPortMin: 30000}.RandomizedPortRange() + assert.Equal(t, 30000, lo) + assert.Equal(t, 60999, hi, "each bound defaults on its own") + + lo, hi = InstancerConfig{RandomizedPortMax: 25000}.RandomizedPortRange() + assert.Equal(t, 20000, lo) + assert.Equal(t, 25000, hi) +} + +func TestInstancerConfig_Validate(t *testing.T) { + for _, ok := range []InstancerConfig{ + {}, + {RandomizedPortMin: 30000, RandomizedPortMax: 30000}, + {RandomizedPortMin: 1, RandomizedPortMax: 65535}, + } { + assert.NoError(t, ok.Validate(), "%+v", ok) + } + for _, bad := range []InstancerConfig{ + {RandomizedPortMin: 40000, RandomizedPortMax: 30000}, + {RandomizedPortMin: 61000}, // above the default maximum + {RandomizedPortMax: 70000}, + {RandomizedPortMin: -1}, + } { + assert.Error(t, bad.Validate(), "%+v", bad) + } +} + +func TestLoad_RejectsInvalidPortRange(t *testing.T) { + t.Cleanup(viper.Reset) + viper.Reset() + viper.Set("instancer.randomized_port_min", 30000) + viper.Set("instancer.randomized_port_max", 30009) + require.NoError(t, Load()) + require.Equal(t, 30000, Get().Instancer.RandomizedPortMin) + + viper.Set("instancer.randomized_port_min", 40000) + err := Load() + require.Error(t, err) + assert.Contains(t, err.Error(), "randomized port range 40000-30009") + assert.Equal(t, 30000, Get().Instancer.RandomizedPortMin, "the current config is kept") +} From 8ceae36ba9d194f49201bfd9134cd30707b351ba Mon Sep 17 00:00:00 2001 From: CorentinFelten Date: Thu, 1 Oct 2026 17:35:17 -0400 Subject: [PATCH 5/5] fix: query expires_at in GetExpiredDeployments GetExpiredDeployments filtered on expired_at, a column that does not exist (the field is ExpiresAt, stored as expires_at), so any call failed with "no such column". Nothing calls it yet, which is why it went unnoticed. The expiry scheduler ran its own, correct, copy of the query. Both now use models.GetDeploymentsExpiringBy(db, t): running team deployments expiring at t or earlier, soonest first. GetExpiredDeployments is that query at time.Now(), and so, like the scheduler, it now leaves out unique deployments, which have no team and never expire. --- CHANGELOG.md | 1 + galvanize-instancer/pkg/models/deployment.go | 15 ++++- .../pkg/models/deployment_test.go | 66 +++++++++++++++++++ .../pkg/scheduler/scheduler.go | 7 +- 4 files changed, 81 insertions(+), 8 deletions(-) create mode 100644 galvanize-instancer/pkg/models/deployment_test.go diff --git a/CHANGELOG.md b/CHANGELOG.md index 04ebf1a..a126205 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,6 +14,7 @@ - One invalid `challenge.yml` no longer takes every challenge down: it stopped Galvanize from starting, or made `/admin/reload-challs` fail. Files that cannot be parsed (including a bad compose file), unreadable directories and challenges declaring an already indexed `category/name` are now skipped and logged, and the other challenges are indexed - A missing or unreadable challenge directory makes `BuildIndex` return an error instead of panicking; a failed reload keeps the current index - `randomized_port_min` and `randomized_port_max` are now honored: randomized host ports were always picked from 20000-60999. Each bound still defaults (20000 and 60999) when unset; an invalid range (outside 1-65535, or a minimum above the maximum) fails startup, and a config reload with one keeps the current config. When random picks keep colliding, a free port of the range is taken in order, so a nearly full range is still used up +- `models.GetExpiredDeployments` queried a column that does not exist (`expired_at` instead of `expires_at`), so it always failed. It now shares `models.GetDeploymentsExpiringBy` with the expiry scheduler, and like it leaves out unique deployments, which never expire ## v0.7.1 (2026-06-02) diff --git a/galvanize-instancer/pkg/models/deployment.go b/galvanize-instancer/pkg/models/deployment.go index 00e76e4..1e91883 100755 --- a/galvanize-instancer/pkg/models/deployment.go +++ b/galvanize-instancer/pkg/models/deployment.go @@ -47,12 +47,23 @@ func (deployment *Deployment) BeforeDelete(tx *gorm.DB) (err error) { return tx.Error } -func GetExpiredDeployments(db *gorm.DB) ([]Deployment, error) { +// GetDeploymentsExpiringBy returns the running team deployments that expire +// at t or earlier, the soonest first. Unique (shared) deployments have no +// team and are never expired, so they are left out. +func GetDeploymentsExpiringBy(db *gorm.DB, t time.Time) ([]Deployment, error) { var deployments []Deployment - result := db.Where("status = ? AND expired_at <= ?", DeploymentStatusRunning, time.Now()).Find(&deployments) + result := db.Where("status = ? AND expires_at IS NOT NULL AND expires_at <= ? AND team_id IS NOT NULL", + DeploymentStatusRunning, t). + Order("expires_at ASC"). + Find(&deployments) return deployments, result.Error } +// GetExpiredDeployments returns the running team deployments already expired. +func GetExpiredDeployments(db *gorm.DB) ([]Deployment, error) { + return GetDeploymentsExpiringBy(db, time.Now()) +} + func GetDeployment(db *gorm.DB, category, challengeName, teamID string, lock bool) (*Deployment, error) { var deployment Deployment var result *gorm.DB diff --git a/galvanize-instancer/pkg/models/deployment_test.go b/galvanize-instancer/pkg/models/deployment_test.go new file mode 100644 index 0000000..dcf9f85 --- /dev/null +++ b/galvanize-instancer/pkg/models/deployment_test.go @@ -0,0 +1,66 @@ +package models + +import ( + "testing" + "time" + + "github.com/28Pollux28/galvanize/pkg/utils" + "github.com/glebarez/sqlite" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "gorm.io/gorm" +) + +func newTestDB(t *testing.T) *gorm.DB { + t.Helper() + db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{}) + require.NoError(t, err) + require.NoError(t, db.AutoMigrate(Deployment{})) + return db +} + +// addDeployment stores a team deployment (a unique one when teamID is empty) +// with the given status, expiring at expiresAt (none when nil). +func addDeployment(t *testing.T, db *gorm.DB, name, teamID, status string, expiresAt *time.Time) { + t.Helper() + d := &Deployment{ChallengeName: name, Category: "web", Status: status, ExpiresAt: expiresAt} + if teamID != "" { + d.TeamID = &teamID + } + require.NoError(t, db.Create(d).Error) +} + +func names(deployments []Deployment) []string { + out := make([]string, 0, len(deployments)) + for _, d := range deployments { + out = append(out, d.ChallengeName) + } + return out +} + +func TestGetExpiredDeployments(t *testing.T) { + db := newTestDB(t) + now := time.Now() + addDeployment(t, db, "expired-later", "team1", DeploymentStatusRunning, utils.Ptr(now.Add(-time.Minute))) + addDeployment(t, db, "expired-first", "team2", DeploymentStatusRunning, utils.Ptr(now.Add(-time.Hour))) + addDeployment(t, db, "not-yet", "team3", DeploymentStatusRunning, utils.Ptr(now.Add(time.Hour))) + addDeployment(t, db, "starting", "team4", DeploymentStatusStarting, utils.Ptr(now.Add(-time.Hour))) + addDeployment(t, db, "no-expiry", "team5", DeploymentStatusRunning, nil) + addDeployment(t, db, "unique", "", DeploymentStatusRunning, utils.Ptr(now.Add(-time.Hour))) + + expired, err := GetExpiredDeployments(db) + require.NoError(t, err) + assert.Equal(t, []string{"expired-first", "expired-later"}, names(expired), "running team deployments past expiry, soonest first") +} + +func TestGetDeploymentsExpiringBy(t *testing.T) { + db := newTestDB(t) + now := time.Now() + addDeployment(t, db, "in-1m", "team1", DeploymentStatusRunning, utils.Ptr(now.Add(time.Minute))) + addDeployment(t, db, "in-1h", "team2", DeploymentStatusRunning, utils.Ptr(now.Add(time.Hour))) + addDeployment(t, db, "past", "team3", DeploymentStatusRunning, utils.Ptr(now.Add(-time.Minute))) + + upcoming, err := GetDeploymentsExpiringBy(db, now.Add(10*time.Minute)) + require.NoError(t, err) + assert.Equal(t, []string{"past", "in-1m"}, names(upcoming)) +} diff --git a/galvanize-instancer/pkg/scheduler/scheduler.go b/galvanize-instancer/pkg/scheduler/scheduler.go index 0b26ce2..f207a95 100644 --- a/galvanize-instancer/pkg/scheduler/scheduler.go +++ b/galvanize-instancer/pkg/scheduler/scheduler.go @@ -76,12 +76,7 @@ func (s *ExpiryScheduler) fetchNextExpiries() { window := time.Now().Add(s.lookahead) - var deployments []models.Deployment - err := s.db.Where("status = ? AND expires_at IS NOT NULL AND expires_at <= ? AND team_id IS NOT NULL", // Not null excludes unique deployments - "running", window). - Order("expires_at ASC"). - Find(&deployments).Error - + deployments, err := models.GetDeploymentsExpiringBy(s.db, window) if err != nil { s.l.Errorf("failed to fetch upcoming expirations: %v", err) return