Initial upload to Gitea
This commit is contained in:
1 parent
78193254ad
commit
8478998cae
1485 files changed
+461025
-42348
No files matched your search
@@ -0,0 +1,263 @@
|
||||
package main
|
||||
|
||||
// Tests for the shared image-extract candidate derivation
|
||||
// (imageExtractCandidates).
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
const fakeDockerCLIScript = `#!/bin/sh
|
||||
[ -n "$ADP_TEST_LOG" ] && echo "$*" >> "$ADP_TEST_LOG"
|
||||
cmd="$1"; shift
|
||||
case "$cmd" in
|
||||
pull)
|
||||
[ "${ADP_TEST_PULL_FAILS:-0}" = "1" ] && exit 1
|
||||
exit 0 ;;
|
||||
image)
|
||||
# "image inspect --format ..." is inspectImageConfig's CLI fallback
|
||||
# (payload); bare "image inspect <ref>" is imageExistsLocally's
|
||||
# availability check.
|
||||
if [ "$1" = "inspect" ] && [ "$2" = "--format" ]; then
|
||||
[ "${ADP_TEST_PULL_FAILS:-0}" = "1" ] && exit 1
|
||||
printf '%s\n' "$ADP_TEST_IMAGE_CONFIG"
|
||||
exit 0
|
||||
fi
|
||||
[ "${ADP_TEST_PULL_FAILS:-0}" = "1" ] && exit 1
|
||||
exit 0 ;;
|
||||
inspect)
|
||||
exit 1 ;;
|
||||
create|kill|rm|stop)
|
||||
exit 0 ;;
|
||||
cp)
|
||||
src="$1"; dest="$2"
|
||||
cpath="${src#*:}"
|
||||
cpath="${cpath%/}"
|
||||
cpath="${cpath%/.}"
|
||||
case ",${ADP_TEST_PARTIAL_PATHS:-}," in
|
||||
*",$cpath,"*)
|
||||
# A torn mid-stream cp: docker cp extracts incrementally, so a
|
||||
# failure can leave real files behind before exiting non-zero.
|
||||
mkdir -p "$dest/stub-partial"
|
||||
echo stub > "$dest/stub-partial/server.jar"
|
||||
echo "docker cp: IO error mid-stream" >&2
|
||||
exit 1 ;;
|
||||
esac
|
||||
case ",${ADP_TEST_CONTENT_PATHS:-}," in
|
||||
*",$cpath,"*)
|
||||
mkdir -p "$dest/stub-data"
|
||||
echo stub > "$dest/stub-data/server.jar"
|
||||
exit 0 ;;
|
||||
esac
|
||||
case ",${ADP_TEST_EMPTY_PATHS:-}," in
|
||||
*",$cpath,"*)
|
||||
exit 0 ;;
|
||||
esac
|
||||
echo "no such path: $cpath" >&2
|
||||
exit 1 ;;
|
||||
*)
|
||||
exit 0 ;;
|
||||
esac
|
||||
`
|
||||
|
||||
// fakeDockerImage parameterizes the fake docker CLI for one handler test.
|
||||
type fakeDockerImage struct {
|
||||
// ContentPaths: COMMA-separated container paths whose cp materializes
|
||||
// stub-data/server.jar into the destination.
|
||||
ContentPaths string
|
||||
// EmptyPaths: COMMA-separated container paths whose cp exits 0 without
|
||||
// writing anything.
|
||||
EmptyPaths string
|
||||
// PartialPaths: COMMA-separated container paths whose cp writes
|
||||
// stub-partial/server.jar and THEN exits 1 — a torn mid-stream cp.
|
||||
PartialPaths string
|
||||
// Config: the pre-rendered image-inspect payload the CLI fallback
|
||||
// serves (7 "||"-separated parts: Volumes||Workdir||User||Env||
|
||||
// Entrypoint||Cmd||Labels).
|
||||
Config string
|
||||
// PullFails: pull and `docker image inspect` both fail, simulating an
|
||||
// image that never became available locally.
|
||||
PullFails bool
|
||||
}
|
||||
|
||||
// installFakeDockerCLI writes the stub, points PATH at it, kills the engine
|
||||
// API transport, and returns the invocation log path.
|
||||
func installFakeDockerCLI(t *testing.T, img fakeDockerImage) string {
|
||||
t.Helper()
|
||||
binDir := t.TempDir()
|
||||
if err := os.WriteFile(filepath.Join(binDir, "docker"), []byte(fakeDockerCLIScript), 0o755); err != nil {
|
||||
t.Fatalf("write docker CLI stub: %v", err)
|
||||
}
|
||||
t.Setenv("PATH", binDir+string(os.PathListSeparator)+os.Getenv("PATH"))
|
||||
if out, err := exec.LookPath("docker"); err != nil || filepath.Dir(out) != binDir {
|
||||
t.Fatalf("docker CLI stub not in effect (looked up %q, err %v)", out, err)
|
||||
}
|
||||
|
||||
logPath := filepath.Join(t.TempDir(), "docker.log")
|
||||
t.Setenv("ADP_TEST_LOG", logPath)
|
||||
t.Setenv("ADP_TEST_CONTENT_PATHS", img.ContentPaths)
|
||||
t.Setenv("ADP_TEST_EMPTY_PATHS", img.EmptyPaths)
|
||||
t.Setenv("ADP_TEST_PARTIAL_PATHS", img.PartialPaths)
|
||||
t.Setenv("ADP_TEST_IMAGE_CONFIG", img.Config)
|
||||
if img.PullFails {
|
||||
t.Setenv("ADP_TEST_PULL_FAILS", "1")
|
||||
}
|
||||
|
||||
// The engine API client bypasses PATH entirely (unix socket), so a host
|
||||
// with a live docker daemon would answer the API-side pull and inspect
|
||||
// for real. Both stubs must be in effect.
|
||||
stubDockerEngineUnavailable(t)
|
||||
|
||||
return logPath
|
||||
}
|
||||
|
||||
// imageConfigParts renders a 7-part CLI-fallback inspect payload
|
||||
// (Volumes||Workdir||User||Env||Entrypoint||Cmd||Labels). Empty slices
|
||||
// render as "null", matching `docker image inspect --format {{json ...}}`
|
||||
// output for unset fields.
|
||||
func imageConfigParts(t *testing.T, volumes, workdir, user, env, entrypoint, cmd, labels string) string {
|
||||
t.Helper()
|
||||
return volumes + "||" + workdir + "||" + user + "||" + env + "||" + entrypoint + "||" + cmd + "||" + labels
|
||||
}
|
||||
|
||||
// emptyImageConfigPayload is the payload of an image that declares nothing.
|
||||
func emptyImageConfigPayload() string {
|
||||
return "null||" + "||" + "null||null||null||null"
|
||||
}
|
||||
|
||||
func decodeJSONMap(t *testing.T, rr *httptest.ResponseRecorder) map[string]any {
|
||||
t.Helper()
|
||||
var m map[string]any
|
||||
if err := json.Unmarshal(rr.Body.Bytes(), &m); err != nil {
|
||||
t.Fatalf("decode response %q: %v", rr.Body.String(), err)
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
func jsonSlice(m map[string]any, key string) []any {
|
||||
v, _ := m[key].([]any)
|
||||
return v
|
||||
}
|
||||
|
||||
func jsonStr(m map[string]any, key string) string {
|
||||
v, _ := m[key].(string)
|
||||
return v
|
||||
}
|
||||
|
||||
// --- Pure-function tests: candidate derivation ---
|
||||
|
||||
// The full precedence chain: request manifest, label, volume, env, workdir,
|
||||
// command reference, curated fallback — de-duplicated across sources with
|
||||
// first source winning.
|
||||
func TestImageExtractCandidatesPrecedenceAndDedup(t *testing.T) {
|
||||
cfg := imageConfig{
|
||||
Volumes: []string{"/data"},
|
||||
Workdir: "/app",
|
||||
Env: map[string]string{"STEAMAPPDIR": "/steamapp", "PATH": "/usr/bin:/bin"},
|
||||
Entrypoint: []string{"/bin/sh", "-c"},
|
||||
Cmd: []string{"java -jar /serverdata/server.jar"},
|
||||
Labels: map[string]string{imageExtractLabel: "/opt/game"},
|
||||
}
|
||||
|
||||
cands := imageExtractCandidates([]string{"/manifest", "/manifest", "relative", "/", "", "/data"}, cfg)
|
||||
|
||||
var want []imageExtractCandidate
|
||||
want = append(want, imageExtractCandidate{Path: "/manifest", Source: extractSourceRequest})
|
||||
want = append(want, imageExtractCandidate{Path: "/data", Source: extractSourceRequest}) // manifest outranks the volume
|
||||
want = append(want, imageExtractCandidate{Path: "/opt/game", Source: extractSourceLabel})
|
||||
want = append(want, imageExtractCandidate{Path: "/steamapp", Source: extractSourceEnv})
|
||||
want = append(want, imageExtractCandidate{Path: "/app", Source: extractSourceWorkdir})
|
||||
want = append(want, imageExtractCandidate{Path: "/serverdata", Source: extractSourceCommand})
|
||||
for _, p := range curatedImageExtractFallbackPaths {
|
||||
if p == "/app" || p == "/data" { // already covered by higher-priority sources
|
||||
continue
|
||||
}
|
||||
want = append(want, imageExtractCandidate{Path: p, Source: extractSourceFallback})
|
||||
}
|
||||
|
||||
if len(cands) != len(want) {
|
||||
t.Fatalf("got %d candidates, want %d:\n%+v", len(cands), len(want), cands)
|
||||
}
|
||||
for i := range want {
|
||||
if cands[i] != want[i] {
|
||||
t.Fatalf("candidate[%d] = %+v, want %+v", i, cands[i], want[i])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Label grammar: commas, semicolons, and whitespace all separate paths; the
|
||||
// split itself keeps duplicates and the builder de-duplicates them.
|
||||
func TestImageExtractCandidatesLabelGrammar(t *testing.T) {
|
||||
if got := labelExtractPaths("/srv/a, /srv/b;/srv/a\t/srv/c"); len(got) != 4 {
|
||||
t.Fatalf("labelExtractPaths = %q, want 4 raw paths", got)
|
||||
}
|
||||
|
||||
cfg := imageConfig{Labels: map[string]string{imageExtractLabel: "/srv/a, /srv/b;/srv/a\t/srv/c"}}
|
||||
cands := imageExtractCandidates(nil, cfg)
|
||||
if len(cands) < 3 {
|
||||
t.Fatalf("got %d candidates, want at least the 3 deduped label paths: %+v", len(cands), cands)
|
||||
}
|
||||
for i, wantPath := range []string{"/srv/a", "/srv/b", "/srv/c"} {
|
||||
if cands[i].Path != wantPath || cands[i].Source != extractSourceLabel {
|
||||
t.Fatalf("candidate[%d] = %+v, want %s+%s", i, cands[i], wantPath, extractSourceLabel)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Command-derived paths exclude system directories (segment-precise) but
|
||||
// author-declared sources (workdir) are taken at face value, and the curated
|
||||
// fallback always trails.
|
||||
func TestImageExtractCandidatesCommandSystemFilter(t *testing.T) {
|
||||
if !looksLikeImageSystemPath("/usr/bin/foo") || !looksLikeImageSystemPath("/etc") {
|
||||
t.Fatalf("expected /usr/bin/foo and /etc to be system paths")
|
||||
}
|
||||
if looksLikeImageSystemPath("/usr/binuary-data") {
|
||||
t.Fatalf("/usr/binuary-data must not match the /usr/bin prefix (segment-precise)")
|
||||
}
|
||||
|
||||
cfg := imageConfig{
|
||||
Workdir: "/usr/bin", // pathological, but author-declared: kept
|
||||
Entrypoint: []string{"/usr/bin/supervisord", "-c", "/etc/supervisor/supervisord.conf"},
|
||||
Cmd: []string{"-n"},
|
||||
}
|
||||
cands := imageExtractCandidates(nil, cfg)
|
||||
if len(cands) < 1 || cands[0].Path != "/usr/bin" || cands[0].Source != extractSourceWorkdir {
|
||||
t.Fatalf("expected the author-declared workdir first, got %+v", cands)
|
||||
}
|
||||
for _, cand := range cands {
|
||||
if cand.Source == extractSourceCommand {
|
||||
t.Fatalf("command-derived candidate survived the system filter: %+v", cand)
|
||||
}
|
||||
if cand.Path == "/etc/supervisor" {
|
||||
t.Fatalf("system path /etc/supervisor leaked into candidates: %+v", cands)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Absolute env paths survive; relative, empty, and root values are dropped.
|
||||
func TestImageExtractCandidatesRejectsNonAbsolute(t *testing.T) {
|
||||
cfg := imageConfig{
|
||||
Env: map[string]string{"SERVER_DIR": "relative/path", "DATA_DIR": "", "GAME_DIR": "/"},
|
||||
}
|
||||
for _, cand := range imageExtractCandidates(nil, cfg) {
|
||||
if cand.Source == extractSourceEnv {
|
||||
t.Fatalf("relative/empty/root env value produced an env candidate: %+v", cand)
|
||||
}
|
||||
if !filepath.IsAbs(cand.Path) || cand.Path == "/" {
|
||||
t.Fatalf("non-absolute or root candidate leaked through: %+v", cand)
|
||||
}
|
||||
}
|
||||
for _, cand := range imageExtractCandidates([]string{"relative/path", "/", ""}, imageConfig{}) {
|
||||
if !filepath.IsAbs(cand.Path) || cand.Path == "/" {
|
||||
t.Fatalf("non-absolute or root candidate leaked through: %+v", cand)
|
||||
}
|
||||
if cand.Source != extractSourceFallback {
|
||||
t.Fatalf("all-request candidates were dropped, but got %+v", cand)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user