From e63ad6739eea536a920274eb1118316164814d3a Mon Sep 17 00:00:00 2001 From: Ivan Liang Date: Tue, 17 Nov 2026 13:43:32 -0500 Subject: [PATCH 01/13] fix(docker): pass security options with = rather than : Docker's parseSecurityOpt splits an option at its first '=' whenever the option contains one, and falls back to ':' only when it does not. cmgr built its seccomp option as "seccomp:" + profile, so any '=' inside the profile JSON became the split point: the key came out as `seccomp:{...` and the create failed with `invalid --security-opt 2`. validateSeccompProfile decodes with a plain json.Unmarshal, which ignores unknown fields, and Docker's profile format has a per-syscall "comment". A per-challenge profile with an '=' in a comment therefore passed validation and then failed every launch. The embedded seccomp.json has no '=', so the default profile was never affected. With "seccomp=" the first '=' is always the separator. no-new-privileges moves to the same form, which also stops dockerd logging the colon-separator deprecation warning for each option on every create. HostConfig.SecurityOpt is stored as given, so `docker inspect` on new containers shows `seccomp={...}`. Running containers keep the colon form, which Docker still accepts on restart, so there is nothing to migrate. Checked against Docker 29.9.3 with a challenge profile carrying "persona=0xffffffff" in a comment: master fails the launch with `invalid --security-opt 2`; on this branch the instance starts and serves. Backported from cork (CyLabAcademy/challenge-orchestrator) cea231f. --- cmgr/docker.go | 6 +++--- cmgr/seccomp.go | 7 +++++++ cmgr/seccomp_test.go | 15 +++++++++++++++ cmgr/solver_framework.go | 2 +- examples/specification.md | 2 +- 5 files changed, 27 insertions(+), 5 deletions(-) diff --git a/cmgr/docker.go b/cmgr/docker.go index 10bb70d..048036b 100644 --- a/cmgr/docker.go +++ b/cmgr/docker.go @@ -629,7 +629,7 @@ func (m *Manager) executeBuild(cMeta *ChallengeMetadata, bMeta *BuildMetadata, b if m.hostOSType == "linux" { m.log.debug("inserting custom seccomp profile") - hConfig.SecurityOpt = []string{"seccomp:" + seccompPolicy} + hConfig.SecurityOpt = []string{seccompSecurityOpt(seccompPolicy)} } respCC, err := m.cli.ContainerCreate(m.ctx, client.ContainerCreateOptions{ @@ -913,7 +913,7 @@ func (m *Manager) startContainers(build *BuildMetadata, instance *InstanceMetada hConfig.ReadonlyRootfs = cOpts.ReadonlyRootfs hConfig.CapDrop = (strslice.StrSlice)(cOpts.DroppedCaps) if cOpts.NoNewPrivileges { - hConfig.SecurityOpt = append(hConfig.SecurityOpt, "no-new-privileges:true") + hConfig.SecurityOpt = append(hConfig.SecurityOpt, "no-new-privileges=true") } if cOpts.DiskQuota != "" { _, quotas_enabled := os.LookupEnv(DISK_QUOTA_ENV) @@ -947,7 +947,7 @@ func (m *Manager) startContainers(build *BuildMetadata, instance *InstanceMetada } else { m.log.debug("inserting custom seccomp profile") } - hConfig.SecurityOpt = append(hConfig.SecurityOpt, "seccomp:"+profile) + hConfig.SecurityOpt = append(hConfig.SecurityOpt, seccompSecurityOpt(profile)) } nConfig := network.NetworkingConfig{ diff --git a/cmgr/seccomp.go b/cmgr/seccomp.go index 07918a0..4d3397b 100644 --- a/cmgr/seccomp.go +++ b/cmgr/seccomp.go @@ -70,6 +70,13 @@ func (opts *SeccompOptions) resolve(challengeDir string) error { return nil } +// seccompSecurityOpt passes profile to Docker as a security option. Docker +// splits an option at its first '=' when it has one, so the ':' form breaks on +// any profile containing '='. +func seccompSecurityOpt(profile string) string { + return "seccomp=" + profile +} + // validateSeccompProfileFilename constrains profiles to a plain JSON file // beside the challenge metadata. Names beginning with '.' are rejected in // particular because checksumIgnore skips them, so a hidden profile would not diff --git a/cmgr/seccomp_test.go b/cmgr/seccomp_test.go index cc228c0..421ad67 100644 --- a/cmgr/seccomp_test.go +++ b/cmgr/seccomp_test.go @@ -192,6 +192,21 @@ func TestEmbeddedPolicyPassesProfileValidation(t *testing.T) { } } +// A per-syscall "comment" is valid Docker profile syntax that validation +// ignores, so an '=' in one reaches the security option and must not move +// where Docker splits it. +func TestSeccompSecurityOptKeepsProfileWithEquals(t *testing.T) { + profile := strings.Replace(testSeccompProfile, `"action"`, `"comment": "persona=0xffffffff only queries", "action"`, 1) + if err := validateSeccompProfile(profile); err != nil { + t.Fatalf("profile with a comment was rejected: %s", err) + } + // Docker's parseSecurityOpt cuts at the first '=' whenever there is one. + key, value, _ := strings.Cut(seccompSecurityOpt(profile), "=") + if key != "seccomp" || value != profile { + t.Fatalf("security option splits into key %q and a %d-byte value; expected seccomp and the %d-byte profile", key, len(value), len(profile)) + } +} + // Challenge options arrive as JSON from problem.json and as YAML from // problem.md, so the option must decode through both paths. func TestSeccompOptionParsesFromChallengeMetadata(t *testing.T) { diff --git a/cmgr/solver_framework.go b/cmgr/solver_framework.go index 5083147..d0b1cdc 100644 --- a/cmgr/solver_framework.go +++ b/cmgr/solver_framework.go @@ -143,7 +143,7 @@ func (m *Manager) executeSolver(cMeta *ChallengeMetadata, bMeta *BuildMetadata, hConfig := container.HostConfig{} if m.hostOSType == "linux" { m.log.debug("inserting custom seccomp profile") - hConfig.SecurityOpt = []string{"seccomp:" + seccompPolicy} + hConfig.SecurityOpt = []string{seccompSecurityOpt(seccompPolicy)} } // With no instance network (non-service builds) the solver runs on Docker's diff --git a/examples/specification.md b/examples/specification.md index a97f487..e39bf9d 100644 --- a/examples/specification.md +++ b/examples/specification.md @@ -157,7 +157,7 @@ containers. [prevent](https://www.kernel.org/doc/html/latest/userspace-api/no_new_privs.html) processes inside the container from gaining additional privileges via `execve()` calls (by exploiting setuid binaries, etc). This is equivalent to passing the - [`--security-opt="no-new-privileges:true"`](https://docs.docker.com/engine/reference/run/#security-configuration) + [`--security-opt="no-new-privileges=true"`](https://docs.docker.com/engine/reference/run/#security-configuration) option to `docker run`. Specify a boolean value, as shown in the example below. Defaults to `false`. From f7f9914d3d5c79d5b5d9111203b374f96de09e44 Mon Sep 17 00:00:00 2001 From: Ivan Liang Date: Tue, 17 Nov 2026 13:43:35 -0500 Subject: [PATCH 02/13] fix(loader): fail closed when a challenge's container options cannot be read Three error swallows let a challenge run without its declared hardening: - loadMarkdownChallenge assigned each section's error to the same err that the next section, and then the checksum write, overwrote. A YAML error in the "challenge options" block (yaml v3 rejects duplicate mapping keys, for one) was logged and the challenge loaded with zeroed container options. Section errors now fail the load. Update already refuses removals when errors are present, so a broken challenge is reported, never torn down. This applies to every section, as in cork: a tag or attribute line the loader cannot read now fails the load too, where it used to be logged and dropped. - Within that section, a fence problem (an unclosed or unopened block, two blocks, or a close before the open) was itself overwritten by parsing an empty range, which succeeds: zeroed options again, and with two blocks the first one silently dropped. A close before the open would instead have sliced an inverted range and panicked. Each is now an error. Fences are matched trimmed, so a CRLF file or a trailing space on a fence delimits the block instead of failing it. - lookupChallengeMetadata shadowed err inside the containerOptions loop, so a row that failed to decode (a corrupt seccomp column, say) broke out of the loop and returned the challenge with no container options and a nil error. Instances launched from it ran without any of their hardening. The lookup now fails, and the launch with it. Regression tests cover each swallow and fail without the fix. Backported from cork (CyLabAcademy/challenge-orchestrator) 558a9f9; the fence handling goes beyond it. --- cmgr/database_challenges.go | 4 +- cmgr/database_operations_test.go | 37 +++++++++++++ cmgr/loader_markdown.go | 62 +++++++++++++-------- cmgr/loader_markdown_test.go | 95 ++++++++++++++++++++++++++++++++ 4 files changed, 174 insertions(+), 24 deletions(-) diff --git a/cmgr/database_challenges.go b/cmgr/database_challenges.go index a9adc9e..e872ada 100644 --- a/cmgr/database_challenges.go +++ b/cmgr/database_challenges.go @@ -122,8 +122,10 @@ func (m *Manager) lookupChallengeMetadata(challenge ChallengeId) (*ChallengeMeta err = txn.Select(containerOptions, "SELECT host, init, cpus, memory, ulimits, pidslimit, readonlyrootfs, droppedcaps, nonewprivileges, diskquota, cgroupparent, capimmutable, seccomp FROM containerOptions WHERE challenge=?", challenge) } for _, dbOpts := range *containerOptions { - cOpts, err := newFromDbContainerOptions(dbOpts) + var cOpts ContainerOptions + cOpts, err = newFromDbContainerOptions(dbOpts) if err != nil { + m.log.errorf("could not decode container options for '%s' (host '%s'): %s", challenge, dbOpts.Host, err) break } if metadata.ChallengeOptions.Overrides == nil { diff --git a/cmgr/database_operations_test.go b/cmgr/database_operations_test.go index 092dc02..83e3e7e 100644 --- a/cmgr/database_operations_test.go +++ b/cmgr/database_operations_test.go @@ -1794,3 +1794,40 @@ func TestInitDatabaseRepairsStaleIsFinalizedDefault(t *testing.T) { t.Errorf("expected new instance to default to is_finalized=0, got %d", fresh) } } + +// TestLookupChallengeMetadataSurfacesOptionsDecodeError verifies that a +// containerOptions row that fails to decode (e.g. a corrupt seccomp column) +// causes lookupChallengeMetadata to return an error instead of silently +// returning the challenge with no container options — which would launch +// instances without any of their declared hardening. +func TestLookupChallengeMetadataSurfacesOptionsDecodeError(t *testing.T) { + mgr := setupTestManager(t) + defer mgr.db.Close() + + challenge := &ChallengeMetadata{ + Id: "test/corrupt-options", + Name: "Corrupt Options", + Namespace: "test", + ChallengeType: "custom", + Hosts: []HostInfo{{Name: "challenge", Target: ""}}, + PortMap: map[string]PortInfo{}, + Path: "/tmp/test/problem.md", + ChallengeOptions: ChallengeOptions{ + Overrides: map[string]ContainerOptions{ + "": {ReadonlyRootfs: true}, + }, + }, + } + + if errs := mgr.addChallenges([]*ChallengeMetadata{challenge}); len(errs) > 0 { + t.Fatalf("addChallenges failed: %v", errs) + } + + if _, err := mgr.db.Exec("UPDATE containerOptions SET seccomp='{not json' WHERE challenge=?", challenge.Id); err != nil { + t.Fatalf("failed to corrupt seccomp column: %s", err) + } + + if _, err := mgr.lookupChallengeMetadata(challenge.Id); err == nil { + t.Fatal("expected lookupChallengeMetadata to fail on a corrupt seccomp column, got nil error") + } +} diff --git a/cmgr/loader_markdown.go b/cmgr/loader_markdown.go index 3ab84ba..8685e4f 100644 --- a/cmgr/loader_markdown.go +++ b/cmgr/loader_markdown.go @@ -159,13 +159,18 @@ func (m *Manager) loadMarkdownChallenge(path string, info os.FileInfo) (*Challen } } + // A section error fails the load: swallowed, a bad "challenge options" + // block would deploy the challenge without its hardening. + var sectionErr error section := "" startIdx := 0 for idx < len(lines) { line = strings.TrimSpace(lines[idx]) match := sectionRe.FindStringSubmatch(line) if match != nil && section != "" { - err = m.processMarkdownSection(md, section, lines, startIdx, idx) + if tmpErr := m.processMarkdownSection(md, section, lines, startIdx, idx); tmpErr != nil && sectionErr == nil { + sectionErr = tmpErr + } } if match != nil { section = match[1] @@ -175,7 +180,13 @@ func (m *Manager) loadMarkdownChallenge(path string, info os.FileInfo) (*Challen } if section != "" { - err = m.processMarkdownSection(md, section, lines, startIdx, idx) + if tmpErr := m.processMarkdownSection(md, section, lines, startIdx, idx); tmpErr != nil && sectionErr == nil { + sectionErr = tmpErr + } + } + + if sectionErr != nil { + return nil, sectionErr } h := crc32.NewIEEE() @@ -240,42 +251,47 @@ func (m *Manager) processMarkdownSection(md *ChallengeMetadata, section string, case "challenge options": yamlStart := 0 yamlEnd := 0 - for i := startIdx; i < endIdx; i++ { - if lines[i] == "```yaml" { + // Markers are matched trimmed, so CRLF files and trailing spaces work. + // Any marker problem is returned rather than parsed past: parsing the + // wrong range would load the challenge without its options. + for i := startIdx; i < endIdx && err == nil; i++ { + switch strings.TrimSpace(lines[i]) { + case "```yaml": if yamlStart != 0 { - err = fmt.Errorf("found multiple start markers for yaml at lines %d and %d", yamlStart-1, i) - m.log.error(err) + err = fmt.Errorf("found multiple start markers for yaml at lines %d and %d: %s", yamlStart, i+1, md.Path) } yamlStart = i + 1 - } else if lines[i] == "```" { + case "```": if yamlEnd != 0 { - err = fmt.Errorf("found multiple end markers for yaml at lines %d and %d", yamlEnd, i) - m.log.error(err) + err = fmt.Errorf("found multiple end markers for yaml at lines %d and %d: %s", yamlEnd+1, i+1, md.Path) } yamlEnd = i } } - if yamlStart == 0 && yamlEnd == 0 { - m.log.debug("addining implicit delimiters for challenge options") - yamlStart = startIdx - yamlEnd = endIdx - } else if (yamlStart == 0) != (yamlEnd == 0) { - err = fmt.Errorf("found a start/end marker but missing its pair: startline=%d endline=%d", yamlStart, yamlEnd) - m.log.error(err) - yamlStart = 0 - yamlEnd = 0 + if err == nil { + if yamlStart == 0 && yamlEnd == 0 { + m.log.debug("adding implicit delimiters for challenge options") + yamlStart = startIdx + yamlEnd = endIdx + } else if yamlStart == 0 || yamlEnd == 0 || yamlEnd < yamlStart { + err = fmt.Errorf("challenge options need one ```yaml line and one ``` line after it: %s", md.Path) + } } - opts := ChallengeOptions{} - yamlData := []byte(strings.Join(lines[yamlStart:yamlEnd], "\n")) - err = yaml.Unmarshal(yamlData, &opts) + if err == nil { + opts := ChallengeOptions{} + yamlData := []byte(strings.Join(lines[yamlStart:yamlEnd], "\n")) + if err = yaml.Unmarshal(yamlData, &opts); err != nil { + err = fmt.Errorf("could not parse challenge options: %w: %s", err, md.Path) + } else { + md.ChallengeOptions = opts + } + } if err != nil { m.log.error(err) } - md.ChallengeOptions = opts - default: attrVal := strings.TrimSpace(strings.Join(lines[startIdx:endIdx], "\n")) md.Attributes[section] = attrVal diff --git a/cmgr/loader_markdown_test.go b/cmgr/loader_markdown_test.go index c87c670..128eaf5 100644 --- a/cmgr/loader_markdown_test.go +++ b/cmgr/loader_markdown_test.go @@ -618,3 +618,98 @@ func TestTagLineRegex(t *testing.T) { } } } + +// TestLoadMarkdownChallengeFailsOnSectionError verifies that an error while +// processing a markdown section — here a duplicate mapping key, which yaml v3 +// rejects — fails the whole load rather than being logged and swallowed. A +// swallowed error would load the challenge with zeroed container options and +// deploy it without its declared hardening. +func TestLoadMarkdownChallengeFailsOnSectionError(t *testing.T) { + mgr := newTestManager() + + content := `# Dup Key Challenge + +- Namespace: cmgr/test +- Type: custom +- Category: test +- Points: 1 + +## Description + +A challenge. + +## Challenge Options + +` + "```yaml" + ` +memory: 512m +memory: 1g +` + "```" + ` +` + + dir := t.TempDir() + path := filepath.Join(dir, "problem.md") + if err := os.WriteFile(path, []byte(content), 0644); err != nil { + t.Fatalf("failed to write problem.md: %s", err) + } + info, err := os.Stat(path) + if err != nil { + t.Fatalf("failed to stat problem.md: %s", err) + } + + if _, err := mgr.loadMarkdownChallenge(path, info); err == nil { + t.Fatal("expected loadMarkdownChallenge to fail on duplicate challenge-options key, got nil error") + } +} + +// loadOptionsFixture writes a problem.md whose "challenge options" section is +// body, verbatim, and loads it. +func loadOptionsFixture(t *testing.T, body string) (*ChallengeMetadata, error) { + t.Helper() + content := "# Options Challenge\n\n- Namespace: cmgr/test\n- Type: custom\n\n## Description\n\nA challenge.\n\n## Challenge Options\n\n" + body + path := filepath.Join(t.TempDir(), "problem.md") + if err := os.WriteFile(path, []byte(content), 0644); err != nil { + t.Fatalf("failed to write problem.md: %s", err) + } + info, err := os.Stat(path) + if err != nil { + t.Fatalf("failed to stat problem.md: %s", err) + } + return newTestManager().loadMarkdownChallenge(path, info) +} + +// A fence problem used to be overwritten by the parse of an empty range, which +// loaded the challenge with no options at all. +func TestLoadMarkdownChallengeFailsOnBadOptionsFence(t *testing.T) { + for name, body := range map[string]string{ + "unclosed": "```yaml\nmemory: 512m\n", + "unopened": "memory: 512m\n```\n", + "two blocks": "```yaml\nmemory: 512m\n```\n\n```yaml\npidslimit: 64\n```\n", + "close then open": "```\nmemory: 512m\n```yaml\n", + } { + t.Run(name, func(t *testing.T) { + if md, err := loadOptionsFixture(t, body); err == nil { + t.Fatalf("expected the load to fail, got options %+v", md.ChallengeOptions.ContainerOptions) + } + }) + } +} + +// Fences are matched trimmed: a CRLF file or a trailing space on a fence still +// delimits the block, and its options apply. +func TestLoadMarkdownChallengeOptionsFenceTolerance(t *testing.T) { + for name, body := range map[string]string{ + "crlf": "```yaml\r\nmemory: 512m\r\npidslimit: 64\r\n```\r\n", + "trailing space": "```yaml \nmemory: 512m\npidslimit: 64\n``` \n", + } { + t.Run(name, func(t *testing.T) { + md, err := loadOptionsFixture(t, body) + if err != nil { + t.Fatalf("load failed: %s", err) + } + opts := md.ChallengeOptions.ContainerOptions + if opts.Memory != "512m" || opts.PidsLimit != 64 { + t.Fatalf("options did not apply: memory=%q pidslimit=%d", opts.Memory, opts.PidsLimit) + } + }) + } +} From 97fd3ba21c8014484e9d9126d4cfce7b8d74e013 Mon Sep 17 00:00:00 2001 From: Ivan Liang Date: Tue, 17 Nov 2026 13:43:35 -0500 Subject: [PATCH 03/13] fix(loader): fail the load on a header value that does not parse loadMarkdownChallenge assigned the parse error of a header value to the same err the next line, and finally the checksum write, overwrote, and then returned the challenge with a nil error. '- Points: ten' loaded as 0 points, '- MaxUsers: x' as no limit and '- Templatable: maybe' as false, each with an ERROR line in the log and nothing else. Such a value now fails the load, naming the key and line, and so does a header line that is not a '- key: value' bullet at all: '* Points: 100' was logged as unrecognized text and loaded as 0 points the same way. An unknown key does not fail the load: it is logged as ignored and the challenge loads, so that a problem.md written for a newer loader (cork's '- Difficulty: easy', for one) keeps loading here. That line is logged at warn rather than error, since nothing is wrong with the challenge. None of the 554 problem.md files in the picoCTF challenge repositories, nor cmgr's examples, has a value or a header line this rejects. --- cmgr/loader_markdown.go | 27 +++++++++++++------------ cmgr/loader_markdown_test.go | 38 ++++++++++++++++++++++++++++++++++++ 2 files changed, 53 insertions(+), 12 deletions(-) diff --git a/cmgr/loader_markdown.go b/cmgr/loader_markdown.go index 8685e4f..6d757e5 100644 --- a/cmgr/loader_markdown.go +++ b/cmgr/loader_markdown.go @@ -126,12 +126,17 @@ func (m *Manager) loadMarkdownChallenge(path string, info os.FileInfo) (*Challen continue } + // Text that is not a '- key: value' line, or a value that does not + // parse, fails the load rather than leaving a field at its zero value. + // An unknown key is ignored, so that a problem.md written for a newer + // loader (cork's difficulty, say) still loads. if match == nil { - err = fmt.Errorf("unrecognized metadata text on line %d: %s", idx, path) + err = fmt.Errorf("unrecognized metadata text on line %d (header lines are '- key: value'): %s", idx, path) m.log.error(err) - continue + return nil, err } + var valueErr error switch strings.ToLower(match[1]) { case "id": md.Id = ChallengeId(match[2]) @@ -142,20 +147,18 @@ func (m *Manager) loadMarkdownChallenge(path string, info os.FileInfo) (*Challen case "category": md.Category = match[2] case "templatable": - val, tmpErr := parseBool(match[2]) - md.Templatable = val - err = tmpErr + md.Templatable, valueErr = parseBool(match[2]) case "points": - i, tmpErr := strconv.Atoi(match[2]) - md.Points = i - err = tmpErr + md.Points, valueErr = strconv.Atoi(match[2]) case "maxusers": - i, tmpErr := strconv.Atoi(match[2]) - md.MaxUsers = i - err = tmpErr + md.MaxUsers, valueErr = strconv.Atoi(match[2]) default: - err = fmt.Errorf("unrecognized top-level attribute '%s' on line %d: %s", match[1], idx, path) + m.log.warnf("ignoring unrecognized top-level attribute '%s' on line %d: %s", match[1], idx, path) + } + if valueErr != nil { + err = fmt.Errorf("invalid value for '%s' on line %d: %w: %s", match[1], idx, valueErr, path) m.log.error(err) + return nil, err } } diff --git a/cmgr/loader_markdown_test.go b/cmgr/loader_markdown_test.go index 128eaf5..760c79a 100644 --- a/cmgr/loader_markdown_test.go +++ b/cmgr/loader_markdown_test.go @@ -713,3 +713,41 @@ func TestLoadMarkdownChallengeOptionsFenceTolerance(t *testing.T) { }) } } + +func loadHeaderFixture(t *testing.T, header string) (*ChallengeMetadata, error) { + t.Helper() + content := "# Header Challenge\n\n- Namespace: cmgr/test\n- Type: custom\n" + header + "\n## Description\n\nA challenge.\n" + path := filepath.Join(t.TempDir(), "problem.md") + if err := os.WriteFile(path, []byte(content), 0644); err != nil { + t.Fatalf("failed to write problem.md: %s", err) + } + info, err := os.Stat(path) + if err != nil { + t.Fatalf("failed to stat problem.md: %s", err) + } + return newTestManager().loadMarkdownChallenge(path, info) +} + +// A header value that does not parse, or a header line that is not a +// '- key: value' bullet, used to load the challenge with the field at its +// zero value. +func TestLoadMarkdownChallengeFailsOnBadHeaderValue(t *testing.T) { + for _, line := range []string{"- Points: ten", "- MaxUsers: x", "- Templatable: maybe", "* Points: 100", "Points are doubled this week"} { + t.Run(line, func(t *testing.T) { + if md, err := loadHeaderFixture(t, line+"\n"); err == nil { + t.Fatalf("expected the load to fail, got points=%d maxusers=%d templatable=%v", md.Points, md.MaxUsers, md.Templatable) + } + }) + } +} + +// An unknown key, such as one a newer loader understands, is ignored. +func TestLoadMarkdownChallengeIgnoresUnknownHeaderKey(t *testing.T) { + md, err := loadHeaderFixture(t, "- Points: 50\n- Difficulty: easy\n") + if err != nil { + t.Fatalf("load failed: %s", err) + } + if md.Points != 50 { + t.Fatalf("points = %d, want 50", md.Points) + } +} From da843a9b1a369c4c5f775e4c68fd61861da49e01 Mon Sep 17 00:00:00 2001 From: Ivan Liang Date: Tue, 17 Nov 2026 13:43:35 -0500 Subject: [PATCH 04/13] fix(db): report the failure that rolled back a challenge's write addChallenges and updateChallenges wrote a challenge's rows statement by statement, and on a failure did `err = txn.Rollback()`. A rollback that succeeds sets err to nil, so the `if err != nil { continue }` after each loop fell through: the next statements ran on the dead transaction, got "transaction has already been committed or rolled back", rolled back again, and that second rollback's error returned from the function, abandoning every remaining challenge in the batch. The error that caused it was only logged. A failed insert of the challenge row itself was skipped with `continue` and never reported at all, and a failure in the container options loop shadowed err and reached the commit of a rolled-back transaction. Both now go through writeChallenge: one transaction that writes the challenge row, replaces the rows that hang off it and returns the first failure, which is rolled back and reported, and the batch moves on to the next challenge. It begins with Beginx rather than MustBegin, so a database that cannot start a transaction is an error, not a panic. A test drives a trigger-rejected tag through both paths: the rejection is the one error reported, the failed challenge is left as it was, and the challenge after it is written. On the old loops the next challenge is never written. Cork carries the same loops; this goes beyond it. --- cmgr/database_challenges.go | 512 ++++++------------------------- cmgr/database_operations_test.go | 60 ++++ 2 files changed, 146 insertions(+), 426 deletions(-) diff --git a/cmgr/database_challenges.go b/cmgr/database_challenges.go index e872ada..9b234f5 100644 --- a/cmgr/database_challenges.go +++ b/cmgr/database_challenges.go @@ -5,6 +5,8 @@ import ( "fmt" "os" "strings" + + "github.com/jmoiron/sqlx" ) // Columns for list/search results: the light-weight subset plus what @@ -156,191 +158,103 @@ func (m *Manager) lookupChallengeMetadata(challenge ChallengeId) (*ChallengeMeta func (m *Manager) addChallenges(addedChallenges []*ChallengeMetadata) []error { errs := []error{} for _, metadata := range addedChallenges { - txn := m.db.MustBegin() - - _, err := txn.NamedExec(challengeInsertQuery, metadata) - if err != nil { - m.log.error(err) - err = txn.Rollback() - if err != nil { // If rollback fails, we're in trouble. - m.log.error(err) - return append(errs, err) - } - continue - } - - for i, hint := range metadata.Hints { - _, err = txn.Exec("INSERT INTO hints(challenge, idx, hint) VALUES (?, ?, ?);", - metadata.Id, - i, - hint) - - if err != nil { - m.log.error(err) - err = txn.Rollback() - if err != nil { // If rollback fails, we're in trouble. - m.log.error(err) - return append(errs, err) - } - break - } - } - if err != nil { - continue + if err := m.writeChallenge(metadata, challengeInsertQuery); err != nil { + errs = append(errs, err) } + } + return errs +} - for _, tag := range metadata.Tags { - _, err = txn.Exec("INSERT INTO tags(challenge, tag) VALUES (?, ?);", - metadata.Id, - tag) - - if err != nil { - m.log.error(err) - err = txn.Rollback() - if err != nil { // If rollback fails, we're in trouble. - m.log.error(err) - return append(errs, err) - } - break - } - } - if err != nil { - continue +// writeChallenge records a challenge and the rows that hang off it in one +// transaction, query inserting or updating the challenge row itself. The +// first failure rolls the whole write back and is the error returned. +func (m *Manager) writeChallenge(metadata *ChallengeMetadata, query string) error { + txn, err := m.db.Beginx() + if err != nil { + m.log.error(err) + return err + } + if err = m.writeChallengeRows(txn, metadata, query); err != nil { + err = fmt.Errorf("could not record challenge %s: %w", metadata.Id, err) + m.log.error(err) + if rbErr := txn.Rollback(); rbErr != nil { + m.log.error(rbErr) } + return err + } + if err = txn.Commit(); err != nil { + m.log.error(err) + } + return err +} - for k, v := range metadata.Attributes { - _, err = txn.Exec("INSERT INTO attributes(challenge, key, value) VALUES (?, ?, ?);", - metadata.Id, - k, - v) - - if err != nil { - m.log.error(err) - err = txn.Rollback() - if err != nil { // If rollback fails, we're in trouble. - m.log.error(err) - return append(errs, err) - } - break - } - } - if err != nil { - continue +func (m *Manager) writeChallengeRows(txn *sqlx.Tx, metadata *ChallengeMetadata, query string) error { + if _, err := txn.NamedExec(query, metadata); err != nil { + return err + } + // There are no network-level challenge options yet; they would go here. + for _, table := range []string{"hints", "tags", "attributes", "hosts", "portNames", "containerOptions"} { + if _, err := txn.Exec("DELETE FROM "+table+" WHERE challenge = ?;", metadata.Id); err != nil { + return err } - - for i, host := range metadata.Hosts { - m.log.debugf("%s: %v", metadata.Id, host) - _, err = txn.Exec("INSERT INTO hosts(challenge, name, idx, target) VALUES (?, ?, ?, ?);", - metadata.Id, - host.Name, - i, - host.Target) - - if err != nil { - m.log.error(err) - err = txn.Rollback() - if err != nil { // If rollback fails, we're in trouble. - m.log.error(err) - return append(errs, err) - } - break - } + } + for i, hint := range metadata.Hints { + if _, err := txn.Exec("INSERT INTO hints(challenge, idx, hint) VALUES (?, ?, ?);", + metadata.Id, i, hint); err != nil { + return err } - if err != nil { - continue + } + for _, tag := range metadata.Tags { + if _, err := txn.Exec("INSERT INTO tags(challenge, tag) VALUES (?, ?);", + metadata.Id, tag); err != nil { + return err } - - for k, v := range metadata.PortMap { - m.log.debugf("%s: %v", metadata.Id, v) - _, err = txn.Exec("INSERT INTO portNames(challenge, name, host, port) VALUES (?, ?, ?, ?);", - metadata.Id, - k, - v.Host, - v.Port) - - if err != nil { - m.log.error(err) - err = txn.Rollback() - if err != nil { // If rollback fails, we're in trouble. - m.log.error(err) - return append(errs, err) - } - break - } + } + for k, v := range metadata.Attributes { + if _, err := txn.Exec("INSERT INTO attributes(challenge, key, value) VALUES (?, ?, ?);", + metadata.Id, k, v); err != nil { + return err } - if err != nil { - continue + } + for i, host := range metadata.Hosts { + m.log.debugf("%s: %v", metadata.Id, host) + if _, err := txn.Exec("INSERT INTO hosts(challenge, name, idx, target) VALUES (?, ?, ?, ?);", + metadata.Id, host.Name, i, host.Target); err != nil { + return err } - - // Note: there are currently no network-level challenge options, but they will be saved here if added in the future. - - // m.log.debugf("%s: %v", metadata.Id, metadata.ChallengeOptions.NetworkOptions) - // _, err = txn.Exec("INSERT INTO networkOptions(challenge) VALUES (?);", - // metadata.Id, - // ) - // if err != nil { - // m.log.error(err) - // err = txn.Rollback() - // if err != nil { // If rollback fails, we're in trouble. - // m.log.error(err) - // return append(errs, err) - // } - // } - // if err != nil { - // continue - // } - - for host, opts := range metadata.ChallengeOptions.Overrides { - host_str := "" - if host != "" { - host_str = fmt.Sprintf(" (%s)", host) - } - dbOpts, err := opts.toDbContainerOptions() - if err != nil { - m.log.error(err) - err = txn.Rollback() - if err != nil { // If rollback fails, we're in trouble. - m.log.error(err) - return append(errs, err) - } - break - } - m.log.debugf("%s%s: %v", metadata.Id, host_str, dbOpts) - _, err = txn.Exec("INSERT INTO containerOptions(challenge, host, init, cpus, memory, ulimits, pidslimit, readonlyrootfs, droppedcaps, nonewprivileges, diskquota, cgroupparent, capimmutable, seccomp) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);", - metadata.Id, - host, - dbOpts.Init, - dbOpts.Cpus, - dbOpts.Memory, - dbOpts.Ulimits, - dbOpts.PidsLimit, - dbOpts.ReadonlyRootfs, - dbOpts.DroppedCaps, - dbOpts.NoNewPrivileges, - dbOpts.DiskQuota, - dbOpts.CgroupParent, - dbOpts.CapImmutable, - dbOpts.Seccomp) - if err != nil { - m.log.error(err) - err = txn.Rollback() - if err != nil { // If rollback fails, we're in trouble. - m.log.error(err) - return append(errs, err) - } - break - } + } + for k, v := range metadata.PortMap { + m.log.debugf("%s: %v", metadata.Id, v) + if _, err := txn.Exec("INSERT INTO portNames(challenge, name, host, port) VALUES (?, ?, ?, ?);", + metadata.Id, k, v.Host, v.Port); err != nil { + return err } + } + for host, opts := range metadata.ChallengeOptions.Overrides { + dbOpts, err := opts.toDbContainerOptions() if err != nil { - continue + return err } - - if err := txn.Commit(); err != nil { // It's undocumented what this means... - m.log.error(err) - errs = append(errs, err) + m.log.debugf("%s (host %q): %v", metadata.Id, host, dbOpts) + if _, err = txn.Exec("INSERT INTO containerOptions(challenge, host, init, cpus, memory, ulimits, pidslimit, readonlyrootfs, droppedcaps, nonewprivileges, diskquota, cgroupparent, capimmutable, seccomp) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);", + metadata.Id, + host, + dbOpts.Init, + dbOpts.Cpus, + dbOpts.Memory, + dbOpts.Ulimits, + dbOpts.PidsLimit, + dbOpts.ReadonlyRootfs, + dbOpts.DroppedCaps, + dbOpts.NoNewPrivileges, + dbOpts.DiskQuota, + dbOpts.CgroupParent, + dbOpts.CapImmutable, + dbOpts.Seccomp); err != nil { + return err } } - return errs + return nil } // rotatedPrevChecksum returns the rollback generation to retain after a @@ -369,262 +283,8 @@ func displacedPruneCandidate(oldChecksum, newChecksum, displaced uint32) bool { func (m *Manager) updateChallenges(updatedChallenges []*ChallengeMetadata, rebuild bool, pruneOldImages bool) []error { errs := []error{} for _, metadata := range updatedChallenges { - txn := m.db.MustBegin() - - _, err := txn.NamedExec(challengeUpdateQuery, metadata) - if err != nil { - m.log.error(err) - err = txn.Rollback() - if err != nil { // If rollback fails, we're in trouble. - m.log.error(err) - return append(errs, err) - } - continue - } - - _, err = txn.Exec("DELETE FROM hints WHERE challenge = ?;", metadata.Id) - - if err != nil { - m.log.error(err) - err = txn.Rollback() - if err != nil { // If rollback fails, we're in trouble. - m.log.error(err) - return append(errs, err) - } - continue - } - for i, hint := range metadata.Hints { - - _, err = txn.Exec("INSERT INTO hints(challenge, idx, hint) VALUES (?, ?, ?);", - metadata.Id, - i, - hint) - - if err != nil { - m.log.error(err) - err = txn.Rollback() - if err != nil { // If rollback fails, we're in trouble. - m.log.error(err) - return append(errs, err) - } - break - } - } + err := m.writeChallenge(metadata, challengeUpdateQuery) if err != nil { - continue - } - - _, err = txn.Exec("DELETE FROM tags WHERE challenge = ?;", metadata.Id) - - if err != nil { - m.log.error(err) - err = txn.Rollback() - if err != nil { // If rollback fails, we're in trouble. - m.log.error(err) - return append(errs, err) - } - continue - } - for _, tag := range metadata.Tags { - - _, err = txn.Exec("INSERT INTO tags(challenge, tag) VALUES (?, ?);", - metadata.Id, - tag) - - if err != nil { - m.log.error(err) - err = txn.Rollback() - if err != nil { // If rollback fails, we're in trouble. - m.log.error(err) - return append(errs, err) - } - break - } - } - if err != nil { - continue - } - - _, err = txn.Exec("DELETE FROM attributes WHERE challenge = ?;", metadata.Id) - - if err != nil { - m.log.error(err) - err = txn.Rollback() - if err != nil { // If rollback fails, we're in trouble. - m.log.error(err) - return append(errs, err) - } - continue - } - for k, v := range metadata.Attributes { - - _, err = txn.Exec("INSERT INTO attributes(challenge, key, value) VALUES (?, ?, ?);", - metadata.Id, - k, - v) - - if err != nil { - m.log.error(err) - err = txn.Rollback() - if err != nil { // If rollback fails, we're in trouble. - m.log.error(err) - return append(errs, err) - } - break - } - } - if err != nil { - continue - } - - _, err = txn.Exec("DELETE FROM hosts WHERE challenge = ?;", metadata.Id) - - if err != nil { - m.log.error(err) - err = txn.Rollback() - if err != nil { // If rollback fails, we're in trouble. - m.log.error(err) - return append(errs, err) - } - continue - } - - for i, host := range metadata.Hosts { - _, err = txn.Exec("INSERT INTO hosts(challenge, name, idx, target) VALUES (?, ?, ?, ?);", - metadata.Id, - host.Name, - i, - host.Target) - - if err != nil { - m.log.error(err) - err = txn.Rollback() - if err != nil { // If rollback fails, we're in trouble. - m.log.error(err) - return append(errs, err) - } - break - } - } - if err != nil { - continue - } - - _, err = txn.Exec("DELETE FROM portNames WHERE challenge = ?;", metadata.Id) - - if err != nil { - m.log.error(err) - err = txn.Rollback() - if err != nil { // If rollback fails, we're in trouble. - m.log.error(err) - return append(errs, err) - } - continue - } - - for k, v := range metadata.PortMap { - _, err = txn.Exec("INSERT INTO portNames(challenge, name, host, port) VALUES (?, ?, ?, ?);", - metadata.Id, - k, - v.Host, - v.Port) - - if err != nil { - m.log.error(err) - err = txn.Rollback() - if err != nil { // If rollback fails, we're in trouble. - m.log.error(err) - return append(errs, err) - } - break - } - } - if err != nil { - continue - } - - // Note: there are currently no network-level challenge options, but they would be updated here if added in the future. - - // _, err = txn.Exec("DELETE FROM networkOptions WHERE challenge = ?;", metadata.Id) - - // if err != nil { - // m.log.error(err) - // err = txn.Rollback() - // if err != nil { // If rollback fails, we're in trouble. - // m.log.error(err) - // return append(errs, err) - // } - // continue - // } - - // _, err = txn.Exec("INSERT INTO networkOptions(challenge) VALUES (?);", - // metadata.Id) - // if err != nil { - // m.log.error(err) - // err = txn.Rollback() - // if err != nil { // If rollback fails, we're in trouble. - // m.log.error(err) - // return append(errs, err) - // } - // } - // if err != nil { - // continue - // } - - _, err = txn.Exec("DELETE FROM containerOptions WHERE challenge = ?;", metadata.Id) - - if err != nil { - m.log.error(err) - err = txn.Rollback() - if err != nil { // If rollback fails, we're in trouble. - m.log.error(err) - return append(errs, err) - } - continue - } - - for host, opts := range metadata.ChallengeOptions.Overrides { - dbOpts, err := opts.toDbContainerOptions() - if err != nil { - m.log.error(err) - err = txn.Rollback() - if err != nil { // If rollback fails, we're in trouble. - m.log.error(err) - return append(errs, err) - } - break - } - _, err = txn.Exec("INSERT INTO containerOptions(challenge, host, init, cpus, memory, ulimits, pidslimit, readonlyrootfs, droppedcaps, nonewprivileges, diskquota, cgroupparent, capimmutable, seccomp) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);", - metadata.Id, - host, - dbOpts.Init, - dbOpts.Cpus, - dbOpts.Memory, - dbOpts.Ulimits, - dbOpts.PidsLimit, - dbOpts.ReadonlyRootfs, - dbOpts.DroppedCaps, - dbOpts.NoNewPrivileges, - dbOpts.DiskQuota, - dbOpts.CgroupParent, - dbOpts.CapImmutable, - dbOpts.Seccomp) - if err != nil { - m.log.error(err) - err = txn.Rollback() - if err != nil { // If rollback fails, we're in trouble. - m.log.error(err) - return append(errs, err) - } - break - } - } - if err != nil { - continue - } - - if err := txn.Commit(); err != nil { // It's undocumented what this means... - m.log.error(err) errs = append(errs, err) continue // next challenge } diff --git a/cmgr/database_operations_test.go b/cmgr/database_operations_test.go index 83e3e7e..4768ca8 100644 --- a/cmgr/database_operations_test.go +++ b/cmgr/database_operations_test.go @@ -3,6 +3,7 @@ package cmgr import ( "encoding/json" "os" + "strings" "testing" "time" @@ -1831,3 +1832,62 @@ func TestLookupChallengeMetadataSurfacesOptionsDecodeError(t *testing.T) { t.Fatal("expected lookupChallengeMetadata to fail on a corrupt seccomp column, got nil error") } } + +// A failed child-row insert used to roll the transaction back and then carry +// on with a nil err: later statements ran on the dead transaction, the real +// error was lost, and the batch was abandoned at the next rollback. +func TestWriteChallengesReportsTheFailureAndContinues(t *testing.T) { + newChallenge := func(id ChallengeId, tag string) *ChallengeMetadata { + return &ChallengeMetadata{ + Id: id, Name: string(id), Namespace: "test", ChallengeType: "custom", Path: "/t/" + string(id), + Tags: []string{tag}, + Hints: []string{"a hint"}, + Hosts: []HostInfo{{Name: "challenge"}}, + PortMap: map[string]PortInfo{}, + ChallengeOptions: ChallengeOptions{Overrides: map[string]ContainerOptions{"": {ReadonlyRootfs: true}}}, + } + } + for _, path := range []string{"add", "update"} { + t.Run(path, func(t *testing.T) { + mgr := setupTestManager(t) + defer mgr.db.Close() + bad, good := newChallenge("test/bad", "fine"), newChallenge("test/good", "fine") + if path == "update" { + if errs := mgr.addChallenges([]*ChallengeMetadata{bad, good}); len(errs) > 0 { + t.Fatalf("seeding failed: %v", errs) + } + } + if _, err := mgr.db.Exec(`CREATE TRIGGER reject_boom BEFORE INSERT ON tags WHEN NEW.tag = 'boom' + BEGIN SELECT RAISE(ABORT, 'tag rejected'); END;`); err != nil { + t.Fatalf("create trigger: %s", err) + } + bad.Tags = []string{"boom"} + good.Tags = []string{"changed"} + + var errs []error + if path == "add" { + errs = mgr.addChallenges([]*ChallengeMetadata{bad, good}) + } else { + errs = mgr.updateChallenges([]*ChallengeMetadata{bad, good}, false, false) + } + if len(errs) != 1 || !strings.Contains(errs[0].Error(), "tag rejected") { + t.Fatalf("errors = %v; want exactly the rejected tag", errs) + } + got, err := mgr.lookupChallengeMetadata(good.Id) + if err != nil || len(got.Tags) != 1 || got.Tags[0] != "changed" { + t.Fatalf("the next challenge was not written: %v, %v", got, err) + } + kept, err := mgr.lookupChallengeMetadata(bad.Id) + switch path { + case "add": + if err == nil { + t.Fatalf("the failed challenge was recorded: %+v", kept) + } + case "update": + if err != nil || len(kept.Tags) != 1 || kept.Tags[0] != "fine" || len(kept.Hints) != 1 { + t.Fatalf("the failed update was not rolled back: %+v, %v", kept, err) + } + } + }) + } +} From d3a7acc437c9daef2bbcf8289a321f6d8237ce2d Mon Sep 17 00:00:00 2001 From: Ivan Liang Date: Tue, 17 Nov 2026 13:43:36 -0500 Subject: [PATCH 05/13] fix(build): keep the served artifact archive in step with the build row executeBuild wrote the new artifact archive straight to the final .tar.gz path and, when validateBuild then failed, removed that path. A failed rebuild leaves the build row at its previous generation, which cmgrd keeps serving, so the archive players were downloading was deleted out from under them and every artifact request turned into a 500 from cmgrd. A build that failed earlier, on a bad metadata.json or a missing flag, left the new archive in place instead, serving files from a build that was never recorded. The new archive is now staged at a dot-prefixed path beside the final one, and served only once the build row that describes it is committed: executeBuild leaves it staged, and its callers rename it into place (promoteArtifacts) after finalizeBuild succeeds. A build that fails, at any point in executeBuild or in finalizeBuild, discards the staged file and leaves the served archive alone. The rename is atomic, so a concurrent download sees the old archive or the new one, never a partial file, and the directory is synced to persist the swap. The staged name ends in .staged, so it never matches a served .tar.gz. Checked against Docker 29.9.3: master deletes .tar.gz when a rebuild fails validation; on this branch the previous archive stays. Backported from cork (CyLabAcademy/challenge-orchestrator) 558a9f9, which staged the archive but promoted it inside executeBuild, before the row was committed, and left it staged on the early failures. --- cmgr/artifacts_test.go | 55 +++++++++++++++++++++++++++++++++++ cmgr/database_challenges.go | 6 +++- cmgr/docker.go | 57 ++++++++++++++++++++++++++++++------- cmgr/types.go | 3 ++ 4 files changed, 110 insertions(+), 11 deletions(-) diff --git a/cmgr/artifacts_test.go b/cmgr/artifacts_test.go index a9b249c..82f32dc 100644 --- a/cmgr/artifacts_test.go +++ b/cmgr/artifacts_test.go @@ -381,3 +381,58 @@ func TestCacheArtifactsBoundsUncountedMetadata(t *testing.T) { t.Fatalf("expected the decompressed-size bound to fire, got: %s", err) } } + +// stageArchive writes content where executeBuild would stage the build's +// archive and records it on the build. +func stageArchive(t *testing.T, m *Manager, build *BuildMetadata, content string) { + t.Helper() + build.stagedArtifacts = filepath.Join(m.artifactsDir, "."+build.getArtifactsFilename()+".staged") + if err := os.WriteFile(build.stagedArtifacts, []byte(content), 0644); err != nil { + t.Fatal(err) + } +} + +func readServed(t *testing.T, m *Manager, build *BuildMetadata) string { + t.Helper() + data, err := os.ReadFile(filepath.Join(m.artifactsDir, build.getArtifactsFilename())) + if os.IsNotExist(err) { + return "" + } else if err != nil { + t.Fatal(err) + } + return string(data) +} + +// The archive a build is served from changes only when its row is recorded: +// promoted after finalizeBuild, discarded when the build is not recorded. +func TestStagedArtifactsPromoteOrDiscard(t *testing.T) { + m := &Manager{log: newLogger(DISABLED), artifactsDir: t.TempDir()} + build := &BuildMetadata{Id: 7, Challenge: "test/artifacts"} + + stageArchive(t, m, build, "generation 1") + if got := readServed(t, m, build); got != "" { + t.Fatalf("a staged archive is served before promotion: %q", got) + } + if err := m.promoteArtifacts(build); err != nil { + t.Fatal(err) + } + if got := readServed(t, m, build); got != "generation 1" { + t.Fatalf("served %q after promotion, want generation 1", got) + } + + stageArchive(t, m, build, "generation 2") + staged := build.stagedArtifacts + m.discardArtifacts(build) + if _, err := os.Stat(staged); !os.IsNotExist(err) { + t.Fatalf("the discarded archive is still on disk: %v", err) + } + if got := readServed(t, m, build); got != "generation 1" { + t.Fatalf("served %q after a discard, want generation 1 untouched", got) + } + if err := m.promoteArtifacts(build); err != nil { + t.Fatal(err) + } + if got := readServed(t, m, build); got != "generation 1" { + t.Fatalf("served %q after promoting nothing, want generation 1", got) + } +} diff --git a/cmgr/database_challenges.go b/cmgr/database_challenges.go index 9b234f5..e144669 100644 --- a/cmgr/database_challenges.go +++ b/cmgr/database_challenges.go @@ -345,12 +345,16 @@ func (m *Manager) updateChallenges(updatedChallenges []*ChallengeMetadata, rebui // retention guarantee. build.PrevChecksum = rotatedPrevChecksum(oldChecksum, build.Checksum, build.PrevChecksum) - // Update database + // Update database, then serve the archive it describes err = m.finalizeBuild(build) if err != nil { + m.discardArtifacts(build) errs = append(errs, err) continue } + if err = m.promoteArtifacts(build); err != nil { + errs = append(errs, err) + } // Stop and tear down existing instances. For persistent (non-on-demand) // instances also restart them with the new image. On-demand (dynamic) diff --git a/cmgr/docker.go b/cmgr/docker.go index 048036b..4f8fbb7 100644 --- a/cmgr/docker.go +++ b/cmgr/docker.go @@ -153,6 +153,36 @@ func (b *BuildMetadata) getArtifactsFilename() string { return fmt.Sprintf("%d.tar.gz", b.Id) } +// promoteArtifacts serves the archive executeBuild staged, once the build row +// that describes it is committed. The rename is atomic: a download gets the +// old archive or the new one, never a partial file. +func (m *Manager) promoteArtifacts(build *BuildMetadata) error { + staged := build.stagedArtifacts + build.stagedArtifacts = "" + if staged == "" { + return nil + } + if err := os.Rename(staged, filepath.Join(m.artifactsDir, build.getArtifactsFilename())); err != nil { + os.Remove(staged) + err = fmt.Errorf("could not promote the artifact archive of %s/%d: %w", build.Challenge, build.Id, err) + m.log.error(err) + return err + } + if directory, err := os.Open(m.artifactsDir); err == nil { + _ = directory.Sync() + _ = directory.Close() + } + return nil +} + +// discardArtifacts drops a staged archive whose build was not recorded. +func (m *Manager) discardArtifacts(build *BuildMetadata) { + if build.stagedArtifacts != "" { + os.Remove(build.stagedArtifacts) + build.stagedArtifacts = "" + } +} + func (i *InstanceMetadata) getNetworkName() string { return fmt.Sprintf("cmgr-%d", i.Id) } @@ -252,6 +282,10 @@ func (m *Manager) generateBuilds(builds []*BuildMetadata) error { err = m.finalizeBuild(build) if err != nil { + m.discardArtifacts(build) + return err + } + if err = m.promoteArtifacts(build); err != nil { return err } } @@ -522,7 +556,15 @@ func (m *Manager) freezeBaseImage(challenge ChallengeId, force bool) error { return nil } -func (m *Manager) executeBuild(cMeta *ChallengeMetadata, bMeta *BuildMetadata, buildCtxFile string) error { +// executeBuild leaves a validated artifact archive staged; the caller +// promotes it once the build row is committed (promoteArtifacts). +func (m *Manager) executeBuild(cMeta *ChallengeMetadata, bMeta *BuildMetadata, buildCtxFile string) (retErr error) { + bMeta.stagedArtifacts = "" + defer func() { + if retErr != nil { + m.discardArtifacts(bMeta) + } + }() seedStr := fmt.Sprintf("%d", bMeta.Seed) @@ -687,13 +729,10 @@ func (m *Manager) executeBuild(cMeta *ChallengeMetadata, bMeta *BuildMetadata, b delete(lookups, "flag") } else if hdr.Name == "challenge/artifacts.tar.gz" { - // cacheArtifacts writes atomically, but to the final build-ID path, - // so a rebuild replaces the prior archive here before the rest of the - // build is validated. Preserving the previous artifact across a failed - // rebuild requires staging the whole build and promoting on success, - // which is deferred to the staged-build work. - artifactsPath := filepath.Join(m.artifactsDir, bMeta.getArtifactsFilename()) - files, err = m.cacheArtifacts(cTar, artifactsPath) + // Staged under a name no served ".tar.gz" can match: the + // previous archive keeps serving until this build is recorded. + bMeta.stagedArtifacts = filepath.Join(m.artifactsDir, "."+bMeta.getArtifactsFilename()+".staged") + files, err = m.cacheArtifacts(cTar, bMeta.stagedArtifacts) if err != nil { m.log.errorf("could not cache artifacts: %s", err) return err @@ -722,8 +761,6 @@ func (m *Manager) executeBuild(cMeta *ChallengeMetadata, bMeta *BuildMetadata, b err = m.validateBuild(cMeta, bMeta, files) if err != nil { - os.Remove(filepath.Join(m.artifactsDir, bMeta.getArtifactsFilename())) - // Free the build image now rather than waiting for the deferred // container cleanup: while the extraction container exists it references // the image, so the non-forced ImageRemove below could not untag it. diff --git a/cmgr/types.go b/cmgr/types.go index ba2439d..9c1d0cb 100644 --- a/cmgr/types.go +++ b/cmgr/types.go @@ -226,6 +226,9 @@ type BuildMetadata struct { Schema string `json:"schema"` InstanceCount int `json:"instance_count"` + + // stagedArtifacts is a validated archive awaiting promoteArtifacts. + stagedArtifacts string } type ImageId int64 From 8e9e83564f723b0594c0697360979f538792425a Mon Sep 17 00:00:00 2001 From: Ivan Liang Date: Tue, 17 Nov 2026 13:43:36 -0500 Subject: [PATCH 06/13] fix(build): stop serving an archive a rebuild no longer publishes A challenge that stops producing artifacts.tar.gz and is rebuilt records has_artifacts false, but nothing removed the previous generation's .tar.gz. cmgrd's artifact handler only returned 404 when the build lookup failed and has_artifacts was false together, so with a successful lookup it went on serving the stale archive, and an artifact server mirroring the directory went on publishing its files. promoteArtifacts now removes the served archive when the build it is recording staged none. The handler answers 404 for an unknown build or one with no artifacts, and 500 for a failed lookup, which it used to answer with 404. Cork serves no artifacts and has no counterpart. --- cmd/cmgrd/main.go | 13 +++++++++++-- cmgr/artifacts_test.go | 21 +++++++++++++++++++-- cmgr/docker.go | 13 ++++++++++--- 3 files changed, 40 insertions(+), 7 deletions(-) diff --git a/cmd/cmgrd/main.go b/cmd/cmgrd/main.go index 9b55644..c1978cf 100644 --- a/cmd/cmgrd/main.go +++ b/cmd/cmgrd/main.go @@ -370,8 +370,17 @@ func (s state) artifactsHandler(w http.ResponseWriter, r *http.Request) { build := cmgr.BuildId(buildInt) meta, err := s.mgr.GetBuildMetadata(build) - _, ok := err.(*cmgr.UnknownIdentifierError) - if ok || (err != nil && !meta.HasArtifacts) { + if _, ok := err.(*cmgr.UnknownIdentifierError); ok { + w.WriteHeader(http.StatusNotFound) + return + } else if err != nil { + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(err.Error())) + return + } + // A build that published nothing has no archive to serve, whatever a + // file of its name holds. + if !meta.HasArtifacts { w.WriteHeader(http.StatusNotFound) return } diff --git a/cmgr/artifacts_test.go b/cmgr/artifacts_test.go index 82f32dc..6bc412c 100644 --- a/cmgr/artifacts_test.go +++ b/cmgr/artifacts_test.go @@ -429,10 +429,27 @@ func TestStagedArtifactsPromoteOrDiscard(t *testing.T) { if got := readServed(t, m, build); got != "generation 1" { t.Fatalf("served %q after a discard, want generation 1 untouched", got) } +} + +// A rebuild that publishes no archive any more must not leave the previous +// generation's archive behind to be served under the build's id. +func TestPromoteArtifactsRemovesADroppedArchive(t *testing.T) { + m := &Manager{log: newLogger(DISABLED), artifactsDir: t.TempDir()} + build := &BuildMetadata{Id: 8, Challenge: "test/artifacts"} + + stageArchive(t, m, build, "generation 1") if err := m.promoteArtifacts(build); err != nil { t.Fatal(err) } - if got := readServed(t, m, build); got != "generation 1" { - t.Fatalf("served %q after promoting nothing, want generation 1", got) + // The next generation produced no archive: nothing was staged. + if err := m.promoteArtifacts(build); err != nil { + t.Fatal(err) + } + if got := readServed(t, m, build); got != "" { + t.Fatalf("served %q after a rebuild without artifacts, want nothing", got) + } + // And a build that never had one is not an error. + if err := m.promoteArtifacts(build); err != nil { + t.Fatalf("promoting nothing over nothing failed: %s", err) } } diff --git a/cmgr/docker.go b/cmgr/docker.go index 4f8fbb7..d217e34 100644 --- a/cmgr/docker.go +++ b/cmgr/docker.go @@ -154,15 +154,22 @@ func (b *BuildMetadata) getArtifactsFilename() string { } // promoteArtifacts serves the archive executeBuild staged, once the build row -// that describes it is committed. The rename is atomic: a download gets the -// old archive or the new one, never a partial file. +// that describes it is committed, or removes the previous one when the build +// produced none. The rename is atomic: a download gets the old archive or the +// new one, never a partial file. func (m *Manager) promoteArtifacts(build *BuildMetadata) error { staged := build.stagedArtifacts build.stagedArtifacts = "" + served := filepath.Join(m.artifactsDir, build.getArtifactsFilename()) if staged == "" { + if err := os.Remove(served); err != nil && !os.IsNotExist(err) { + err = fmt.Errorf("could not remove the artifact archive %s/%d no longer publishes: %w", build.Challenge, build.Id, err) + m.log.error(err) + return err + } return nil } - if err := os.Rename(staged, filepath.Join(m.artifactsDir, build.getArtifactsFilename())); err != nil { + if err := os.Rename(staged, served); err != nil { os.Remove(staged) err = fmt.Errorf("could not promote the artifact archive of %s/%d: %w", build.Challenge, build.Id, err) m.log.error(err) From 56b280b0afeb593a824ebcde3b302fbde8cc5b05 Mon Sep 17 00:00:00 2001 From: Ivan Liang Date: Tue, 17 Nov 2026 13:43:36 -0500 Subject: [PATCH 07/13] fix(db): never reuse an instance id instances.id was an INTEGER PRIMARY KEY without AUTOINCREMENT, so SQLite handed the id of the newest deleted row to the next instance. Every path that deletes a row while something outside cmgrd may still hold its id therefore risked pointing that holder at another user's instance: a stale DELETE /instances/ from the platform tore down whoever had drawn the id since, and a GET reported their ports. The deleted rows are usually the newest ones, hence exactly the next ids handed out; the prune path relied on its delay to make this unlikely. The column is now INTEGER PRIMARY KEY AUTOINCREMENT, so an id is handed out once. An existing database is migrated by the same table rebuild that brought in created_at and is_finalized, which now also runs when the stored declaration lacks AUTOINCREMENT (no ALTER can add it), and seeds sqlite_sequence so the numbering continues above every id handed out: the old high-water mark when the table already had one (DROP TABLE deletes it, so it is read first), otherwise the largest id present. Ids freed before the first migration and above that largest one can be handed out once more; from then on none is. Since every existing database now goes through that rebuild once, its closing foreign-key check is scoped to the tables it touched (instances, portAssignments, containers). It used to check the whole database, so a stale row in any unrelated table would have refused the migration and kept cmgr from starting. Rolling back to an older cmgr is safe: it finds every column it expects and leaves the table, AUTOINCREMENT included, as it is. Checked against Docker 29.9.3: master hands a stopped instance's id to the next launch; on this branch the next launch gets the next id. Backported from cork (CyLabAcademy/challenge-orchestrator) 1ef7502; the high-water mark and the scoped check go beyond it. --- cmgr/database.go | 83 ++++++++--- cmgr/database_operations_test.go | 230 +++++++++++++++++++++++++++++++ 2 files changed, 291 insertions(+), 22 deletions(-) diff --git a/cmgr/database.go b/cmgr/database.go index f1d22b9..a495cf0 100644 --- a/cmgr/database.go +++ b/cmgr/database.go @@ -9,6 +9,7 @@ import ( "os" "reflect" "strconv" + "strings" "time" "github.com/jmoiron/sqlx" @@ -130,8 +131,10 @@ const schemaQuery string = ` ON UPDATE RESTRICT ON DELETE CASCADE ); + -- AUTOINCREMENT: an id is never handed out twice, since front-ends hold + -- ids after cmgr deletes the row. CREATE TABLE IF NOT EXISTS instances ( - id INTEGER PRIMARY KEY, + id INTEGER PRIMARY KEY AUTOINCREMENT, lastsolved INTEGER, build INTEGER NOT NULL, created_at DATETIME DEFAULT CURRENT_TIMESTAMP, @@ -331,7 +334,17 @@ func (m *Manager) initDatabase() error { } staleIsFinalizedDefault := isFinalizedCols > 0 && isFinalizedDefault.String != "0" - if createdAtCols == 0 || isFinalizedCols == 0 || staleIsFinalizedDefault { + // No ALTER adds AUTOINCREMENT, so a table declared without it (the + // stored declaration shows) is rebuilt too. + var instancesSQL string + err = db.QueryRow("SELECT sql FROM sqlite_master WHERE type = 'table' AND name = 'instances';").Scan(&instancesSQL) + if err != nil { + m.log.errorf("could not read the instances table declaration: %s", err) + return err + } + hasAutoincrement := strings.Contains(strings.ToUpper(instancesSQL), "AUTOINCREMENT") + + if createdAtCols == 0 || isFinalizedCols == 0 || staleIsFinalizedDefault || !hasAutoincrement { if err = rebuildInstancesTable(db, createdAtCols > 0, isFinalizedCols > 0); err != nil { m.log.errorf("could not migrate instances table: %s", err) return err @@ -373,7 +386,8 @@ func (m *Manager) initDatabase() error { // schema and copies existing rows across. It migrates databases that predate // the created_at and/or is_finalized columns, which cannot simply be added via // ALTER TABLE ... ADD COLUMN because created_at's DEFAULT CURRENT_TIMESTAMP is a -// non-constant default that SQLite rejects in ADD COLUMN. +// non-constant default that SQLite rejects in ADD COLUMN, and databases whose +// id column lacks AUTOINCREMENT, which no ALTER can add. // // `instances` is the target of ON DELETE CASCADE foreign keys (portAssignments, // containers), so the implicit DELETE that DROP TABLE performs would cascade and @@ -410,7 +424,7 @@ func rebuildInstancesTable(db *sqlx.DB, hasCreatedAt, hasIsFinalized bool) (retE defer tx.Rollback() const createNew = `CREATE TABLE instances_migrate_new ( - id INTEGER PRIMARY KEY, + id INTEGER PRIMARY KEY AUTOINCREMENT, lastsolved INTEGER, build INTEGER NOT NULL, created_at DATETIME DEFAULT CURRENT_TIMESTAMP, @@ -445,6 +459,13 @@ func rebuildInstancesTable(db *sqlx.DB, hasCreatedAt, hasIsFinalized bool) (retE return err } + // A table already declared with AUTOINCREMENT keeps its high-water mark + // in sqlite_sequence, and DROP TABLE deletes that row: read it first. + var prevSeq int64 + if err = tx.QueryRowContext(ctx, "SELECT COALESCE(MAX(seq), 0) FROM sqlite_sequence WHERE name = 'instances';").Scan(&prevSeq); err != nil { + return err + } + if _, err = tx.ExecContext(ctx, "DROP TABLE instances;"); err != nil { return err } @@ -452,6 +473,15 @@ func rebuildInstancesTable(db *sqlx.DB, hasCreatedAt, hasIsFinalized bool) (retE return err } + // Continue the numbering above every id handed out so far: the old + // high-water mark or, for a table without one, the largest id copied. + if _, err = tx.ExecContext(ctx, "DELETE FROM sqlite_sequence WHERE name IN ('instances', 'instances_migrate_new');"); err != nil { + return err + } + if _, err = tx.ExecContext(ctx, "INSERT INTO sqlite_sequence(name, seq) SELECT 'instances', MAX(?, COALESCE(MAX(id), 0)) FROM instances;", prevSeq); err != nil { + return err + } + // Recreate the indexes that were dropped along with the old table. if _, err = tx.ExecContext(ctx, "CREATE INDEX IF NOT EXISTS instanceBuildIndex ON instances(build);"); err != nil { return err @@ -461,40 +491,49 @@ func rebuildInstancesTable(db *sqlx.DB, hasCreatedAt, hasIsFinalized bool) (retE } // Confirm the rebuild left no dangling foreign-key references before - // committing (rows were copied with enforcement off). - rows, err := tx.QueryContext(ctx, "PRAGMA foreign_key_check;") + // committing (rows were copied with enforcement off). Only the tables it + // touched are checked: a stale row elsewhere is not this migration's to + // refuse, and would otherwise keep cmgr from starting. + for _, table := range []string{"instances", "portAssignments", "containers"} { + violation, err := firstForeignKeyViolation(ctx, tx, table) + if err != nil { + return err + } + if violation != "" { + return fmt.Errorf("foreign key check failed after rebuilding instances table: %s", violation) + } + } + + return tx.Commit() +} + +// firstForeignKeyViolation describes the first row of table whose foreign key +// references a missing row, or returns "" when there is none. +func firstForeignKeyViolation(ctx context.Context, tx *sql.Tx, table string) (string, error) { + rows, err := tx.QueryContext(ctx, "PRAGMA foreign_key_check("+table+");") if err != nil { - return err + return "", err } + defer rows.Close() var violation string if rows.Next() { // foreign_key_check yields: table, rowid, parent (referenced table), fkid. var ( - table string + child string rowid sql.NullInt64 parent string fkid int ) - if err = rows.Scan(&table, &rowid, &parent, &fkid); err != nil { - rows.Close() - return err + if err = rows.Scan(&child, &rowid, &parent, &fkid); err != nil { + return "", err } rowidStr := "NULL" if rowid.Valid { rowidStr = strconv.FormatInt(rowid.Int64, 10) } - violation = fmt.Sprintf("row %s in %q references a missing row in %q (fk %d)", rowidStr, table, parent, fkid) - } - if err = rows.Err(); err != nil { - rows.Close() - return err + violation = fmt.Sprintf("row %s in %q references a missing row in %q (fk %d)", rowidStr, child, parent, fkid) } - rows.Close() - if violation != "" { - return fmt.Errorf("foreign key check failed after rebuilding instances table: %s", violation) - } - - return tx.Commit() + return violation, rows.Err() } func (m *Manager) getReversePortMap(id ChallengeId) (map[string]string, error) { diff --git a/cmgr/database_operations_test.go b/cmgr/database_operations_test.go index 4768ca8..9b69a71 100644 --- a/cmgr/database_operations_test.go +++ b/cmgr/database_operations_test.go @@ -3,6 +3,7 @@ package cmgr import ( "encoding/json" "os" + "path/filepath" "strings" "testing" "time" @@ -1712,6 +1713,235 @@ func TestRebuildInstancesTableMigration(t *testing.T) { } } +// instancesDeclaration returns the CREATE TABLE text SQLite keeps for the +// instances table. +func instancesDeclaration(t *testing.T, db *sqlx.DB) string { + t.Helper() + var decl string + if err := db.Get(&decl, "SELECT sql FROM sqlite_master WHERE type = 'table' AND name = 'instances';"); err != nil { + t.Fatalf("read instances declaration: %s", err) + } + return decl +} + +// A database from before ids stopped being reused has every current column +// but no AUTOINCREMENT. The rebuild must add it, keep every row and what +// references it, and continue the numbering, so that the id of a deleted +// instance is never handed out again. +func TestRebuildInstancesTableAddsAutoincrement(t *testing.T) { + dbFile, err := os.CreateTemp("", "cmgr-autoinc-*.db") + if err != nil { + t.Fatalf("failed to create temp file: %s", err) + } + dbFile.Close() + t.Cleanup(func() { removeDBFiles(dbFile.Name()) }) + db, err := sqlx.Open("sqlite3", dbFile.Name()+"?_fk=true&_journal_mode=WAL&_busy_timeout=50&_synchronous=NORMAL") + if err != nil { + t.Fatalf("failed to open db: %s", err) + } + t.Cleanup(func() { db.Close() }) + + const schema = ` + CREATE TABLE builds (id INTEGER PRIMARY KEY); + CREATE TABLE instances ( + id INTEGER PRIMARY KEY, + lastsolved INTEGER, + build INTEGER NOT NULL, + created_at DATETIME DEFAULT CURRENT_TIMESTAMP, + is_finalized INTEGER NOT NULL DEFAULT 0 CHECK(is_finalized IN (0,1)), + FOREIGN KEY (build) REFERENCES builds (id) ON UPDATE RESTRICT ON DELETE RESTRICT + ); + CREATE TABLE portAssignments ( + instance INTEGER NOT NULL, + name TEXT NOT NULL, + port INTEGER NOT NULL, + FOREIGN KEY (instance) REFERENCES instances (id) ON UPDATE RESTRICT ON DELETE CASCADE + ); + CREATE TABLE containers ( + instance INTEGER NOT NULL, + id TEXT NOT NULL PRIMARY KEY, + FOREIGN KEY (instance) REFERENCES instances (id) ON UPDATE RESTRICT ON DELETE CASCADE + ); + INSERT INTO builds(id) VALUES (1); + INSERT INTO instances(id, lastsolved, build) VALUES (1, 0, 1); + INSERT INTO instances(id, lastsolved, build) VALUES (5, 0, 1); + INSERT INTO portAssignments(instance, name, port) VALUES (1, 'challenge', 12345); + INSERT INTO containers(instance, id) VALUES (1, 'deadbeefcafe');` + if _, err := db.Exec(schema); err != nil { + t.Fatalf("failed to create the pre-AUTOINCREMENT schema: %s", err) + } + if strings.Contains(strings.ToUpper(instancesDeclaration(t, db)), "AUTOINCREMENT") { + t.Fatal("fixture already has AUTOINCREMENT") + } + + if err := rebuildInstancesTable(db, true, true); err != nil { + t.Fatalf("rebuildInstancesTable failed: %s", err) + } + if !strings.Contains(strings.ToUpper(instancesDeclaration(t, db)), "AUTOINCREMENT") { + t.Fatal("instances still lacks AUTOINCREMENT after the rebuild") + } + + for _, check := range []struct { + what, query string + want int + }{ + {"instances", "SELECT COUNT(*) FROM instances;", 2}, + {"portAssignment", "SELECT COUNT(*) FROM portAssignments WHERE instance = 1;", 1}, + {"container", "SELECT COUNT(*) FROM containers WHERE instance = 1;", 1}, + } { + var n int + if err := db.Get(&n, check.query); err != nil { + t.Fatalf("%s count: %s", check.what, err) + } + if n != check.want { + t.Errorf("%s rows after the rebuild = %d, want %d", check.what, n, check.want) + } + } + + // The numbering continues past the largest id copied, and the id of a + // deleted instance is not handed out again. + if _, err := db.Exec("DELETE FROM instances WHERE id = 5;"); err != nil { + t.Fatalf("delete instance 5: %s", err) + } + res, err := db.Exec("INSERT INTO instances(lastsolved, build) VALUES (0, 1);") + if err != nil { + t.Fatalf("insert after the rebuild: %s", err) + } + if id, _ := res.LastInsertId(); id != 6 { + t.Fatalf("the instance after the rebuild got id %d, want 6 (5 was deleted and must not come back)", id) + } + if _, err := db.Exec("DELETE FROM instances WHERE id = 6;"); err != nil { + t.Fatalf("delete instance 6: %s", err) + } + res, err = db.Exec("INSERT INTO instances(lastsolved, build) VALUES (0, 1);") + if err != nil { + t.Fatalf("second insert after the rebuild: %s", err) + } + if id, _ := res.LastInsertId(); id != 7 { + t.Fatalf("the next instance got id %d, want 7", id) + } +} + +// initDatabase detects a table declared without AUTOINCREMENT and rebuilds +// it; a fresh database gets it from the schema; a second run changes nothing. +func TestInitDatabaseAddsAutoincrement(t *testing.T) { + dbFile, err := os.CreateTemp("", "cmgr-autoinc-init-*.db") + if err != nil { + t.Fatalf("failed to create temp file: %s", err) + } + dbFile.Close() + t.Cleanup(func() { removeDBFiles(dbFile.Name()) }) + t.Setenv(DB_ENV, dbFile.Name()) + + old := strings.Replace(schemaQuery, "id INTEGER PRIMARY KEY AUTOINCREMENT,", "id INTEGER PRIMARY KEY,", 1) + if old == schemaQuery { + t.Fatal("schemaQuery does not declare instances.id with AUTOINCREMENT") + } + db, err := sqlx.Open("sqlite3", dbFile.Name()+"?_fk=true") + if err != nil { + t.Fatalf("failed to open db: %s", err) + } + if _, err := db.Exec(old); err != nil { + t.Fatalf("failed to create the old schema: %s", err) + } + db.Close() + + for run := 1; run <= 2; run++ { + m := &Manager{log: newLogger(DISABLED)} + if err := m.initDatabase(); err != nil { + t.Fatalf("initDatabase run %d: %s", run, err) + } + decl := instancesDeclaration(t, m.db) + m.db.Close() + if !strings.Contains(strings.ToUpper(decl), "AUTOINCREMENT") { + t.Fatalf("run %d: instances lacks AUTOINCREMENT: %s", run, decl) + } + } + + fresh := &Manager{log: newLogger(DISABLED)} + t.Setenv(DB_ENV, filepath.Join(t.TempDir(), "fresh.db")) + if err := fresh.initDatabase(); err != nil { + t.Fatalf("initDatabase on a fresh database: %s", err) + } + defer fresh.db.Close() + if !strings.Contains(strings.ToUpper(instancesDeclaration(t, fresh.db)), "AUTOINCREMENT") { + t.Fatal("a fresh database lacks AUTOINCREMENT on instances") + } +} + +// openRebuildFixture opens a scratch database holding schema. +func openRebuildFixture(t *testing.T, schema string) *sqlx.DB { + t.Helper() + db, err := sqlx.Open("sqlite3", filepath.Join(t.TempDir(), "rebuild.db")+"?_fk=true") + if err != nil { + t.Fatalf("failed to open db: %s", err) + } + t.Cleanup(func() { db.Close() }) + if _, err := db.Exec(schema); err != nil { + t.Fatalf("failed to create the fixture: %s", err) + } + return db +} + +const rebuildFixtureTables = ` + CREATE TABLE builds (id INTEGER PRIMARY KEY); + CREATE TABLE portAssignments (instance INTEGER NOT NULL, name TEXT NOT NULL, port INTEGER NOT NULL, + FOREIGN KEY (instance) REFERENCES instances (id) ON UPDATE RESTRICT ON DELETE CASCADE); + CREATE TABLE containers (instance INTEGER NOT NULL, id TEXT NOT NULL PRIMARY KEY, + FOREIGN KEY (instance) REFERENCES instances (id) ON UPDATE RESTRICT ON DELETE CASCADE); + INSERT INTO builds(id) VALUES (1);` + +// Rebuilding a table that already has AUTOINCREMENT must keep its high-water +// mark: the newest instance deleted before the rebuild keeps its id retired. +func TestRebuildInstancesTableKeepsTheHighWaterMark(t *testing.T) { + db := openRebuildFixture(t, rebuildFixtureTables+` + CREATE TABLE instances ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + lastsolved INTEGER, + build INTEGER NOT NULL, + created_at DATETIME DEFAULT CURRENT_TIMESTAMP, + is_finalized INTEGER NOT NULL DEFAULT 0 CHECK(is_finalized IN (0,1)), + FOREIGN KEY (build) REFERENCES builds (id) ON UPDATE RESTRICT ON DELETE RESTRICT + ); + INSERT INTO instances(lastsolved, build) VALUES (0, 1), (0, 1), (0, 1); + DELETE FROM instances WHERE id = 3;`) + + if err := rebuildInstancesTable(db, true, true); err != nil { + t.Fatalf("rebuildInstancesTable failed: %s", err) + } + res, err := db.Exec("INSERT INTO instances(lastsolved, build) VALUES (0, 1);") + if err != nil { + t.Fatalf("insert after the rebuild: %s", err) + } + if id, _ := res.LastInsertId(); id != 4 { + t.Fatalf("the instance after the rebuild got id %d, want 4 (3 was handed out before)", id) + } +} + +// The migration checks only the tables it rebuilt: a stale foreign key +// elsewhere is not its to refuse, and refusing it would keep cmgr from starting. +func TestRebuildInstancesTableIgnoresUnrelatedForeignKeys(t *testing.T) { + db := openRebuildFixture(t, rebuildFixtureTables+` + CREATE TABLE instances ( + id INTEGER PRIMARY KEY, + lastsolved INTEGER, + build INTEGER NOT NULL, + created_at DATETIME DEFAULT CURRENT_TIMESTAMP, + is_finalized INTEGER NOT NULL DEFAULT 0 CHECK(is_finalized IN (0,1)), + FOREIGN KEY (build) REFERENCES builds (id) ON UPDATE RESTRICT ON DELETE RESTRICT + ); + CREATE TABLE lookupData (build INTEGER NOT NULL, key TEXT NOT NULL, value TEXT NOT NULL, + FOREIGN KEY (build) REFERENCES builds (id) ON UPDATE RESTRICT ON DELETE CASCADE); + PRAGMA foreign_keys = OFF; + INSERT INTO lookupData(build, key, value) VALUES (99, 'stale', 'row'); + PRAGMA foreign_keys = ON; + INSERT INTO instances(id, lastsolved, build) VALUES (1, 0, 1);`) + + if err := rebuildInstancesTable(db, true, true); err != nil { + t.Fatalf("a stale row in an unrelated table failed the migration: %s", err) + } +} + // TestInitDatabaseRepairsStaleIsFinalizedDefault drives initDatabase against a // database in the buggy intermediate state: created_at and is_finalized both // exist, but is_finalized was added by the old ALTER ... DEFAULT 1 migration. From 6b4d2ae54ab2684db95b020ba7d47039f0a3b4cf Mon Sep 17 00:00:00 2001 From: Ivan Liang Date: Tue, 17 Nov 2026 13:43:36 -0500 Subject: [PATCH 08/13] fix(docker): recover from a stale challenge network when starting an instance The instance network is named cmgr-. A network left on the daemon by an earlier instance with the same id (ids were reused until the previous commit) or by a removal that was cut short made the next start that drew the id fail with "network with name cmgr- already exists"; that failed start's own cleanup removed the network, so the launch after it succeeded, and the player who drew the id got an error in between. On that conflict, remove the stale network and create it once more; a removal that finds it already gone goes on to the create. A network that still has containers attached refuses removal, and the launch fails as before with both errors reported. A launch that failed before creating its network (a port it could not reserve, or the network create itself) used to clean up through stopInstance, which removes the network of that name: not this launch's, since it created none. With live endpoints the removal failed, and the launch's row was left behind half-made; without them, it removed a network another daemon user had just created. It now drops only its own row (dropFailedLaunch). Found when another run on the same daemon held cmgr-5. The name is all a leftover is known by, so two cmgr databases sharing a daemon can still meet on one, as they already collided on master; that setup needs distinct network names, which this does not attempt. Checked against Docker 29.9.3 with cmgr- created by hand: master fails the launch; on this branch it logs the warning and the launch gets that id. Backported from cork (CyLabAcademy/challenge-orchestrator) 6c33afb. --- cmgr/api.go | 13 +++++++++++-- cmgr/docker.go | 11 +++++++++++ 2 files changed, 22 insertions(+), 2 deletions(-) diff --git a/cmgr/api.go b/cmgr/api.go index 64a9e01..4ad3b54 100644 --- a/cmgr/api.go +++ b/cmgr/api.go @@ -300,7 +300,7 @@ func (m *Manager) newInstance(build *BuildMetadata, envVars map[string]string) ( portName := revPortMap[portStr] hostPort, err := m.reservePort(iMeta.Id, portName) if err != nil { - m.stopInstance(iMeta) + m.dropFailedLaunch(iMeta.Id) return 0, err } iMeta.Ports[portName] = hostPort @@ -310,7 +310,7 @@ func (m *Manager) newInstance(build *BuildMetadata, envVars map[string]string) ( err = m.startNetwork(iMeta, cMeta.ChallengeOptions.NetworkOptions) if err != nil { - m.stopInstance(iMeta) + m.dropFailedLaunch(iMeta.Id) return 0, err } @@ -344,6 +344,15 @@ func (m *Manager) Stop(instance InstanceId) error { return m.stopInstance(iMeta) } +// dropFailedLaunch removes the record of a launch that failed before it +// created its network, so a network of that name is not its to remove. The +// port reservations go with the row. +func (m *Manager) dropFailedLaunch(instance InstanceId) { + if err := m.removeInstanceMetadata(instance); err != nil { + m.log.errorf("could not remove the record of failed launch %d: %s", instance, err) + } +} + func (m *Manager) stopInstance(instance *InstanceMetadata) error { err := m.stopContainers(instance) if err != nil { diff --git a/cmgr/docker.go b/cmgr/docker.go index d217e34..9b862aa 100644 --- a/cmgr/docker.go +++ b/cmgr/docker.go @@ -804,6 +804,17 @@ func (m *Manager) startNetwork(instance *InstanceMetadata, opts NetworkOptions) } netname := instance.getNetworkName() _, err := m.cli.NetworkCreate(m.ctx, netname, netSpec) + if errdefs.IsConflict(err) { + // A leftover of an earlier instance with this id: remove it and create + // again. One with endpoints still attached refuses removal. + m.log.warnf("stale challenge network %s already exists; removing it and retrying", netname) + _, rmErr := m.cli.NetworkRemove(m.ctx, netname, client.NetworkRemoveOptions{}) + if rmErr != nil && !errdefs.IsNotFound(rmErr) { + err = fmt.Errorf("%w (stale network not removed: %w)", err, rmErr) + } else { + _, err = m.cli.NetworkCreate(m.ctx, netname, netSpec) + } + } if err != nil { m.log.errorf("could not create challenge network (%s): %s", netname, err) } From 4d3294b9c01e30fffa448f476efc91f269b59a4d Mon Sep 17 00:00:00 2001 From: Ivan Liang Date: Tue, 17 Nov 2026 13:43:37 -0500 Subject: [PATCH 09/13] fix(update): keep persistent instances on their ports across a rebuild With CMGR_PORTS set, the rebuild path in updateChallenges lost an instance's host ports: stopContainers deletes the instance's port assignments, the restart then handed docker host port 0, and the port docker picked was never persisted because finalizeInstance only records read-back ports when no range is configured. The restarted container ended up on an ephemeral port outside the range, and the API reported no port for the instance, leaving a front-end no port to give players. reassignPorts now runs before the in-place restart. It re-claims each port's previous number when that is still free and inside the range (so players keep the address they were given), and reserves a fresh one from the range otherwise. The atomic INSERT ... WHERE NOT EXISTS is split out of reservePort as claimPort so both share it. A published port with no name in the reverse map is an error rather than a reservation under "". A failure part-way through reassignPorts releases what it had reserved, and a restart that fails after it (the network or the containers) is rolled back: containers created so far and the network are removed and the port reservations released, so a failed restart no longer holds numbers in CMGR_PORTS. The instance row stays, as it did before. Checked against Docker 29.9.3 with CMGR_PORTS=42000-42050: on master the rebuilt instance came back on 0.0.0.0:32768 with no recorded port; on this branch it keeps 42020 and serves the new build there. Backported from cork (CyLabAcademy/challenge-orchestrator) 6db2ec6, 862eb3d and 5100601. --- cmgr/database_challenges.go | 12 +++ cmgr/database_instances.go | 100 +++++++++++++++++++--- cmgr/database_operations_test.go | 138 +++++++++++++++++++++++++++++++ cmgr/docker.go | 12 +-- 4 files changed, 242 insertions(+), 20 deletions(-) diff --git a/cmgr/database_challenges.go b/cmgr/database_challenges.go index e144669..ccac942 100644 --- a/cmgr/database_challenges.go +++ b/cmgr/database_challenges.go @@ -374,18 +374,27 @@ func (m *Manager) updateChallenges(updatedChallenges []*ChallengeMetadata, rebui } for _, iid := range instances { instance, err := m.lookupInstanceMetadata(iid) + found := err == nil if err == nil && !cMeta.NeedsInstance() { if err = m.stopInstance(instance); err != nil { errs = append(errs, err) } continue } + // stopContainers releases the port assignments; the + // restart below reclaims them (same numbers when free) + // so the instance keeps its address across the rebuild. + var previousPorts map[string]int if err == nil { + previousPorts = instance.Ports err = m.stopContainers(instance) } if err == nil { err = m.stopNetwork(instance) } + if err == nil && build.InstanceCount != DYNAMIC_INSTANCES { + err = m.reassignPorts(build, instance, revPortMap, previousPorts) + } if err == nil && build.InstanceCount != DYNAMIC_INSTANCES { err = m.startNetwork(instance, cMeta.ChallengeOptions.NetworkOptions) } @@ -394,6 +403,9 @@ func (m *Manager) updateChallenges(updatedChallenges []*ChallengeMetadata, rebui } if err != nil { errs = append(errs, err) + if found && build.InstanceCount != DYNAMIC_INSTANCES { + m.rollbackRestart(instance) + } } } diff --git a/cmgr/database_instances.go b/cmgr/database_instances.go index 5ef299d..1708bf0 100644 --- a/cmgr/database_instances.go +++ b/cmgr/database_instances.go @@ -38,21 +38,11 @@ func (m *Manager) reservePort(instance InstanceId, name string) (int, error) { return 0, fmt.Errorf("All ports between %d and %d are in use", m.portLow, m.portHigh) } - // Atomic claim: INSERT ... SELECT ... WHERE NOT EXISTS - query := `INSERT INTO portAssignments(instance, name, port) - SELECT ?, ?, ? - WHERE NOT EXISTS (SELECT 1 FROM portAssignments WHERE port = ?);` - res, err := m.db.Exec(query, instance, name, candidate, candidate) + claimed, err := m.claimPort(instance, name, candidate) if err != nil { return 0, err } - - rowsAffected, err := res.RowsAffected() - if err != nil { - return 0, err - } - - if rowsAffected == 1 { + if claimed { return candidate, nil } // Collision — mark this port as used in the local bitset and retry @@ -63,6 +53,92 @@ func (m *Manager) reservePort(instance InstanceId, name string) (int, error) { return 0, fmt.Errorf("failed to reserve a port after 50 attempts due to high contention") } +// claimPort records the given host port for the instance if nobody else +// holds it. The INSERT ... WHERE NOT EXISTS is the atomic check-and-claim +// reservePort relies on under concurrent launches. +func (m *Manager) claimPort(instance InstanceId, name string, port int) (bool, error) { + query := `INSERT INTO portAssignments(instance, name, port) + SELECT ?, ?, ? + WHERE NOT EXISTS (SELECT 1 FROM portAssignments WHERE port = ?);` + res, err := m.db.Exec(query, instance, name, port, port) + if err != nil { + return false, err + } + rowsAffected, err := res.RowsAffected() + if err != nil { + return false, err + } + return rowsAffected == 1, nil +} + +// reassignPorts reserves the ports of an instance restarted in place, which +// stopContainers released: each keeps its previous number while that is free +// and in range, so players keep their address. A failure releases them all. +// No-op without a port range, where Docker picks the ports. +func (m *Manager) reassignPorts(build *BuildMetadata, instance *InstanceMetadata, revPortMap map[string]string, previous map[string]int) error { + if m.portLow == 0 { + return nil + } + instance.Ports = make(map[string]int) + err := m.reassignPortsUnchecked(build, instance, revPortMap, previous) + if err != nil { + m.releasePorts(instance) + } + return err +} + +func (m *Manager) reassignPortsUnchecked(build *BuildMetadata, instance *InstanceMetadata, revPortMap map[string]string, previous map[string]int) error { + for _, image := range build.Images { + if image.Host == "builder" { + continue + } + for _, portStr := range image.Ports { + name, ok := revPortMap[portStr] + if !ok || name == "" { + return fmt.Errorf("no published port name for %s of instance %d", portStr, instance.Id) + } + if prev, ok := previous[name]; ok && prev >= m.portLow && prev <= m.portHigh { + claimed, err := m.claimPort(instance.Id, name, prev) + if err != nil { + return err + } + if claimed { + instance.Ports[name] = prev + continue + } + m.log.warnf("port %d of instance %d was taken during its restart; assigning a new one", prev, instance.Id) + } + port, err := m.reservePort(instance.Id, name) + if err != nil { + return err + } + instance.Ports[name] = port + } + } + return nil +} + +// rollbackRestart removes what a failed in-place restart brought up and the +// ports it held, keeping the instance row. Its own errors are only logged. +func (m *Manager) rollbackRestart(instance *InstanceMetadata) { + if err := m.stopContainers(instance); err != nil { + m.log.warnf("could not remove the containers of instance %d after its failed restart: %s", instance.Id, err) + } + if err := m.stopNetwork(instance); err != nil { + m.log.warnf("could not remove the network of instance %d after its failed restart: %s", instance.Id, err) + } + m.releasePorts(instance) +} + +// releasePorts drops every port assignment recorded for the instance, both +// in the database and on the metadata. +func (m *Manager) releasePorts(instance *InstanceMetadata) { + if _, err := m.db.Exec("DELETE FROM portAssignments WHERE instance=?;", instance.Id); err != nil { + m.log.errorf("failed to release the ports of instance %d: %s", instance.Id, err) + } + instance.Ports = make(map[string]int) +} + func (m *Manager) openInstance(meta *InstanceMetadata) error { res, err := m.db.NamedExec("INSERT INTO instances(build, lastsolved) VALUES (:build, :lastsolved);", meta) diff --git a/cmgr/database_operations_test.go b/cmgr/database_operations_test.go index 9b69a71..3e41cf5 100644 --- a/cmgr/database_operations_test.go +++ b/cmgr/database_operations_test.go @@ -2121,3 +2121,141 @@ func TestWriteChallengesReportsTheFailureAndContinues(t *testing.T) { }) } } + +// TestReassignPortsKeepsAddressAcrossRestart covers the rebuild path with a +// port range configured: after stopContainers released an instance's ports, +// reassignPorts must claim them again (the same numbers while free, a fresh +// one from the range otherwise) and persist them, so the restarted containers +// bind inside CMGR_PORTS and the API keeps reporting the port. +func TestReassignPortsKeepsAddressAcrossRestart(t *testing.T) { + mgr := setupTestManager(t) + defer mgr.db.Close() + mgr.portLow = 30000 + mgr.portHigh = 30010 + + challenge := &ChallengeMetadata{ + Id: "test/restart", Name: "Restart", Namespace: "t", ChallengeType: "custom", Description: "d", Path: "/t/p", + Hosts: []HostInfo{{Name: "challenge"}}, + PortMap: map[string]PortInfo{"http": {Host: "challenge", Port: 8000}}, + ChallengeOptions: ChallengeOptions{Overrides: map[string]ContainerOptions{"": {}}}, + } + if errs := mgr.addChallenges([]*ChallengeMetadata{challenge}); len(errs) > 0 { + t.Fatalf("failed to add challenge: %v", errs) + } + build := &BuildMetadata{Seed: 1, Format: "flag{%s}", Challenge: challenge.Id, Schema: "s", InstanceCount: 1} + if err := mgr.openBuild(build); err != nil { + t.Fatalf("failed to open build: %v", err) + } + build.Images = []Image{{Host: "challenge", Ports: []string{"8000/tcp"}}} + revPortMap := map[string]string{"8000/tcp": "http"} + + instance := &InstanceMetadata{Build: build.Id, Ports: map[string]int{}} + if err := mgr.openInstance(instance); err != nil { + t.Fatalf("failed to open instance: %v", err) + } + port, err := mgr.reservePort(instance.Id, "http") + if err != nil { + t.Fatalf("failed to reserve the initial port: %v", err) + } + instance.Ports["http"] = port + + // The rebuild path: containers (and with them the port rows) go away, + // then the instance is restarted in place. + previous := instance.Ports + if err := mgr.removeContainersMetadata(instance); err != nil { + t.Fatalf("failed to release container metadata: %v", err) + } + if len(instance.Ports) != 0 { + t.Fatalf("expected the ports to be released, got %v", instance.Ports) + } + if err := mgr.reassignPorts(build, instance, revPortMap, previous); err != nil { + t.Fatalf("reassignPorts failed: %v", err) + } + if instance.Ports["http"] != port { + t.Errorf("expected the instance to keep port %d, got %d", port, instance.Ports["http"]) + } + stored, err := mgr.lookupInstanceMetadata(instance.Id) + if err != nil { + t.Fatalf("failed to look up the instance: %v", err) + } + if stored.Ports["http"] != port { + t.Errorf("expected the reassigned port %d to be persisted, got %v", port, stored.Ports) + } + + // If another launch grabbed the number meanwhile, a fresh one from the + // range is assigned instead of failing or colliding. + if err := mgr.removeContainersMetadata(instance); err != nil { + t.Fatalf("failed to release container metadata: %v", err) + } + other := &InstanceMetadata{Build: build.Id, Ports: map[string]int{}} + if err := mgr.openInstance(other); err != nil { + t.Fatalf("failed to open the competing instance: %v", err) + } + if claimed, err := mgr.claimPort(other.Id, "http", port); err != nil || !claimed { + t.Fatalf("competing instance could not take port %d: claimed=%v err=%v", port, claimed, err) + } + if err := mgr.reassignPorts(build, instance, revPortMap, previous); err != nil { + t.Fatalf("reassignPorts after a collision failed: %v", err) + } + got := instance.Ports["http"] + if got == port || got < mgr.portLow || got > mgr.portHigh { + t.Errorf("expected a different port inside %d-%d, got %d", mgr.portLow, mgr.portHigh, got) + } + + rowsFor := func(id InstanceId) int { + var n int + if err := mgr.db.Get(&n, "SELECT COUNT(*) FROM portAssignments WHERE instance = ?", id); err != nil { + t.Fatalf("failed to count port assignments: %v", err) + } + return n + } + + // A previous port outside the current range (an instance from before + // CMGR_PORTS was set) is not reclaimed; a fresh one from the range is. + if err := mgr.removeContainersMetadata(instance); err != nil { + t.Fatalf("failed to release container metadata: %v", err) + } + if err := mgr.reassignPorts(build, instance, revPortMap, map[string]int{"http": 45000}); err != nil { + t.Fatalf("reassignPorts with an out-of-range previous port failed: %v", err) + } + if got := instance.Ports["http"]; got < mgr.portLow || got > mgr.portHigh { + t.Errorf("expected a port inside %d-%d, got %d", mgr.portLow, mgr.portHigh, got) + } + + // A published port with no name in the reverse map is an error, and + // nothing is left reserved under an empty name. + if err := mgr.removeContainersMetadata(instance); err != nil { + t.Fatalf("failed to release container metadata: %v", err) + } + if err := mgr.reassignPorts(build, instance, map[string]string{}, previous); err == nil { + t.Errorf("expected an error for a port missing from the reverse map") + } + if n := rowsFor(instance.Id); n != 0 { + t.Errorf("expected no port assignments after the failed reassignment, found %d", n) + } + + // A failure part-way through (here: the range is exhausted after the + // first port) releases the ports already reserved for the instance. + twoPorts := &BuildMetadata{Id: build.Id, Images: []Image{{Host: "challenge", Ports: []string{"8000/tcp", "8001/tcp"}}}} + twoNames := map[string]string{"8000/tcp": "http", "8001/tcp": "ssh"} + mgr.portLow, mgr.portHigh = 31000, 31000 + if err := mgr.reassignPorts(twoPorts, instance, twoNames, nil); err == nil { + t.Errorf("expected an error when the range cannot hold both ports") + } + if n := rowsFor(instance.Id); n != 0 { + t.Errorf("expected the partial reservation to be rolled back, found %d assignment(s)", n) + } + if len(instance.Ports) != 0 { + t.Errorf("expected instance.Ports to be cleared after the rollback, got %v", instance.Ports) + } + + // Without a port range nothing is reserved: docker picks and the + // read-back records it. + mgr.portLow = 0 + if err := mgr.reassignPorts(build, instance, revPortMap, previous); err != nil { + t.Fatalf("reassignPorts without a port range failed: %v", err) + } + if n := rowsFor(instance.Id); n != 0 { + t.Errorf("expected no reservation without a port range, found %d", n) + } +} diff --git a/cmgr/docker.go b/cmgr/docker.go index 9b862aa..1802689 100644 --- a/cmgr/docker.go +++ b/cmgr/docker.go @@ -835,14 +835,10 @@ func (m *Manager) stopNetwork(instance *InstanceMetadata) error { return err } -// portsAlreadyKnown reports whether every published port for an image already has -// a non-zero host port reserved in ports, so the post-start read-back in -// startContainers can be safely skipped. It is false when explicit ports are -// disabled (portLow == 0, Docker assigns ephemeral ports) or when any required -// port is unassigned — e.g. the rebuild flow, which clears instance.Ports before -// restarting and so must read the bound port back. A port whose name is missing -// from revPortMap is treated as unknown (false): without a resolvable name we -// cannot confirm its reservation, and must not skip the read-back. +// portsAlreadyKnown reports whether every published port for an image already +// has a host port reserved in ports, so startContainers can skip reading the +// bound ports back. Never without a port range, where Docker picks them, nor +// for a port missing from revPortMap, whose reservation cannot be confirmed. func portsAlreadyKnown(portLow int, imagePorts []string, ports map[string]int, revPortMap map[string]string) bool { if portLow == 0 { return false From 8129c2151dd19e6029fa0220d13d303bd3e3de65 Mon Sep 17 00:00:00 2001 From: Ivan Liang Date: Tue, 17 Nov 2026 13:43:37 -0500 Subject: [PATCH 10/13] fix(update): remove on-demand instances on rebuild instead of leaving hollow records On update, the on-demand instances of a rebuilt build were torn down but their rows stayed behind with no containers and no ports: GET still answered 200, with no address, until a stop from the front-end or the prune age cleared them. They cannot be restarted, since the user_id and env of the original POST are not retained, so they now go through stopInstance and are removed entirely: GET and DELETE answer 404 (the platform already treats a 404 on DELETE as stopped) and the front-end re-issues POST /builds/ for the ones it still wants. A failed instance lookup now skips the instance outright, rather than carrying the empty metadata the lookup returns into a loop where every later step had to check err to leave it alone. A row that has not finalized is skipped too. cmgrd launches while `cmgr update` rebuilds, and such a row belongs to a launch still in flight: stopping it would delete the row under that launch, taking its container rows with it by cascade, and the launch would fail on a foreign key. It finishes on the generation it read; a crashed one is reclaimed by the unfinalized-launch cleanup. For a persistent build the update logs a warning naming the instance, which may come up on the previous build. A warning and not an error: the cleanup runs only when something launches, so a crashed persistent launch would otherwise fail every update, skipping its removals and stopping `cmgr test`, until a player happened to launch. Persistent launches come from schema operations, which take no lock against `cmgr update` in another process, and a schema converge can also launch from build metadata it read before the rebuild, which no scan sees; the README now says not to run the two together. A lock across processes is left for later. Checked against Docker 29.9.3: on master two on-demand records survived the rebuild with "ports": null; on this branch none do. Backported from cork (CyLabAcademy/challenge-orchestrator) b5a6825. --- README.md | 17 ++++++++++----- cmgr/database_challenges.go | 43 +++++++++++++++++++++---------------- 2 files changed, 36 insertions(+), 24 deletions(-) diff --git a/README.md b/README.md index f5c8301..1c0e6b8 100644 --- a/README.md +++ b/README.md @@ -177,11 +177,18 @@ In multi-container challenges, the `user_id` and all `env` variables are propaga equally to **every** container in the build — there is no per-container filtering. **Note:** When a build is rebuilt, its on-demand instances (those launched via -`POST /builds/`) are torn down but **not** restarted, since the original -`user_id` and `env` payload are not retained. Front-ends that automate rebuilds -must re-issue `POST /builds/` with the appropriate runtime configuration to -bring those instances back up. Persistent (schema-managed) instances are -restarted automatically as before. +`POST /builds/`) are stopped and removed, **not** restarted, since the +original `user_id` and `env` payload are not retained; a `GET` or `DELETE` on +one of them afterwards is a 404. Front-ends that automate rebuilds must re-issue +`POST /builds/` with the appropriate runtime configuration to bring those +instances back up. Persistent (schema-managed) instances are restarted +automatically as before. + +**Note:** Do not run a schema operation (`add-schema`, `update-schema`, +`remove-schema`, or their cmgrd endpoints) at the same time as `cmgr update`. +Nothing serializes the two across processes, so an instance a schema operation +launches while `update` rebuilds its build can come up on the previous build; +`update` logs a warning for any it finds still launching. **Note:** Challenge metadata includes a derived `delivery_type` field (`"service"`, `"artifact_only"`, or `"flag_only"`) describing what competitors diff --git a/cmgr/database_challenges.go b/cmgr/database_challenges.go index ccac942..3b3cab9 100644 --- a/cmgr/database_challenges.go +++ b/cmgr/database_challenges.go @@ -356,12 +356,9 @@ func (m *Manager) updateChallenges(updatedChallenges []*ChallengeMetadata, rebui errs = append(errs, err) } - // Stop and tear down existing instances. For persistent (non-on-demand) - // instances also restart them with the new image. On-demand (dynamic) - // instances are started per-user with injected env vars, so they are - // only torn down here and not restarted. Non-service challenges never - // run instances, so any found here are placeholders left by older - // versions of cmgr and are removed entirely. + // Persistent instances restart in place on the new images. On-demand + // ones cannot (their launch env is not kept), so they are removed + // and the front-end relaunches; so are any of a non-service challenge. revPortMap, err := m.getReversePortMap(build.Challenge) if err != nil { errs = append(errs, err) @@ -374,8 +371,21 @@ func (m *Manager) updateChallenges(updatedChallenges []*ChallengeMetadata, rebui } for _, iid := range instances { instance, err := m.lookupInstanceMetadata(iid) - found := err == nil - if err == nil && !cMeta.NeedsInstance() { + if err != nil { + errs = append(errs, err) + continue + } + // An unfinalized row is a launch in flight, or a crashed one the + // prune will remove: stopping it would delete the row under a live + // launch. Warned, not an error, since a crashed one never goes away + // by running update again. + if !instance.IsFinalized { + if build.InstanceCount != DYNAMIC_INSTANCES { + m.log.warnf("instance %d of build %d had not finished launching when the build was rebuilt; if it is running, it may be on the previous build", instance.Id, build.Id) + } + continue + } + if build.InstanceCount == DYNAMIC_INSTANCES || !cMeta.NeedsInstance() { if err = m.stopInstance(instance); err != nil { errs = append(errs, err) } @@ -384,28 +394,23 @@ func (m *Manager) updateChallenges(updatedChallenges []*ChallengeMetadata, rebui // stopContainers releases the port assignments; the // restart below reclaims them (same numbers when free) // so the instance keeps its address across the rebuild. - var previousPorts map[string]int - if err == nil { - previousPorts = instance.Ports - err = m.stopContainers(instance) - } + previousPorts := instance.Ports + err = m.stopContainers(instance) if err == nil { err = m.stopNetwork(instance) } - if err == nil && build.InstanceCount != DYNAMIC_INSTANCES { + if err == nil { err = m.reassignPorts(build, instance, revPortMap, previousPorts) } - if err == nil && build.InstanceCount != DYNAMIC_INSTANCES { + if err == nil { err = m.startNetwork(instance, cMeta.ChallengeOptions.NetworkOptions) } - if err == nil && build.InstanceCount != DYNAMIC_INSTANCES { + if err == nil { err = m.startContainers(build, instance, cMeta.ChallengeOptions.Overrides, nil, revPortMap) } if err != nil { errs = append(errs, err) - if found && build.InstanceCount != DYNAMIC_INSTANCES { - m.rollbackRestart(instance) - } + m.rollbackRestart(instance) } } From 04f665d46e6080bfbf037898d0067d910c0dfac7 Mon Sep 17 00:00:00 2001 From: Ivan Liang Date: Tue, 17 Nov 2026 13:43:37 -0500 Subject: [PATCH 11/13] fix(loader): report every validation problem, not just the last validateBuild assigned over its error rather than joining, and it did so at three levels: several bad references in one field collapsed to the last, each field overwrote the one before it, and the published-but-unreferenced sweeps run last and so reported over whatever the reference checks had found. A challenge that both named a missing artifact and published an unused one was told only about the unused file, never the typo that usually causes both. An author fixed one mistake, rebuilt, and was shown the next. Collect every problem and return errors.Join. Sort the map keys before reporting them: the sweeps ranged over their maps, so which problem the author saw -- and now the order they arrive in -- depended on map iteration and differed run to run. validateMetadata, which checks the challenge itself before any build, had the same habit with its own lastErr: a challenge with no name, a bad namespace and a {{server}} in its description was told only that {{server}} was an unrecognized template string, the last of four checks to fail. It now reports every problem it finds as well. An error can now carry several lines, so the CLI's numbered error lists indent continuation lines under the entry they belong to rather than leaving them flush against the margin. Checked against Docker 29.9.3 with a rebuild that both references a missing artifact and publishes an unused one: master reports only the unused file; on this branch both problems are listed. Backported from cork (CyLabAcademy/challenge-orchestrator) 40403d0. --- cmd/cmgr/challenges.go | 12 +- cmgr/loader.go | 113 +++++++-------- cmgr/validate_build_test.go | 274 ++++++++++++++++++++++++++++++++++++ 3 files changed, 341 insertions(+), 58 deletions(-) create mode 100644 cmgr/validate_build_test.go diff --git a/cmd/cmgr/challenges.go b/cmd/cmgr/challenges.go index 48ce429..2ea8b32 100644 --- a/cmd/cmgr/challenges.go +++ b/cmd/cmgr/challenges.go @@ -375,11 +375,19 @@ func printChanges(status *cmgr.ChallengeUpdates, verbose bool) { if len(status.Errors) != 0 { fmt.Println("Errors:") for idx, err := range status.Errors { - fmt.Printf(" %d) %s\n", idx+1, err) + fmt.Printf(" %d) %s\n", idx+1, indentContinuation(fmt.Sprint(err), " ")) } } } +// indentContinuation lines the later lines of a multi-line message up under +// the first. A single error can report several problems at once +// (validateBuild returns every one it found, joined); without this all but +// the first sit flush against the margin. +func indentContinuation(msg, indent string) string { + return strings.ReplaceAll(strings.TrimRight(msg, "\n"), "\n", "\n"+indent) +} + // getMetaByDir returns the unmodified challenges under dir and whether the // lookup succeeded. ok is false when errors occurred or the database is out of // sync (both already reported to the user); callers must not treat that as an @@ -401,7 +409,7 @@ func getMetaByDir(m *cmgr.Manager, dir string) ([]*cmgr.ChallengeMetadata, bool) if len(cu.Errors) > 0 { fmt.Println("error: errors occurred during execution:") for i, err := range cu.Errors { - fmt.Printf(" %d) %s\n", i+1, err) + fmt.Printf(" %d) %s\n", i+1, indentContinuation(fmt.Sprint(err), " ")) } return nil, false } diff --git a/cmgr/loader.go b/cmgr/loader.go index bb3f81e..da039ba 100644 --- a/cmgr/loader.go +++ b/cmgr/loader.go @@ -1,11 +1,14 @@ package cmgr import ( + "errors" "fmt" "io/ioutil" + "maps" "os" "path/filepath" "regexp" + "slices" "strconv" "strings" @@ -120,18 +123,24 @@ const shortLinkAsRePattern string = `\{\{\s*link_as\(["']` + urlPathPattern + `[ var shortLinkAsRe *regexp.Regexp = regexp.MustCompile(shortLinkAsRePattern) func (m *Manager) validateMetadata(md *ChallengeMetadata) error { + // Every problem is reported, so an author with several sees them all. + var problems []error + note := func(err error) error { + problems = append(problems, err) + return err + } var lastErr error // Require a challenge name if md.Name == "" { - lastErr = fmt.Errorf("challenge file missing name: %s", md.Path) + lastErr = note(fmt.Errorf("challenge file missing name: %s", md.Path)) m.log.error(lastErr) } // Validate Namespace re := regexp.MustCompile(`^([a-z0-9]+(/[a-z0-9]+)*)?$`) if !re.MatchString(md.Namespace) { - lastErr = fmt.Errorf("invalid namespace (limited to lowercase letters, numerals, and '/') of '%s': %s", - md.Namespace, md.Path) + lastErr = note(fmt.Errorf("invalid namespace (limited to lowercase letters, numerals, and '/') of '%s': %s", + md.Namespace, md.Path)) m.log.error(lastErr) } @@ -139,42 +148,42 @@ func (m *Manager) validateMetadata(md *ChallengeMetadata) error { // picoCTF fork customization: allow template strings not involving connection information in the description section templates := httpBaseRe.FindAllString(md.Description, -1) if len(templates) > 0 { - lastErr = fmt.Errorf("'http_base' template strings not allowed in the 'description' field, but found: %s", strings.Join(templates, ", ")) + lastErr = note(fmt.Errorf("'http_base' template strings not allowed in the 'description' field, but found: %s", strings.Join(templates, ", "))) m.log.error(lastErr) } templates = shortHttpBaseRe.FindAllString(md.Description, -1) if len(templates) > 0 { - lastErr = fmt.Errorf("'http_base' template strings not allowed in the 'description' field, but found: %s", strings.Join(templates, ", ")) + lastErr = note(fmt.Errorf("'http_base' template strings not allowed in the 'description' field, but found: %s", strings.Join(templates, ", "))) m.log.error(lastErr) } templates = portRe.FindAllString(md.Description, -1) if len(templates) > 0 { - lastErr = fmt.Errorf("'port' template strings not allowed in the 'description' field, but found: %s", strings.Join(templates, ", ")) + lastErr = note(fmt.Errorf("'port' template strings not allowed in the 'description' field, but found: %s", strings.Join(templates, ", "))) m.log.error(lastErr) } templates = shortPortRe.FindAllString(md.Description, -1) if len(templates) > 0 { - lastErr = fmt.Errorf("'port' template strings not allowed in the 'description' field, but found: %s", strings.Join(templates, ", ")) + lastErr = note(fmt.Errorf("'port' template strings not allowed in the 'description' field, but found: %s", strings.Join(templates, ", "))) m.log.error(lastErr) } templates = serverRe.FindAllString(md.Description, -1) if len(templates) > 0 { - lastErr = fmt.Errorf("'server' template strings not allowed in the 'description' field, but found: %s", strings.Join(templates, ", ")) + lastErr = note(fmt.Errorf("'server' template strings not allowed in the 'description' field, but found: %s", strings.Join(templates, ", "))) m.log.error(lastErr) } templates = shortServerRe.FindAllString(md.Description, -1) if len(templates) > 0 { - lastErr = fmt.Errorf("'server' template strings not allowed in the 'description' field, but found: %s", strings.Join(templates, ", ")) + lastErr = note(fmt.Errorf("'server' template strings not allowed in the 'description' field, but found: %s", strings.Join(templates, ", "))) m.log.error(lastErr) } templates = linkRe.FindAllString(md.Description, -1) if len(templates) > 0 { - lastErr = fmt.Errorf("'link' template strings not allowed in the 'description' field, but found: %s", strings.Join(templates, ", ")) + lastErr = note(fmt.Errorf("'link' template strings not allowed in the 'description' field, but found: %s", strings.Join(templates, ", "))) m.log.error(lastErr) } templates = shortLinkRe.FindAllString(md.Description, -1) if len(templates) > 0 { - lastErr = fmt.Errorf("'link' template strings not allowed in the 'description' field, but found: %s", strings.Join(templates, ", ")) + lastErr = note(fmt.Errorf("'link' template strings not allowed in the 'description' field, but found: %s", strings.Join(templates, ", "))) m.log.error(lastErr) } @@ -301,13 +310,13 @@ func (m *Manager) validateMetadata(md *ChallengeMetadata) error { res, err := normalizeAndCheckTemplated(md.Description) if err != nil { - lastErr = err + lastErr = note(err) } md.Description = res res, err = normalizeAndCheckTemplated(md.Details) if err != nil { - lastErr = err + lastErr = note(err) } md.Details = res @@ -315,7 +324,7 @@ func (m *Manager) validateMetadata(md *ChallengeMetadata) error { res, err = normalizeAndCheckTemplated(hint) if err != nil { - lastErr = err + lastErr = note(err) } md.Hints[i] = res @@ -323,7 +332,7 @@ func (m *Manager) validateMetadata(md *ChallengeMetadata) error { for port, used := range refPort { if !used { - lastErr = fmt.Errorf("port '%s' published but not referenced: %s", port, md.Path) + lastErr = note(fmt.Errorf("port '%s' published but not referenced: %s", port, md.Path)) m.log.error(lastErr) } } @@ -337,7 +346,7 @@ func (m *Manager) validateMetadata(md *ChallengeMetadata) error { if opts.Seccomp != nil { if err := opts.Seccomp.resolve(md.Path); err != nil { - lastErr = fmt.Errorf("%s%s", hostStr, err) + lastErr = note(fmt.Errorf("%s%s", hostStr, err)) m.log.error(lastErr) } } @@ -345,7 +354,7 @@ func (m *Manager) validateMetadata(md *ChallengeMetadata) error { if opts.Cpus != "" { _, err := parseNanoCPUs(opts.Cpus) if err != nil { - lastErr = fmt.Errorf("%serror parsing cpus container option: %v", hostStr, err) + lastErr = note(fmt.Errorf("%serror parsing cpus container option: %v", hostStr, err)) m.log.error(lastErr) } } @@ -353,7 +362,7 @@ func (m *Manager) validateMetadata(md *ChallengeMetadata) error { if opts.Memory != "" { _, err = units.RAMInBytes(opts.Memory) if err != nil { - lastErr = fmt.Errorf("%serror parsing memory container option: %v", hostStr, err) + lastErr = note(fmt.Errorf("%serror parsing memory container option: %v", hostStr, err)) m.log.error(lastErr) } } @@ -361,18 +370,18 @@ func (m *Manager) validateMetadata(md *ChallengeMetadata) error { for _, ulimit := range opts.Ulimits { limit, err := units.ParseUlimit(ulimit) if err != nil { - lastErr = fmt.Errorf("%serror parsing ulimits container option: %v", hostStr, err) + lastErr = note(fmt.Errorf("%serror parsing ulimits container option: %v", hostStr, err)) m.log.error(lastErr) } // See https://docs.docker.com/engine/reference/commandline/run/#set-ulimits-in-container---ulimit if limit.Name == "nproc" { - lastErr = fmt.Errorf("%snproc ulimits are not supported, use the pidslimit container option instead", hostStr) + lastErr = note(fmt.Errorf("%snproc ulimits are not supported, use the pidslimit container option instead", hostStr)) m.log.error(lastErr) } } if opts.PidsLimit < -1 { - lastErr = fmt.Errorf("%sinvalid pidslimit container option (must be >= -1)", hostStr) + lastErr = note(fmt.Errorf("%sinvalid pidslimit container option (must be >= -1)", hostStr)) m.log.error(lastErr) } @@ -396,7 +405,7 @@ func (m *Manager) validateMetadata(md *ChallengeMetadata) error { for _, cap := range opts.DroppedCaps { if _, ok := droppable_capabilities[cap]; !ok { if _, ok = droppable_capabilities[fmt.Sprintf("CAP_%s", cap)]; !ok { - lastErr = fmt.Errorf("%sinvalid DroppedCaps container option: %s", hostStr, cap) + lastErr = note(fmt.Errorf("%sinvalid DroppedCaps container option: %s", hostStr, cap)) m.log.error(lastErr) } } @@ -405,13 +414,13 @@ func (m *Manager) validateMetadata(md *ChallengeMetadata) error { if opts.DiskQuota != "" { _, err := units.RAMInBytes(opts.DiskQuota) // Despite its name, Docker uses this method to parse the size= storage option. if err != nil { - lastErr = fmt.Errorf("%serror parsing DiskQuota container option: %v", hostStr, err) + lastErr = note(fmt.Errorf("%serror parsing DiskQuota container option: %v", hostStr, err)) m.log.error(lastErr) } } } - return lastErr + return errors.Join(problems...) } func (m *Manager) validateBuild(cMeta *ChallengeMetadata, md *BuildMetadata, files []string) error { @@ -427,14 +436,19 @@ func (m *Manager) validateBuild(cMeta *ChallengeMetadata, md *BuildMetadata, fil } m.log.debugf("lookups: %#v", refLookup) - checkTemplated := func(s string) error { - var err error + // Every problem is reported, so an author with two mistakes sees both. + var problems []error + report := func(format string, args ...interface{}) { + err := fmt.Errorf(format, args...) + m.log.error(err) + problems = append(problems, err) + } + + checkTemplated := func(s string) { fileRefs := urlRe.FindAllStringSubmatch(s, -1) for _, ref := range fileRefs { - _, ok := refFile[ref[1]] - if !ok { - err = fmt.Errorf("unknown artifact '%s' referenced with '%s': %s/%d", ref[1], ref[0], md.Challenge, md.Id) - m.log.error(err) + if _, ok := refFile[ref[1]]; !ok { + report("unknown artifact '%s' referenced with '%s': %s/%d", ref[1], ref[0], md.Challenge, md.Id) } else { refFile[ref[1]] = true } @@ -442,44 +456,31 @@ func (m *Manager) validateBuild(cMeta *ChallengeMetadata, md *BuildMetadata, fil lookupRefs := lookupRe.FindAllStringSubmatch(s, -1) for _, ref := range lookupRefs { - _, ok := refLookup[ref[1]] - if !ok { - err = fmt.Errorf("unknown lookup key of '%s' referenced with '%s': %s/%d", ref[1], ref[0], md.Challenge, md.Id) - m.log.error(err) + if _, ok := refLookup[ref[1]]; !ok { + report("unknown lookup key of '%s' referenced with '%s': %s/%d", ref[1], ref[0], md.Challenge, md.Id) } else { refLookup[ref[1]] = true } } - - return err } // Validate templated fields - err := checkTemplated(cMeta.Description) - detailsErr := checkTemplated(cMeta.Details) - if detailsErr != nil { - err = detailsErr - } - + checkTemplated(cMeta.Description) + checkTemplated(cMeta.Details) for _, hint := range cMeta.Hints { - tmpErr := checkTemplated(hint) - - if tmpErr != nil { - err = tmpErr - } + checkTemplated(hint) } - for f, used := range refFile { - if !used { - err = fmt.Errorf("artifact file '%s' published but not referenced: %s/%d", f, md.Challenge, md.Id) - m.log.error(err) + // Sorted, so the same challenge reports its problems in the same order. + for _, f := range slices.Sorted(maps.Keys(refFile)) { + if !refFile[f] { + report("artifact file '%s' published but not referenced: %s/%d", f, md.Challenge, md.Id) } } - for key, used := range refLookup { - if !used { - err = fmt.Errorf("lookup value '%s' published but not referenced: %s/%d", key, md.Challenge, md.Id) - m.log.error(err) + for _, key := range slices.Sorted(maps.Keys(refLookup)) { + if !refLookup[key] { + report("lookup value '%s' published but not referenced: %s/%d", key, md.Challenge, md.Id) } } @@ -494,7 +495,7 @@ func (m *Manager) validateBuild(cMeta *ChallengeMetadata, md *BuildMetadata, fil m.log.warnf("challenge publishes no ports and produces no artifacts (missing a '# PUBLISH' directive? if intentional, use the 'flag-only' type): %s/%d", md.Challenge, md.Id) } - return err + return errors.Join(problems...) } // Validates the challenge metadata for compliance with expectations diff --git a/cmgr/validate_build_test.go b/cmgr/validate_build_test.go new file mode 100644 index 0000000..37b9f3a --- /dev/null +++ b/cmgr/validate_build_test.go @@ -0,0 +1,274 @@ +package cmgr + +import ( + "strings" + "testing" +) + +// validateBuild is the gate on a challenge's templated text: every artifact +// and lookup key it names must exist, and everything it publishes must be +// named by something. These assert on the offender each message names +// rather than on whole messages. + +func buildFixture(lookups map[string]string) (*ChallengeMetadata, *BuildMetadata) { + cMeta := &ChallengeMetadata{ + Id: ChallengeId("example/challenge"), + DeliveryType: DeliveryService, + } + bMeta := &BuildMetadata{ + Id: BuildId(1), + Challenge: ChallengeId("example/challenge"), + LookupData: lookups, + } + return cMeta, bMeta +} + +// The clean case: every artifact and lookup key is referenced exactly once, +// across all three templated fields. +func TestValidateBuildAcceptsFullyReferenced(t *testing.T) { + m := newTestManager() + cMeta, bMeta := buildFixture(map[string]string{"port": "1337", "host": "example.org"}) + cMeta.Description = `Download {{url("handout.zip")}} and connect to {{lookup("host")}}.` + cMeta.Details = `The service listens on {{lookup("port")}}.` + cMeta.Hints = []string{`Start with {{url("hint.txt")}}.`} + + if err := m.validateBuild(cMeta, bMeta, []string{"handout.zip", "hint.txt"}); err != nil { + t.Fatalf("unexpected error: %v", err) + } +} + +// A challenge with no templating and nothing published is valid; the loader +// reaches here for every build, not only templated ones. +func TestValidateBuildAcceptsNothingTemplated(t *testing.T) { + m := newTestManager() + cMeta, bMeta := buildFixture(nil) + cMeta.Description = "A plain description with no references." + + if err := m.validateBuild(cMeta, bMeta, nil); err != nil { + t.Fatalf("unexpected error: %v", err) + } +} + +// Naming an artifact the build does not produce is the typo case: the player +// would be handed a dead link. +func TestValidateBuildRejectsUnknownArtifact(t *testing.T) { + m := newTestManager() + cMeta, bMeta := buildFixture(nil) + cMeta.Description = `Download {{url("handout.zip")}}.` + + err := m.validateBuild(cMeta, bMeta, nil) + if err == nil { + t.Fatal("expected an error naming the unknown artifact") + } + if !strings.Contains(err.Error(), "handout.zip") { + t.Fatalf("error does not name the bad reference: %v", err) + } +} + +// Same for a lookup key the build never recorded: the template would render +// empty rather than fail at solve time. +func TestValidateBuildRejectsUnknownLookup(t *testing.T) { + m := newTestManager() + cMeta, bMeta := buildFixture(nil) + cMeta.Description = `Connect to {{lookup("hostname")}}.` + + err := m.validateBuild(cMeta, bMeta, nil) + if err == nil { + t.Fatal("expected an error naming the unknown lookup key") + } + if !strings.Contains(err.Error(), "hostname") { + t.Fatalf("error does not name the bad reference: %v", err) + } +} + +// The other direction: publishing an artifact nothing references means the +// player is never told it exists, which is usually a forgotten reference. +func TestValidateBuildRejectsUnreferencedArtifact(t *testing.T) { + m := newTestManager() + cMeta, bMeta := buildFixture(nil) + cMeta.Description = "No references here." + + err := m.validateBuild(cMeta, bMeta, []string{"orphan.zip"}) + if err == nil { + t.Fatal("expected an error for the unreferenced artifact") + } + if !strings.Contains(err.Error(), "orphan.zip") { + t.Fatalf("error does not name the unreferenced artifact: %v", err) + } +} + +// An unreferenced lookup value is the same mistake in the lookup map. +func TestValidateBuildRejectsUnreferencedLookup(t *testing.T) { + m := newTestManager() + cMeta, bMeta := buildFixture(map[string]string{"unused": "value"}) + cMeta.Description = "No references here." + + err := m.validateBuild(cMeta, bMeta, nil) + if err == nil { + t.Fatal("expected an error for the unreferenced lookup value") + } + if !strings.Contains(err.Error(), "unused") { + t.Fatalf("error does not name the unreferenced lookup: %v", err) + } +} + +// References are collected from the details and the hints, not only the +// description, so an artifact named solely in a hint counts as used. +func TestValidateBuildCountsReferencesInHintsAndDetails(t *testing.T) { + m := newTestManager() + + cMeta, bMeta := buildFixture(nil) + cMeta.Details = `See {{url("only-in-details.zip")}}.` + if err := m.validateBuild(cMeta, bMeta, []string{"only-in-details.zip"}); err != nil { + t.Fatalf("a reference in the details did not count: %v", err) + } + + cMeta, bMeta = buildFixture(nil) + cMeta.Hints = []string{`See {{url("only-in-hint.zip")}}.`} + if err := m.validateBuild(cMeta, bMeta, []string{"only-in-hint.zip"}); err != nil { + t.Fatalf("a reference in a hint did not count: %v", err) + } +} + +// A bad reference in any one field fails the build even when the fields +// checked after it are clean: the later checks must not overwrite the verdict +// with a nil. +func TestValidateBuildDoesNotLoseAnEarlierFailure(t *testing.T) { + m := newTestManager() + + // Bad description, clean details and hint. + cMeta, bMeta := buildFixture(nil) + cMeta.Description = `Download {{url("missing.zip")}}.` + cMeta.Details = `Nothing templated here.` + cMeta.Hints = []string{"Nor here."} + if err := m.validateBuild(cMeta, bMeta, nil); err == nil { + t.Fatal("a bad description was lost behind the clean fields after it") + } + + // Bad hint, clean description and details. + cMeta, bMeta = buildFixture(nil) + cMeta.Description = "Nothing templated here." + cMeta.Hints = []string{`See {{url("missing.zip")}}.`, "Nothing templated here."} + if err := m.validateBuild(cMeta, bMeta, nil); err == nil { + t.Fatal("a bad hint was lost behind the clean hint after it") + } +} + +// An artifact-only challenge that produces no artifacts hands the player +// nothing, but existing content still legitimately builds this way, so it +// warns rather than fails. Pinned because the comment marks it as a future +// hard error: this test says what has to change with it. +func TestValidateBuildOnlyWarnsForInertArtifactOnly(t *testing.T) { + m := newTestManager() + cMeta, bMeta := buildFixture(nil) + cMeta.DeliveryType = DeliveryArtifactOnly + cMeta.Description = "A description and nothing else." + + if err := m.validateBuild(cMeta, bMeta, nil); err != nil { + t.Fatalf("an inert artifact-only challenge should warn, not fail: %v", err) + } +} + +// A challenge with more than one mistake reports all of them. The sweeps for +// published-but-unreferenced entries run after the reference checks, and used +// to report over whatever those had found: a challenge that both named a +// missing 'handout.zip' and published an unused 'handout.tar.gz' failed with a +// message about the unused file alone, saying nothing about the typo that was +// the likelier cause of both. +func TestValidateBuildReportsEveryProblem(t *testing.T) { + m := newTestManager() + cMeta, bMeta := buildFixture(map[string]string{"unused_key": "v"}) + cMeta.Description = `Download {{url("handout.zip")}} and connect to {{lookup("missing_key")}}.` + + err := m.validateBuild(cMeta, bMeta, []string{"handout.tar.gz"}) + if err == nil { + t.Fatal("expected the build to fail") + } + + for _, want := range []string{ + "handout.zip", // referenced, never produced + "missing_key", // referenced, never recorded + "handout.tar.gz", // produced, never referenced + "unused_key", // recorded, never referenced + } { + if !strings.Contains(err.Error(), want) { + t.Errorf("no mention of %q in:\n%s", want, err) + } + } +} + +// Every bad reference in a single field is reported, not just the last one. +func TestValidateBuildReportsEveryBadReferenceInOneField(t *testing.T) { + m := newTestManager() + cMeta, bMeta := buildFixture(nil) + cMeta.Description = `Take {{url("one.zip")}}, {{url("two.zip")}} and {{url("three.zip")}}.` + + err := m.validateBuild(cMeta, bMeta, nil) + if err == nil { + t.Fatal("expected the build to fail") + } + for _, want := range []string{"one.zip", "two.zip", "three.zip"} { + if !strings.Contains(err.Error(), want) { + t.Errorf("no mention of %q in:\n%s", want, err) + } + } +} + +// The unreferenced sweeps range over maps, so the message used to depend on +// map iteration order: the same challenge gave a different error run to run. +// Sorting the keys makes a failure reproducible and diffable. +func TestValidateBuildProblemOrderIsStable(t *testing.T) { + m := newTestManager() + published := []string{"delta.zip", "alpha.zip", "charlie.zip", "bravo.zip"} + + cMeta, bMeta := buildFixture(nil) + first := m.validateBuild(cMeta, bMeta, published) + if first == nil { + t.Fatal("expected the unreferenced artifacts to fail the build") + } + + // Same inputs, fresh maps, many times over: Go deliberately randomizes map + // iteration, so a dependence on it shows up within a few rounds. + for i := 0; i < 50; i++ { + cMeta, bMeta := buildFixture(nil) + if got := m.validateBuild(cMeta, bMeta, published); got.Error() != first.Error() { + t.Fatalf("round %d differed:\n first: %s\n got: %s", i, first, got) + } + } + + // Sorted, so alpha is named before bravo before charlie before delta. + msg := first.Error() + prev := -1 + for _, name := range []string{"alpha.zip", "bravo.zip", "charlie.zip", "delta.zip"} { + at := strings.Index(msg, name) + if at < 0 { + t.Fatalf("no mention of %q in:\n%s", name, msg) + } + if at < prev { + t.Fatalf("%q is out of order in:\n%s", name, msg) + } + prev = at + } +} + +// validateMetadata used to keep only its last problem, so an author with two +// was told about one. +func TestValidateMetadataReportsEveryProblem(t *testing.T) { + m := newTestManager() + md := &ChallengeMetadata{ + Id: ChallengeId("Bad Space/x"), + Namespace: "Bad Space", + ChallengeType: "custom", + Path: "/t/problem.md", + Description: "A {{server}} reference where it is not allowed.", + } + err := m.validateMetadata(md) + if err == nil { + t.Fatal("expected validation to fail") + } + for _, want := range []string{"missing name", "invalid namespace", "'server' template strings not allowed"} { + if !strings.Contains(err.Error(), want) { + t.Errorf("error does not mention %q:\n%s", want, err) + } + } +} From 2e5403b6cac9022d36de84c647616c5f7883904f Mon Sep 17 00:00:00 2001 From: Ivan Liang Date: Tue, 17 Nov 2026 13:43:37 -0500 Subject: [PATCH 12/13] fix(docker): name the challenge a build or artifact failure belongs to A failed build reported only docker's half of the story: failed to build image: process "/bin/sh -c make main" did not complete successfully: exit code: 2 which is the same sentence for every challenge of a type. An update or schema deploy across many challenges that hit a handful of those left nothing to act on but a re-run with --verbose, reading the `creating image` debug line above each one. cMeta and bMeta are both in scope, so the build error now carries the challenge id, build id and seed, and the two errors above it the challenge and build ids. The same goes for an artifact archive that fails its checks ("artifact \"source.tar.gz\" is ... bytes" is a name dozens of challenges could produce), and for the matching errors of the freeze base-image build and of the solver image build, which have no counterpart in cork. Backported from cork (CyLabAcademy/challenge-orchestrator) b117683 and 7e41858. --- cmgr/docker.go | 18 +++++++++++------- cmgr/solver_framework.go | 6 +++--- 2 files changed, 14 insertions(+), 10 deletions(-) diff --git a/cmgr/docker.go b/cmgr/docker.go index 1802689..d5db734 100644 --- a/cmgr/docker.go +++ b/cmgr/docker.go @@ -518,7 +518,7 @@ func (m *Manager) freezeBaseImage(challenge ChallengeId, force bool) error { m.log.debugf("creating base image %s", imageName) resp, err := m.cli.ImageBuild(m.ctx, buildCtx, opts) if err != nil { - m.log.errorf("failed to build base image: %s", err) + m.log.errorf("failed to build base image for %s: %s", cMeta.Id, err) return err } @@ -526,13 +526,13 @@ func (m *Manager) freezeBaseImage(challenge ChallengeId, force bool) error { messages, err := ioutil.ReadAll(resp.Body) resp.Body.Close() if err != nil { - m.log.errorf("failed to read build response from docker: %s", err) + m.log.errorf("failed to read build response from docker for %s: %s", cMeta.Id, err) return err } // Search the response for an error message if streamErr := dockerStreamError(messages); streamErr != nil { - err = fmt.Errorf("failed to build image: %s", streamErr) + err = fmt.Errorf("failed to build base image for %s: %s", cMeta.Id, streamErr) m.log.error(err) return err } @@ -640,19 +640,23 @@ func (m *Manager) executeBuild(cMeta *ChallengeMetadata, bMeta *BuildMetadata, b m.log.debugf("creating image %s", imageName) resp, err := m.cli.ImageBuild(m.ctx, buildCtx, opts) if err != nil { - m.log.errorf("failed to build base image: %s", err) + m.log.errorf("failed to build base image for %s/%d: %s", cMeta.Id, bMeta.Id, err) return err } messages, err := ioutil.ReadAll(resp.Body) resp.Body.Close() if err != nil { - m.log.errorf("failed to read build response from docker: %s", err) + m.log.errorf("failed to read build response from docker for %s/%d: %s", cMeta.Id, bMeta.Id, err) return err } + // Named, because docker's half of this failure says only which RUN + // step exited non-zero, the same sentence for every challenge of a + // type; without the ids, finding the failed ones means a re-run. if streamErr := dockerStreamError(messages); streamErr != nil { - err = fmt.Errorf("failed to build image: %s", streamErr) + err = fmt.Errorf("failed to build image for %s (build %d, seed %d): %s", + cMeta.Id, bMeta.Id, bMeta.Seed, streamErr) m.log.error(err) return err } @@ -741,7 +745,7 @@ func (m *Manager) executeBuild(cMeta *ChallengeMetadata, bMeta *BuildMetadata, b bMeta.stagedArtifacts = filepath.Join(m.artifactsDir, "."+bMeta.getArtifactsFilename()+".staged") files, err = m.cacheArtifacts(cTar, bMeta.stagedArtifacts) if err != nil { - m.log.errorf("could not cache artifacts: %s", err) + m.log.errorf("could not cache artifacts for %s (build %d, seed %d): %s", cMeta.Id, bMeta.Id, bMeta.Seed, err) return err } for _, name := range files { diff --git a/cmgr/solver_framework.go b/cmgr/solver_framework.go index d0b1cdc..da7b0fb 100644 --- a/cmgr/solver_framework.go +++ b/cmgr/solver_framework.go @@ -112,19 +112,19 @@ func (m *Manager) executeSolver(cMeta *ChallengeMetadata, bMeta *BuildMetadata, // Build the base image (will run the solver) resp, err := m.cli.ImageBuild(m.ctx, solveCtx, opts) if err != nil { - m.log.errorf("failed to build solver image: %s", err) + m.log.errorf("failed to build solver image for %s/%d: %s", cMeta.Id, bMeta.Id, err) return err } messages, err := ioutil.ReadAll(resp.Body) resp.Body.Close() if err != nil { - m.log.errorf("failed to read build response from docker: %s", err) + m.log.errorf("failed to read solver build response from docker for %s/%d: %s", cMeta.Id, bMeta.Id, err) return err } if streamErr := dockerStreamError(messages); streamErr != nil { - err = fmt.Errorf("failed to build image: %s", streamErr) + err = fmt.Errorf("failed to build solver image for %s (build %d): %s", cMeta.Id, bMeta.Id, streamErr) m.log.error(err) return err } From 71e4edb552c741313e678bf18012f333971a6823 Mon Sep 17 00:00:00 2001 From: Ivan Liang Date: Tue, 17 Nov 2026 13:43:38 -0500 Subject: [PATCH 13/13] test(ci): exercise the update and launch lifecycle against docker `cmgr test` builds each example, solves it and destroys it, once. Nothing in CI ever rebuilt a challenge, relaunched an instance or recycled an id, so every merge stayed green while seven bugs in exactly those paths were present (the fixes earlier on this branch). ci/lifecycle/lifecycle.sh drives a cmgr binary through them on the runner's docker daemon, with two busybox challenges and two schemas: - a challenge's own seccomp profile with '=' in it reaches its container - a stopped instance's id is not handed out again - a launch whose cmgr- network was left behind still starts - a persistent instance keeps its CMGR_PORTS port across a rebuild and serves the new build - a rebuild removes the on-demand instances' records - a rebuild that fails validation leaves the served archive in place - and reports every problem it found It works in a temporary directory, cleans up its schemas on exit, and exits non-zero if any check fails. It needs docker, jq and curl, all on the hosted runners, and host ports 42000-42050. Checked against Docker 29.9.3: a master binary fails all seven checks, this branch passes all seven, in about 20 seconds either way, with CMGR_LOGGING at warn and at debug. --- .github/workflows/go.yml | 5 + ci/lifecycle/challenges/sec/Dockerfile | 10 ++ ci/lifecycle/challenges/sec/problem.md | 22 ++++ ci/lifecycle/challenges/web/Dockerfile | 12 ++ ci/lifecycle/challenges/web/problem.md | 14 +++ ci/lifecycle/challenges/web/version.txt | 1 + ci/lifecycle/dyn.yaml | 6 + ci/lifecycle/lifecycle.sh | 148 ++++++++++++++++++++++++ ci/lifecycle/persist.yaml | 9 ++ 9 files changed, 227 insertions(+) create mode 100644 ci/lifecycle/challenges/sec/Dockerfile create mode 100644 ci/lifecycle/challenges/sec/problem.md create mode 100644 ci/lifecycle/challenges/web/Dockerfile create mode 100644 ci/lifecycle/challenges/web/problem.md create mode 100644 ci/lifecycle/challenges/web/version.txt create mode 100644 ci/lifecycle/dyn.yaml create mode 100755 ci/lifecycle/lifecycle.sh create mode 100644 ci/lifecycle/persist.yaml diff --git a/.github/workflows/go.yml b/.github/workflows/go.yml index 8d6c386..40bb71e 100644 --- a/.github/workflows/go.yml +++ b/.github/workflows/go.yml @@ -75,3 +75,8 @@ jobs: # (BuildKit cache starts empty) vs the master baseline without the flag. - name: Integration Tests run: CMGR_DIR=examples CMGR_ARTIFACT_DIR=artifacts bin/cmgr test --require-solve --keep-images examples + + # Rebuilds, relaunches and their failure paths, which the step above never + # reaches: it builds, solves and destroys each example once. + - name: Lifecycle Tests + run: bash ci/lifecycle/lifecycle.sh bin/cmgr diff --git a/ci/lifecycle/challenges/sec/Dockerfile b/ci/lifecycle/challenges/sec/Dockerfile new file mode 100644 index 0000000..a8f3ff4 --- /dev/null +++ b/ci/lifecycle/challenges/sec/Dockerfile @@ -0,0 +1,10 @@ +FROM busybox:1.36 AS base +RUN mkdir /challenge /www + +FROM base AS challenge +ARG FLAG +RUN echo "{\"flag\":\"$FLAG\"}" > /challenge/metadata.json && echo sec > /www/index.html +CMD ["httpd", "-f", "-p", "4242", "-h", "/www"] + +EXPOSE 4242 +# PUBLISH 4242 AS http diff --git a/ci/lifecycle/challenges/sec/problem.md b/ci/lifecycle/challenges/sec/problem.md new file mode 100644 index 0000000..aad4ff1 --- /dev/null +++ b/ci/lifecycle/challenges/sec/problem.md @@ -0,0 +1,22 @@ +# sec + +- Namespace: lifecycle +- Type: custom +- Category: Test +- Points: 1 + +## Description + +A service under its own seccomp profile, which lifecycle.sh writes beside +this file at run time. + +## Details + +Visit `{{server}}:{{port}}`. + +## Challenge Options + +```yaml +seccomp: + profile: profile.json +``` diff --git a/ci/lifecycle/challenges/web/Dockerfile b/ci/lifecycle/challenges/web/Dockerfile new file mode 100644 index 0000000..4f5d871 --- /dev/null +++ b/ci/lifecycle/challenges/web/Dockerfile @@ -0,0 +1,12 @@ +FROM busybox:1.36 AS base +RUN mkdir /challenge /www + +FROM base AS challenge +ARG FLAG +COPY version.txt /www/index.html +RUN echo "{\"flag\":\"$FLAG\"}" > /challenge/metadata.json +RUN echo "notes" > /notes.txt && tar czf /challenge/artifacts.tar.gz -C / notes.txt +CMD ["httpd", "-f", "-p", "4242", "-h", "/www"] + +EXPOSE 4242 +# PUBLISH 4242 AS http diff --git a/ci/lifecycle/challenges/web/problem.md b/ci/lifecycle/challenges/web/problem.md new file mode 100644 index 0000000..17bfbe3 --- /dev/null +++ b/ci/lifecycle/challenges/web/problem.md @@ -0,0 +1,14 @@ +# web + +- Namespace: lifecycle +- Type: custom +- Category: Test +- Points: 1 + +## Description + +Read the {{url_for('notes.txt', 'notes')}}. + +## Details + +Visit `{{server}}:{{port}}`. diff --git a/ci/lifecycle/challenges/web/version.txt b/ci/lifecycle/challenges/web/version.txt new file mode 100644 index 0000000..626799f --- /dev/null +++ b/ci/lifecycle/challenges/web/version.txt @@ -0,0 +1 @@ +v1 diff --git a/ci/lifecycle/dyn.yaml b/ci/lifecycle/dyn.yaml new file mode 100644 index 0000000..96e5e2a --- /dev/null +++ b/ci/lifecycle/dyn.yaml @@ -0,0 +1,6 @@ +name: dyn +flag_format: dyn{%s} +challenges: + lifecycle/web: + seeds: [2] + instance_count: -1 diff --git a/ci/lifecycle/lifecycle.sh b/ci/lifecycle/lifecycle.sh new file mode 100755 index 0000000..120b4aa --- /dev/null +++ b/ci/lifecycle/lifecycle.sh @@ -0,0 +1,148 @@ +#!/usr/bin/env bash +# Lifecycle test: drives cmgr through launches, rebuilds and their failure +# paths on a real docker daemon. `cmgr test` builds, solves and destroys each +# example once; nothing there ever rebuilds or relaunches. +# +# usage: ci/lifecycle/lifecycle.sh +# Needs docker, jq and curl, and host ports 42000-42050 free. Exits non-zero +# if any check fails. +set -u + +if [ $# -ne 1 ] || [ ! -x "$1" ]; then + echo "usage: $0 " >&2 + exit 2 +fi +BIN=$(cd "$(dirname "$1")" && pwd)/$(basename "$1") +HERE=$(cd "$(dirname "$0")" && pwd) +REPO=$(cd "$HERE/../.." && pwd) +WORK=$(mktemp -d) + +unset CMGR_REGISTRY CMGR_REGISTRY_USER CMGR_REGISTRY_TOKEN +export CMGR_DB=$WORK/cmgr.db CMGR_DIR=$WORK/challenges CMGR_ARTIFACT_DIR=$WORK/artifacts +export CMGR_PORTS=42000-42050 CMGR_LOGGING=${CMGR_LOGGING:-warn} + +checks=0 +failures=0 +pass() { checks=$((checks + 1)); echo "PASS: $*"; } +fail() { checks=$((checks + 1)); failures=$((failures + 1)); echo "FAIL: $*"; } +cm() { "$BIN" "$@" 2>>"$WORK/cmgr.log"; } +instance_id() { sed -n 's/^Instance ID: \([0-9][0-9]*\)$/\1/p'; } +field() { jq -r "$2" <<<"$1"; } + +# serves : the service answers with body within ten seconds. +serves() { + local i + for i in $(seq 20); do + [ "$(curl -fsS -m 2 "http://localhost:$1/" 2>/dev/null)" = "$2" ] && return 0 + sleep 0.5 + done + return 1 +} + +STALE="" +cleanup() { + cm remove-schema dyn >/dev/null + cm remove-schema persist >/dev/null + [ -n "$STALE" ] && docker network rm "$STALE" >/dev/null 2>&1 + rm -rf "$WORK" +} +trap cleanup EXIT + +mkdir -p "$CMGR_DIR" "$CMGR_ARTIFACT_DIR" +cp -r "$HERE/challenges/." "$CMGR_DIR/" +# The default policy with an '=' in a comment: valid profile syntax that +# Docker's option parsing splits on. +jq '.syscalls[0].comment = "persona=0xffffffff only queries"' \ + "$REPO/examples/seccomp/default.json" >"$CMGR_DIR/sec/profile.json" || exit 2 + +echo "== update and converge" +cm update >"$WORK/update1.log" || { cat "$WORK/update1.log"; tail -20 "$WORK/cmgr.log"; exit 2; } +cm add-schema "$HERE/persist.yaml" >"$WORK/persist.log" || cut -c1-200 "$WORK/persist.log" +cm add-schema "$HERE/dyn.yaml" >"$WORK/dyn.log" || cut -c1-200 "$WORK/dyn.log" + +P=$(cm show-schema persist) +WEB_BUILD=$(field "$P" '.[] | select(.id=="lifecycle/web") | .builds[0].id') +WEB_INST=$(field "$P" '.[] | select(.id=="lifecycle/web") | .builds[0].instances[0].id // empty') +WEB_PORT=$(field "$P" '.[] | select(.id=="lifecycle/web") | .builds[0].instances[0].ports.http // empty') +SEC_INST=$(field "$P" '.[] | select(.id=="lifecycle/sec") | .builds[0].instances[0].id // empty') +SEC_PORT=$(field "$P" '.[] | select(.id=="lifecycle/sec") | .builds[0].instances[0].ports.http // empty') +DYN_BUILD=$(field "$(cm show-schema dyn)" '.[] | select(.id=="lifecycle/web") | .builds[0].id') + +echo "== launches" +SEC_CID=$(docker ps -q --filter "network=cmgr-$SEC_INST" | head -1) +if [ -n "$SEC_PORT" ] && serves "$SEC_PORT" sec && + docker inspect --format '{{json .HostConfig.SecurityOpt}}' "$SEC_CID" | grep -q 'persona=0xffffffff'; then + pass "a challenge's own seccomp profile, with '=' in it, reaches its container (instance $SEC_INST on $SEC_PORT)" +else + fail "the challenge with a seccomp profile containing '=' did not launch and serve: $(grep -m1 'security-opt' "$WORK/persist.log" | cut -c1-120)" +fi + +D1=$(cm start "$DYN_BUILD" | instance_id) +cm stop "$D1" >/dev/null +D2=$(cm start "$DYN_BUILD" | instance_id) +if [ -n "$D1" ] && [ -n "$D2" ] && [ "$D2" != "$D1" ]; then + pass "a stopped instance's id is not handed out again ($D1 stopped, next launch got $D2)" +else + fail "instance ids: '$D1' stopped, next launch got '$D2'" +fi + +if [ -n "$D2" ]; then + STALE=cmgr-$((D2 + 1)) + docker network create "$STALE" >/dev/null + OUT=$(cm start "$DYN_BUILD") + D3=$(instance_id <<<"$OUT") + if [ "$D3" = "$((D2 + 1))" ]; then + pass "a launch whose network was left behind still starts (instance $D3)" + else + fail "a launch whose network $STALE was left behind: $(head -1 <<<"$OUT" | cut -c1-160)" + fi + docker network rm "$STALE" >/dev/null 2>&1 + STALE="" +else + fail "a launch whose network was left behind: no instance to number it after" +fi + +echo "== rebuild after a source change" +echo v2 >"$CMGR_DIR/web/version.txt" +cm update >"$WORK/update2.log" || sed -n '/^Errors:/,$p' "$WORK/update2.log" + +P=$(cm show-schema persist) +PORT_AFTER=$(field "$P" '.[] | select(.id=="lifecycle/web") | .builds[0].instances[0].ports.http // empty') +if [ -n "$WEB_PORT" ] && [ "$PORT_AFTER" = "$WEB_PORT" ] && serves "$PORT_AFTER" v2; then + pass "the persistent instance keeps port $WEB_PORT across the rebuild and serves the new build" +else + fail "the persistent instance had port '$WEB_PORT' before the rebuild and '$PORT_AFTER' after (bound: $(docker ps --filter "network=cmgr-$WEB_INST" --format '{{.Ports}}' | head -1))" +fi + +LEFT=$(field "$(cm show-schema dyn)" '[.[] | select(.id=="lifecycle/web") | .builds[0].instances[]? | .id] | join(" ")') +if [ -z "$LEFT" ]; then + pass "the rebuild removed the on-demand instances' records" +else + fail "on-demand instance records survived the rebuild: $LEFT" +fi + +echo "== rebuild that fails validation" +ARCHIVE=$CMGR_ARTIFACT_DIR/$WEB_BUILD.tar.gz +sed 's/notes\.txt/notes2.txt/g' "$CMGR_DIR/web/Dockerfile" >"$WORK/Dockerfile" && + mv "$WORK/Dockerfile" "$CMGR_DIR/web/Dockerfile" +if cm update >"$WORK/update3.log"; then + fail "an update whose build publishes notes2.txt but references notes.txt succeeded" +fi +if [ -f "$ARCHIVE" ] && tar tzf "$ARCHIVE" | grep -qx notes.txt; then + pass "the failed rebuild left the served archive in place" +else + fail "the failed rebuild took the served archive $ARCHIVE with it" +fi +if grep -q "unknown artifact 'notes.txt'" "$WORK/update3.log" && grep -q "artifact file 'notes2.txt' published but not referenced" "$WORK/update3.log"; then + pass "the failed rebuild reported both of its problems" +else + fail "the failed rebuild did not report both of its problems:" + sed -n '/^Errors:/,$p' "$WORK/update3.log" +fi + +echo "== $checks checks, $failures failed" +if [ "$failures" -ne 0 ]; then + echo "-- last lines of cmgr's log" + tail -40 "$WORK/cmgr.log" + exit 1 +fi diff --git a/ci/lifecycle/persist.yaml b/ci/lifecycle/persist.yaml new file mode 100644 index 0000000..5a72c3a --- /dev/null +++ b/ci/lifecycle/persist.yaml @@ -0,0 +1,9 @@ +name: persist +flag_format: flag{%s} +challenges: + lifecycle/web: + seeds: [1] + instance_count: 1 + lifecycle/sec: + seeds: [1] + instance_count: 1