Skip to content

Backport cork fixes - #113

Merged
hi-liang merged 13 commits into
masterfrom
backport-cork-fixes
Nov 17, 2026
Merged

hi-liang merged 13 commits into
masterfrom
backport-cork-fixes

Conversation

@hi-liang

@hi-liang hi-liang commented Nov 17, 2026 •

Copy link
Copy Markdown
Member

Backport correctness fixes from cork

cmgr has had no functional changes since #96. cork, the multi-host fork, fixed a set of bugs in code it inherited from cmgr. This ports the ones a single-host deployment hits, plus fixes for further bugs found while reviewing the port. Each commit says which cork commit it came from, or that it goes beyond cork.

Player-visible

  • Instance ids are never reused. instances.id gets AUTOINCREMENT. Without it, a stale DELETE /instances/<id> from a front-end could tear down whoever drew that id next.
    • Existing databases are migrated in place by the existing table rebuild. The numbering continues above the highest id ever handed out.
    • The migration's foreign-key check now covers only the tables it rebuilds, so a stale row elsewhere can't stop cmgr from starting.
  • On-demand instances are removed on rebuild. Before, a rebuild left their records behind with no containers and no ports, and GET still answered 200. Now GET and DELETE answer 404, so the front-end relaunches.
  • Persistent instances keep their ports across a rebuild when CMGR_PORTS is set. Before, they came back on an ephemeral port outside the range, with no port recorded. A restart that fails is rolled back and no longer holds ports.
  • The served artifact archive matches the recorded build.
    • A new archive is staged and served only after its build row commits, so a failed build or rebuild never replaces or deletes the archive players download.
    • A rebuild that no longer publishes artifacts removes the old archive.
    • cmgrd's artifact handler now returns 404 for a build with no artifacts and 500 for a failed lookup.
  • Per-challenge seccomp profiles containing = (e.g. in a comment) no longer fail every launch. Security options now use = as the separator.
  • Hardening fails closed.
    • A malformed ## Challenge Options section, including a bad, missing or duplicated ```yaml fence, now fails the load instead of loading with zeroed options.
    • Fences are matched trimmed, so CRLF files and trailing spaces work.
    • A container-options row that can't be decoded fails the lookup instead of returning the challenge unhardened.
  • Network conflicts on launch.
    • A stale cmgr-<id> network is removed and recreated instead of failing the launch.
    • A launch that fails before creating its network (no free port, or the create itself) removes only its own row. It never removes a network of that name it didn't create.

Operator-visible

  • A failed write of a challenge's rows reports the real error and moves on to the next challenge. Before, it reported "transaction has already been committed or rolled back" and abandoned the rest of the batch.
  • cmgr update logs a warning for a persistent instance it finds still launching while it rebuilds that build, rather than passing over it in silence. It's a warning, not an error, so a crashed launch can't fail every later update.
  • Challenge and build validation report every problem, not just the last one. The CLI indents multi-line errors under their entry.
  • Build, artifact, freeze and solver-image failures name the challenge (and build and seed where known).

Behaviour changes to know before deploying

  • Any malformed problem.md section now fails the load, as in cork. Before, it was logged and skipped. This covers ## Challenge Options, and also a tag or attribute line the loader can't read (e.g. - web-exploitation).
  • A header value that doesn't parse, or a header line that isn't a - key: value bullet, fails the load. Before, Points: ten and * Points: 100 both loaded as 0. Unknown header keys are still ignored, so a cork-format problem.md with Difficulty: keeps loading.
  • Run cmgr update --dry-run first to find any affected challenge. None of the 554 problem.md files in the picoCTF challenge repositories, nor cmgr's examples, is affected.
  • The first start on an existing database rebuilds the instances table to add AUTOINCREMENT. Rolling back to an older cmgr is safe; it leaves the table as it is.
  • GET and DELETE /instances/<id> for an on-demand instance of a rebuilt build now return 404.

Known limitations (follow-up PR)

  • Don't run a schema operation and cmgr update at the same time. Nothing serializes them across processes, so an instance launched during a rebuild can come up on the previous build; the README now says so. A lock across processes is the follow-up.
  • Build ids are still reused, as instance ids were: a stale POST /builds/<id> or artifact download can reach a different challenge once the newest builds are deleted. It needs the same AUTOINCREMENT migration on builds.
  • Two cmgr databases sharing one Docker daemon, or cmgr and cork on one daemon, collide on cmgr-<id> network names, as they already did on master. This branch refuses to take over a network with live endpoints and never removes one it didn't create, but that setup needs distinct network names.

Verification

  • go vet ./... and go test ./... pass. New unit tests cover:

    • the loader, fence and lookup swallows, and header values;
    • the challenge-write rollback;
    • the AUTOINCREMENT migration, its high-water mark and its scoped check;
    • port reassignment and its rollback;
    • archive promotion and removal;
    • multi-problem validation.

    Each test fails without its fix.

  • New CI step Lifecycle Tests (ci/lifecycle/lifecycle.sh, about 20 s) drives cmgr through what cmgr test never reaches: a seccomp profile with =, no id reuse, a stale network, ports kept across a rebuild, on-demand records removed, the archive kept on a failed rebuild, and both validation problems listed. Against Docker 29.9.3, a master binary fails all seven checks and this branch passes all seven.

  • Checked by hand against Docker 29.9.3, after two review rounds:

    • A persistent launch in flight during a rebuild is warned about, and the update still exits 0.
    • When another container's live network holds a launch's cmgr-<id>, the launch leaves no record and leaves the network alone, whether it failed on the network create or on an exhausted port range.
    • All of cmgr's examples load.
    • Each of these failed before the round that fixed it.

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.
…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.
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.
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.
executeBuild wrote the new artifact archive straight to the final
<build id>.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 <id>.tar.gz.

Checked against Docker 29.9.3: master deletes <id>.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.
A challenge that stops producing artifacts.tar.gz and is rebuilt records
has_artifacts false, but nothing removed the previous generation's
<build id>.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.
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/<id> 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.
…instance

The instance network is named cmgr-<id>. 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-<id> 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-<next id> 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.
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.
… 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/<id> 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.
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.
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 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-<id> 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.
@hi-liang
hi-liang force-pushed the backport-cork-fixes branch from 95384a2 to 71e4edb Compare November 17, 2026 18:49
@hi-liang
hi-liang merged commit aef2a74 into master Nov 17, 2026
1 check passed
@hi-liang
hi-liang deleted the backport-cork-fixes branch November 17, 2026 19:03
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant