Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,20 @@

## 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-<hash>`). 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": <count>, "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
- 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
- `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)

### Added
Expand Down
4 changes: 2 additions & 2 deletions config.example.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
2 changes: 1 addition & 1 deletion data/challenges/example/http/challenge.yml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ type: zync

# The 'http' playbook deploys a single container behind Traefik.
# Traefik routes traffic based on a generated subdomain:
# <compose_project>.<instancer_host> (e.g. polypwn-example-http-team1-a3f2c1.challs.example.com)
# <compose_project>.<instancer_host> (e.g. polypwn-web-example-http-team1-9448f1e7.challs.example.com)
playbook_name: http

deploy_parameters:
Expand Down
31 changes: 30 additions & 1 deletion data/playbooks/custom_compose.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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 }}"
Expand All @@ -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 }}"
Expand All @@ -47,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
11 changes: 11 additions & 0 deletions data/playbooks/http.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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
11 changes: 11 additions & 0 deletions data/playbooks/tcp.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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
34 changes: 33 additions & 1 deletion galvanize-instancer/api/openapi.yaml.in
Original file line number Diff line number Diff line change
Expand Up @@ -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':
Expand Down Expand Up @@ -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:
Expand Down
3 changes: 3 additions & 0 deletions galvanize-instancer/cmd/serve.go
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
2 changes: 1 addition & 1 deletion galvanize-instancer/internal/ansible/compose_expose.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down
9 changes: 6 additions & 3 deletions galvanize-instancer/internal/ansible/connection_info_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"strings"
"testing"

"github.com/28Pollux28/galvanize/pkg/config"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
Expand All @@ -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)
Expand Down Expand Up @@ -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)
Expand All @@ -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 {
Expand All @@ -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)
}
11 changes: 8 additions & 3 deletions galvanize-instancer/internal/ansible/deployer.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
Expand Down Expand Up @@ -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)
}
Expand Down
21 changes: 17 additions & 4 deletions galvanize-instancer/internal/ansible/playbook.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 != "" {
Expand All @@ -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 {
Expand All @@ -44,14 +53,11 @@ func BuildResourceOverrides(rl config.ResourceLimits) map[string]interface{} {
},
}
}
if rl.PidsLimit > 0 {
overrides["pids_limit"] = rl.PidsLimit
}
return overrides
}

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{
Expand All @@ -74,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 {
Expand Down
44 changes: 44 additions & 0 deletions galvanize-instancer/internal/ansible/playbook_test.go
Original file line number Diff line number Diff line change
@@ -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)))
}
Loading
Loading