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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .github/workflows/go.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
17 changes: 12 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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/<id>`) 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/<id>` with the appropriate runtime configuration to
bring those instances back up. Persistent (schema-managed) instances are
restarted automatically as before.
`POST /builds/<id>`) 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/<id>` 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
Expand Down
10 changes: 10 additions & 0 deletions ci/lifecycle/challenges/sec/Dockerfile
Original file line number Diff line number Diff line change
@@ -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
22 changes: 22 additions & 0 deletions ci/lifecycle/challenges/sec/problem.md
Original file line number Diff line number Diff line change
@@ -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
```
12 changes: 12 additions & 0 deletions ci/lifecycle/challenges/web/Dockerfile
Original file line number Diff line number Diff line change
@@ -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
14 changes: 14 additions & 0 deletions ci/lifecycle/challenges/web/problem.md
Original file line number Diff line number Diff line change
@@ -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}}`.
1 change: 1 addition & 0 deletions ci/lifecycle/challenges/web/version.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
v1
6 changes: 6 additions & 0 deletions ci/lifecycle/dyn.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
name: dyn
flag_format: dyn{%s}
challenges:
lifecycle/web:
seeds: [2]
instance_count: -1
148 changes: 148 additions & 0 deletions ci/lifecycle/lifecycle.sh
Original file line number Diff line number Diff line change
@@ -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 <cmgr binary>
# 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 <cmgr binary>" >&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 <port> <body>: 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
9 changes: 9 additions & 0 deletions ci/lifecycle/persist.yaml
Original file line number Diff line number Diff line change
@@ -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
12 changes: 10 additions & 2 deletions cmd/cmgr/challenges.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
}
Expand Down
13 changes: 11 additions & 2 deletions cmd/cmgrd/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand Down
13 changes: 11 additions & 2 deletions cmgr/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
}

Expand Down Expand Up @@ -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 {
Expand Down
Loading
Loading