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/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/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 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/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/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/artifacts_test.go b/cmgr/artifacts_test.go index a9b249c..6bc412c 100644 --- a/cmgr/artifacts_test.go +++ b/cmgr/artifacts_test.go @@ -381,3 +381,75 @@ 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) + } +} + +// 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) + } + // 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/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_challenges.go b/cmgr/database_challenges.go index a9adc9e..3b3cab9 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 @@ -122,8 +124,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 { @@ -154,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 @@ -367,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) - + err := m.writeChallenge(metadata, challengeUpdateQuery) 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 - } - - _, 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 } @@ -683,19 +345,20 @@ 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) - // 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) @@ -708,26 +371,46 @@ func (m *Manager) updateChallenges(updatedChallenges []*ChallengeMetadata, rebui } for _, iid := range instances { instance, err := m.lookupInstanceMetadata(iid) - 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) } continue } + // stopContainers releases the port assignments; the + // restart below reclaims them (same numbers when free) + // so the instance keeps its address across the rebuild. + previousPorts := instance.Ports + err = m.stopContainers(instance) if err == nil { - err = m.stopContainers(instance) + err = m.stopNetwork(instance) } if err == nil { - err = m.stopNetwork(instance) + 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) + 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 092dc02..3e41cf5 100644 --- a/cmgr/database_operations_test.go +++ b/cmgr/database_operations_test.go @@ -3,6 +3,8 @@ package cmgr import ( "encoding/json" "os" + "path/filepath" + "strings" "testing" "time" @@ -1711,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. @@ -1794,3 +2025,237 @@ 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") + } +} + +// 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) + } + } + }) + } +} + +// 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 10bb70d..d5db734 100644 --- a/cmgr/docker.go +++ b/cmgr/docker.go @@ -153,6 +153,43 @@ 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, 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, 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) + 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 +289,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 } } @@ -477,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 } @@ -485,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 } @@ -522,7 +563,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) @@ -591,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 } @@ -629,7 +682,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{ @@ -687,15 +740,12 @@ 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) + 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 { @@ -722,8 +772,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. @@ -760,6 +808,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) } @@ -780,14 +839,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 @@ -913,7 +968,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 +1002,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/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/loader_markdown.go b/cmgr/loader_markdown.go index 3ab84ba..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,30 +147,33 @@ 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 } } + // 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 +183,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 +254,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..760c79a 100644 --- a/cmgr/loader_markdown_test.go +++ b/cmgr/loader_markdown_test.go @@ -618,3 +618,136 @@ 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) + } + }) + } +} + +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) + } +} 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..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 } @@ -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/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 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) + } + } +} 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`.