From 965740effbfc183ec50ccdc892c23b8f635709ed Mon Sep 17 00:00:00 2001 From: Blake Bauman Date: Mon, 7 Sep 2026 19:53:55 -0700 Subject: [PATCH] Widen the sidecar's pure-logic tests and refresh CLAUDE.md. MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Adds tests for audit, engine, compose, and helm, taking the sidecar from 7 test files to 11. The picks are the same as the first pass: pure logic that is security-relevant or easy to get subtly wrong — audit log permissions and tail behaviour, engine mode coercion and persistence, compose path/arg resolution and discovery bounds, helm values-file handling. To test the CLI-output parsing without a docker or helm binary on PATH, the three parsers are split out of the methods that shell out — parseComposeLs, parseComposePs, parseReleaseList — with no change in behaviour. One fix falls out of the helm tests: List mapped Revision with fmt.Sprint(item["revision"]), so a release whose JSON omits revision reached the UI as the literal string "". str() renders numbers identically and maps an absent field to "". CLAUDE.md claimed there were no tests and no TypeScript linter. Both stopped being true in 14fd7c4 and 3f26f9d respectively, so the file now describes the real gates, documents bun run lint / lint:fix, and records the split-parser convention. Co-Authored-By: Claude Opus 5 (1M context) Claude-Session: https://claude.ai/code/session_01Ud4Wz8LSXsSuxRyRaJsb3X --- CLAUDE.md | 22 +- sidecar/internal/audit/audit_test.go | 136 +++++++ sidecar/internal/compose/service.go | 13 + sidecar/internal/compose/service_test.go | 469 +++++++++++++++++++++++ sidecar/internal/engine/mode_test.go | 129 +++++++ sidecar/internal/helm/service.go | 8 +- sidecar/internal/helm/service_test.go | 141 +++++++ 7 files changed, 911 insertions(+), 7 deletions(-) create mode 100644 sidecar/internal/audit/audit_test.go create mode 100644 sidecar/internal/compose/service_test.go create mode 100644 sidecar/internal/engine/mode_test.go create mode 100644 sidecar/internal/helm/service_test.go diff --git a/CLAUDE.md b/CLAUDE.md index 44aa1c2..1a8160a 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -10,19 +10,29 @@ bun run dev # build sidecar → Tauri dev (Vite on :1420) bun run dev:ui # Vite UI only; pair with VITE_SIDECAR_URL bun run dev:sidecar # go run the sidecar on 127.0.0.1:7420 bun run build # tsc --noEmit && vite build (the UI typecheck gate) +bun run lint # biome check . (the UI lint + format gate) +bun run lint:fix # biome check --write . — fixes what CI's `biome ci .` would fail on bun run build:sidecar # scripts/build-sidecar.sh → src-tauri/binaries/ bun run version 0.1.0-x # sync package.json + Cargo.toml bun run version:check # fail if Cargo.toml ≠ root package.json version bun run tauri:build # sidecar + installers (.dmg/.app, .deb/AppImage) -cd sidecar && go build ./... && go vet ./... # sidecar checks +cd sidecar && go build ./... && go vet ./... && go test ./... # sidecar checks ``` -There are **no tests yet** — 32 Go files, zero `*_test.go`, and no JS test runner. Verification -is the build: `bun run build` for the UI, `go build ./... && go vet ./...` for the sidecar. CI -(`.github/workflows/ci.yml`) runs exactly those plus `go test ./...` and `bun run version:check`. -CI also gates `gofmt` on `sidecar/` — fix a failure with `gofmt -w sidecar/`. There is no -formatter or linter configured for the TypeScript side; `tsc --noEmit` is the only gate there. +The sidecar has Go tests; the frontend has **no test runner at all**. Coverage is deliberately +partial — pure logic that is security-relevant or easy to get subtly wrong (`server/auth`, +`k8s/resources` redaction, `audit`, `engine`, `compose`, `helm`, `domains/proxy`, and +`docker/{client,run,stats,volume_ops}`). Anything needing a live daemon is untested, so add a +`*_test.go` next to the logic you touch rather than assuming one exists. Where a method shells +out and then parses the output, split the parser into its own function (`parseComposeLs`, +`parseComposePs`, `parseReleaseList`) so it can be tested without a `docker` or `helm` binary. +Verification for the UI is `bun run build` (typecheck) plus `bun run lint`; for the sidecar it is +`go build ./... && go vet ./... && go test ./...`. + +CI (`.github/workflows/ci.yml`) runs exactly those, plus `bun run version:check`. It gates +`gofmt` on `sidecar/` — fix a failure with `gofmt -w sidecar/` — and gates the TypeScript side +with `biome ci .`, which checks lint *and* formatting; fix a failure with `bun run lint:fix`. xterm.js is code-split behind `ExecTerminalLazy` (~85 KB gzipped, the largest single dependency). Import that wrapper rather than `ExecTerminal` directly, or the terminal lands back in the initial diff --git a/sidecar/internal/audit/audit_test.go b/sidecar/internal/audit/audit_test.go new file mode 100644 index 0000000..1255cac --- /dev/null +++ b/sidecar/internal/audit/audit_test.go @@ -0,0 +1,136 @@ +package audit + +import ( + "errors" + "os" + "path/filepath" + "testing" + "time" +) + +func newTestLogger(t *testing.T) *Logger { + t.Helper() + return New(filepath.Join(t.TempDir(), "nested", "audit.jsonl")) +} + +func TestNewCreatesParentDirectory(t *testing.T) { + l := newTestLogger(t) + if _, err := os.Stat(filepath.Dir(l.Path())); err != nil { + t.Fatalf("parent directory not created: %v", err) + } +} + +func TestLogAndTailRoundTrip(t *testing.T) { + l := newTestLogger(t) + l.Log("container.remove", "web", "force=true", nil) + l.Log("volume.prune", "", "", errors.New("daemon unreachable")) + + events, err := l.Tail(0) + if err != nil { + t.Fatalf("Tail: %v", err) + } + if len(events) != 2 { + t.Fatalf("Tail returned %d events, want 2", len(events)) + } + + ok := events[0] + if ok.Action != "container.remove" || ok.Target != "web" || ok.Detail != "force=true" { + t.Errorf("first event = %+v, want the container.remove fields", ok) + } + if !ok.OK || ok.Error != "" { + t.Errorf("nil error should record OK with no message, got ok=%v error=%q", ok.OK, ok.Error) + } + if _, err := time.Parse(time.RFC3339, ok.Time); err != nil { + t.Errorf("Time %q is not RFC3339: %v", ok.Time, err) + } + + failed := events[1] + if failed.OK { + t.Error("an event logged with an error should not be OK") + } + if failed.Error != "daemon unreachable" { + t.Errorf("Error = %q, want the error's message", failed.Error) + } +} + +func TestTailReturnsTheLastNEvents(t *testing.T) { + l := newTestLogger(t) + for _, action := range []string{"a", "b", "c", "d"} { + l.Log(action, "", "", nil) + } + + events, err := l.Tail(2) + if err != nil { + t.Fatalf("Tail: %v", err) + } + if len(events) != 2 || events[0].Action != "c" || events[1].Action != "d" { + t.Fatalf("Tail(2) = %+v, want the newest two (c, d)", events) + } + + // A request for more than exists is clamped rather than erroring, so the + // UI's fixed tail size works against a short log. + all, err := l.Tail(100) + if err != nil { + t.Fatalf("Tail: %v", err) + } + if len(all) != 4 { + t.Errorf("Tail(100) returned %d events, want all 4", len(all)) + } +} + +func TestTailOnMissingLogIsNotAnError(t *testing.T) { + // The audit log does not exist until the first mutating operation, and the + // UI polls GET /api/audit before then. + l := &Logger{path: filepath.Join(t.TempDir(), "absent.jsonl")} + events, err := l.Tail(10) + if err != nil { + t.Fatalf("Tail on a missing file: %v", err) + } + if len(events) != 0 { + t.Errorf("Tail on a missing file returned %d events, want none", len(events)) + } +} + +func TestTailSkipsUnparseableLines(t *testing.T) { + path := filepath.Join(t.TempDir(), "audit.jsonl") + // A truncated write (crash mid-append) must not poison the whole tail. + body := `{"time":"2026-01-01T00:00:00Z","action":"good","ok":true}` + "\n" + + "{not json" + "\n" + + "\n" + + `{"time":"2026-01-01T00:00:01Z","action":"also-good","ok":true}` + "\n" + if err := os.WriteFile(path, []byte(body), 0o600); err != nil { + t.Fatal(err) + } + + events, err := (&Logger{path: path}).Tail(0) + if err != nil { + t.Fatalf("Tail: %v", err) + } + if len(events) != 2 { + t.Fatalf("Tail returned %d events, want the 2 parseable ones", len(events)) + } + if events[0].Action != "good" || events[1].Action != "also-good" { + t.Errorf("Tail = %+v, want the two well-formed events in order", events) + } +} + +func TestLogFileIsOwnerOnly(t *testing.T) { + // The log records container names, image refs, and host paths; it is + // created 0600 so other local accounts cannot read it. + l := newTestLogger(t) + l.Log("image.pull", "nginx:latest", "", nil) + + st, err := os.Stat(l.Path()) + if err != nil { + t.Fatal(err) + } + if perm := st.Mode().Perm(); perm != 0o600 { + t.Errorf("audit log mode = %o, want 600", perm) + } +} + +func TestNilLoggerIsANoOp(t *testing.T) { + // Handlers call s.audit.Log unconditionally, so a nil logger must not panic. + var l *Logger + l.Log("container.stop", "web", "", nil) +} diff --git a/sidecar/internal/compose/service.go b/sidecar/internal/compose/service.go index f0eaca1..13666a3 100644 --- a/sidecar/internal/compose/service.go +++ b/sidecar/internal/compose/service.go @@ -64,6 +64,12 @@ func (s *Service) List(ctx context.Context) ([]Project, error) { if err != nil { return nil, err } + return parseComposeLs(out) +} + +// parseComposeLs turns `docker compose ls --format json` output into projects. +// Split out from List so it can be exercised without a docker binary. +func parseComposeLs(out string) ([]Project, error) { out = strings.TrimSpace(out) if out == "" || out == "null" { return []Project{}, nil @@ -239,6 +245,13 @@ func (s *Service) Services(ctx context.Context, req UpRequest) ([]ServiceInfo, e if err != nil { return nil, err } + return parseComposePs(out) +} + +// parseComposePs turns `docker compose ps --format json` output into services. +// Docker emits either a JSON array or NDJSON depending on version, so both +// shapes are handled; split out from Services to be testable without docker. +func parseComposePs(out string) ([]ServiceInfo, error) { out = strings.TrimSpace(out) if out == "" || out == "null" { return []ServiceInfo{}, nil diff --git a/sidecar/internal/compose/service_test.go b/sidecar/internal/compose/service_test.go new file mode 100644 index 0000000..f36494e --- /dev/null +++ b/sidecar/internal/compose/service_test.go @@ -0,0 +1,469 @@ +package compose + +import ( + "os" + "path/filepath" + "slices" + "strings" + "testing" +) + +func writeFile(t *testing.T, path string) string { + t.Helper() + if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(path, []byte("services: {}\n"), 0o600); err != nil { + t.Fatal(err) + } + return path +} + +func TestSplitConfigFiles(t *testing.T) { + tests := []struct { + name string + in string + want []string + }{ + {name: "empty", in: "", want: nil}, + {name: "whitespace only", in: " ", want: nil}, + {name: "single path", in: "/srv/compose.yaml", want: []string{"/srv/compose.yaml"}}, + { + // `docker compose ls` joins multiple -f files with commas. + name: "comma separated with padding", + in: " /a/compose.yaml , /b/override.yaml ", + want: []string{"/a/compose.yaml", "/b/override.yaml"}, + }, + {name: "empty segments dropped", in: "/a/compose.yaml,,", want: []string{"/a/compose.yaml"}}, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + if got := splitConfigFiles(tc.in); !slices.Equal(got, tc.want) { + t.Errorf("splitConfigFiles(%q) = %q, want %q", tc.in, got, tc.want) + } + }) + } +} + +func TestExistingFiles(t *testing.T) { + dir := t.TempDir() + real := writeFile(t, filepath.Join(dir, "compose.yaml")) + subdir := filepath.Join(dir, "sub") + if err := os.MkdirAll(subdir, 0o755); err != nil { + t.Fatal(err) + } + + t.Run("nil input", func(t *testing.T) { + if got := existingFiles(nil); got != nil { + t.Errorf("existingFiles(nil) = %q, want nil", got) + } + }) + + t.Run("missing paths are dropped", func(t *testing.T) { + got := existingFiles([]string{real, filepath.Join(dir, "gone.yaml")}) + if !slices.Equal(got, []string{real}) { + t.Errorf("existingFiles = %q, want %q", got, []string{real}) + } + }) + + t.Run("directories are not compose files", func(t *testing.T) { + if got := existingFiles([]string{subdir}); len(got) != 0 { + t.Errorf("existingFiles(dir) = %q, want none", got) + } + }) + + t.Run("duplicates collapse", func(t *testing.T) { + got := existingFiles([]string{real, real, " " + real + " "}) + if !slices.Equal(got, []string{real}) { + t.Errorf("existingFiles = %q, want a single %q", got, real) + } + }) + + t.Run("relative paths are resolved against the working directory", func(t *testing.T) { + // The UI can hand back a path as the user typed it; compose is run + // from a different directory, so it has to be made absolute here. + t.Chdir(dir) + got := existingFiles([]string{"compose.yaml"}) + if len(got) != 1 || !filepath.IsAbs(got[0]) || filepath.Base(got[0]) != "compose.yaml" { + t.Errorf("existingFiles([compose.yaml]) = %q, want one absolute path", got) + } + }) +} + +func TestComposeArgs(t *testing.T) { + tests := []struct { + name string + files []string + project string + want []string + }{ + {name: "bare", want: []string{"compose"}}, + { + name: "each file gets its own -f", + files: []string{"/a/compose.yaml", "/a/override.yaml"}, + want: []string{"compose", "-f", "/a/compose.yaml", "-f", "/a/override.yaml"}, + }, + {name: "blank files are skipped", files: []string{"", "/a/compose.yaml"}, want: []string{"compose", "-f", "/a/compose.yaml"}}, + {name: "project name", project: "web", want: []string{"compose", "-p", "web"}}, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + if got := composeArgs(tc.files, tc.project); !slices.Equal(got, tc.want) { + t.Errorf("composeArgs(%q, %q) = %q, want %q", tc.files, tc.project, got, tc.want) + } + }) + } +} + +func TestResolveComposeConfigFilesWin(t *testing.T) { + dir := t.TempDir() + file := writeFile(t, filepath.Join(dir, "compose.yaml")) + + gotDir, files, cleanup, err := resolveCompose(UpRequest{ConfigFiles: []string{file}, Path: "/nonexistent"}) + if err != nil { + t.Fatalf("resolveCompose: %v", err) + } + if cleanup != nil { + t.Error("no temp file was written, so there is nothing to clean up") + } + if gotDir != dir || !slices.Equal(files, []string{file}) { + t.Errorf("resolveCompose = (%q, %q), want (%q, [%q])", gotDir, files, dir, file) + } +} + +func TestResolveComposePicksTheCanonicalFileName(t *testing.T) { + // composeFileNames is ordered, and compose.yaml is the name the Compose + // spec prefers — a directory holding both must resolve to it. + dir := t.TempDir() + writeFile(t, filepath.Join(dir, "docker-compose.yml")) + preferred := writeFile(t, filepath.Join(dir, "compose.yaml")) + + gotDir, files, _, err := resolveCompose(UpRequest{Path: dir}) + if err != nil { + t.Fatalf("resolveCompose: %v", err) + } + if gotDir != dir || !slices.Equal(files, []string{preferred}) { + t.Errorf("resolveCompose = (%q, %q), want (%q, [%q])", gotDir, files, dir, preferred) + } +} + +func TestResolveComposeAcceptsAFilePath(t *testing.T) { + dir := t.TempDir() + file := writeFile(t, filepath.Join(dir, "stack.yaml")) + + gotDir, files, _, err := resolveCompose(UpRequest{Path: file}) + if err != nil { + t.Fatalf("resolveCompose: %v", err) + } + if gotDir != dir || !slices.Equal(files, []string{file}) { + t.Errorf("resolveCompose = (%q, %q), want (%q, [%q])", gotDir, files, dir, file) + } +} + +func TestResolveComposeWritesInlineYAMLAndCleansUp(t *testing.T) { + dir, files, cleanup, err := resolveCompose(UpRequest{YAML: "services:\n web:\n image: nginx\n"}) + if err != nil { + t.Fatalf("resolveCompose: %v", err) + } + if cleanup == nil { + t.Fatal("inline YAML writes a temp tree, so a cleanup func is required") + } + if len(files) != 1 || filepath.Base(files[0]) != "compose.yaml" { + t.Fatalf("files = %q, want one compose.yaml", files) + } + body, err := os.ReadFile(files[0]) + if err != nil { + t.Fatal(err) + } + if !strings.Contains(string(body), "image: nginx") { + t.Errorf("temp compose file = %q, want the request's YAML", body) + } + + cleanup() + if _, err := os.Stat(dir); !os.IsNotExist(err) { + t.Errorf("cleanup left %q behind (err=%v)", dir, err) + } +} + +func TestResolveComposeErrors(t *testing.T) { + t.Run("nothing to run", func(t *testing.T) { + if _, _, _, err := resolveCompose(UpRequest{}); err == nil { + t.Error("resolveCompose with no path or yaml should fail") + } + }) + + t.Run("directory without a compose file", func(t *testing.T) { + _, _, _, err := resolveCompose(UpRequest{Path: t.TempDir()}) + if err == nil || !strings.Contains(err.Error(), "no compose file") { + t.Errorf("err = %v, want a 'no compose file' error", err) + } + }) +} + +func TestResolveComposeOptionalFile(t *testing.T) { + t.Run("project name alone is enough", func(t *testing.T) { + // down/restart/ps can address a project docker already knows, with no + // file on disk to point at. + dir, files, cleanup, err := resolveComposeOptionalFile(UpRequest{ProjectName: "web"}) + if err != nil { + t.Fatalf("resolveComposeOptionalFile: %v", err) + } + if dir != "" || files != nil || cleanup != nil { + t.Errorf("= (%q, %q, cleanup!=nil:%v), want all empty", dir, files, cleanup != nil) + } + }) + + t.Run("nothing at all fails", func(t *testing.T) { + if _, _, _, err := resolveComposeOptionalFile(UpRequest{}); err == nil { + t.Error("expected an error when no project, path, or yaml is given") + } + }) + + t.Run("a path still resolves to files", func(t *testing.T) { + dir := t.TempDir() + file := writeFile(t, filepath.Join(dir, "compose.yml")) + gotDir, files, _, err := resolveComposeOptionalFile(UpRequest{Path: dir, ProjectName: "web"}) + if err != nil { + t.Fatalf("resolveComposeOptionalFile: %v", err) + } + if gotDir != dir || !slices.Equal(files, []string{file}) { + t.Errorf("= (%q, %q), want (%q, [%q])", gotDir, files, dir, file) + } + }) +} + +func TestDiscover(t *testing.T) { + root := t.TempDir() + writeFile(t, filepath.Join(root, "compose.yaml")) + writeFile(t, filepath.Join(root, "api", "docker-compose.yml")) + writeFile(t, filepath.Join(root, "deep", "one", "two", "compose.yaml")) + writeFile(t, filepath.Join(root, "node_modules", "pkg", "compose.yaml")) + writeFile(t, filepath.Join(root, ".git", "compose.yaml")) + writeFile(t, filepath.Join(root, "vendor", "compose.yaml")) + writeFile(t, filepath.Join(root, "notes.yaml")) + + byPath := func(projects []Project) map[string]Project { + m := map[string]Project{} + for _, p := range projects { + rel, err := filepath.Rel(root, p.Path) + if err != nil { + t.Fatal(err) + } + m[filepath.ToSlash(rel)] = p + } + return m + } + + t.Run("finds compose files and skips vendored trees", func(t *testing.T) { + found := byPath(mustDiscover(t, DiscoverRequest{Roots: []string{root}})) + for _, want := range []string{"compose.yaml", "api/docker-compose.yml", "deep/one/two/compose.yaml"} { + if _, ok := found[want]; !ok { + t.Errorf("Discover missed %s (got %v)", want, keys(found)) + } + } + for _, skipped := range []string{"node_modules/pkg/compose.yaml", ".git/compose.yaml", "vendor/compose.yaml"} { + if _, ok := found[skipped]; ok { + t.Errorf("Discover should not descend into %s", skipped) + } + } + if _, ok := found["notes.yaml"]; ok { + t.Error("Discover matched a yaml file that is not a compose file name") + } + }) + + t.Run("project name is the containing directory", func(t *testing.T) { + found := byPath(mustDiscover(t, DiscoverRequest{Roots: []string{root}})) + if got := found["api/docker-compose.yml"]; got.Name != "api" || got.Source != "scan" || got.Status != "discovered" { + t.Errorf("project = %+v, want name=api source=scan status=discovered", got) + } + }) + + t.Run("one project per directory", func(t *testing.T) { + dir := t.TempDir() + writeFile(t, filepath.Join(dir, "compose.yaml")) + writeFile(t, filepath.Join(dir, "docker-compose.yml")) + projects := mustDiscover(t, DiscoverRequest{Roots: []string{dir}}) + if len(projects) != 1 { + t.Fatalf("Discover returned %d projects for one directory, want 1", len(projects)) + } + if filepath.Base(projects[0].Path) != "compose.yaml" { + t.Errorf("Path = %q, want the canonical compose.yaml", projects[0].Path) + } + }) + + t.Run("maxDepth bounds the walk", func(t *testing.T) { + found := byPath(mustDiscover(t, DiscoverRequest{Roots: []string{root}, MaxDepth: 1})) + if _, ok := found["api/docker-compose.yml"]; !ok { + t.Error("depth 1 should still reach a direct subdirectory") + } + if _, ok := found["deep/one/two/compose.yaml"]; ok { + t.Error("depth 1 should not reach a three-deep file") + } + }) + + t.Run("maxDepth is clamped so a scan cannot run away", func(t *testing.T) { + deep := t.TempDir() + dir := deep + for _, name := range []string{"d1", "d2", "d3", "d4", "d5", "d6", "d7"} { + dir = filepath.Join(dir, name) + writeFile(t, filepath.Join(dir, "compose.yaml")) + } + projects := mustDiscover(t, DiscoverRequest{Roots: []string{deep}, MaxDepth: 100}) + // Depths 1..6 are walked; the seventh level is beyond the cap. + if len(projects) != 6 { + t.Errorf("Discover with MaxDepth=100 found %d projects, want 6 (capped at depth 6)", len(projects)) + } + }) + + t.Run("unusable roots are ignored", func(t *testing.T) { + file := writeFile(t, filepath.Join(t.TempDir(), "compose.yaml")) + projects := mustDiscover(t, DiscoverRequest{Roots: []string{"", " ", filepath.Join(root, "does-not-exist"), file}}) + if len(projects) != 0 { + t.Errorf("Discover = %+v, want nothing for blank, missing, and non-directory roots", projects) + } + }) +} + +func mustDiscover(t *testing.T, req DiscoverRequest) []Project { + t.Helper() + projects, err := (&Service{}).Discover(t.Context(), req) + if err != nil { + t.Fatalf("Discover: %v", err) + } + return projects +} + +func keys(m map[string]Project) []string { + out := make([]string, 0, len(m)) + for k := range m { + out = append(out, k) + } + slices.Sort(out) + return out +} + +func TestParseComposeLs(t *testing.T) { + dir := t.TempDir() + file := writeFile(t, filepath.Join(dir, "compose.yaml")) + + t.Run("empty output", func(t *testing.T) { + for _, out := range []string{"", " ", "null"} { + projects, err := parseComposeLs(out) + if err != nil { + t.Fatalf("parseComposeLs(%q): %v", out, err) + } + if projects == nil || len(projects) != 0 { + t.Errorf("parseComposeLs(%q) = %v, want an empty, non-nil slice", out, projects) + } + } + }) + + t.Run("json array", func(t *testing.T) { + out := `[{"Name":"web","Status":"running(2)","ConfigFiles":"` + file + `"}, + {"Name":"idle","Status":"exited(1)","ConfigFiles":""}]` + projects, err := parseComposeLs(out) + if err != nil { + t.Fatalf("parseComposeLs: %v", err) + } + if len(projects) != 2 { + t.Fatalf("got %d projects, want 2", len(projects)) + } + if projects[0].Name != "web" || projects[0].Path != file || projects[0].Source != "engine" { + t.Errorf("first project = %+v, want web at %q from the engine", projects[0], file) + } + if !projects[0].Running { + t.Error(`status "running(2)" should mark the project running`) + } + if projects[1].Running || projects[1].Path != "" { + t.Errorf("second project = %+v, want not running with no path", projects[1]) + } + }) + + t.Run("ndjson fallback", func(t *testing.T) { + // Older docker versions emit one object per line rather than an array. + out := `{"Name":"a","Status":"running(1)","ConfigFiles":""}` + "\n" + + `{"Name":"b","Status":"exited(0)","ConfigFiles":""}` + "\n" + projects, err := parseComposeLs(out) + if err != nil { + t.Fatalf("parseComposeLs: %v", err) + } + if len(projects) != 2 || projects[0].Name != "a" || projects[1].Name != "b" { + t.Errorf("parseComposeLs = %+v, want projects a and b", projects) + } + }) + + t.Run("config files that no longer exist are dropped", func(t *testing.T) { + // A project can outlive the checkout it was started from. + projects, err := parseComposeLs(`[{"Name":"web","ConfigFiles":"` + filepath.Join(dir, "gone.yaml") + `"}]`) + if err != nil { + t.Fatalf("parseComposeLs: %v", err) + } + if len(projects) != 1 || projects[0].Path != "" || len(projects[0].ConfigFiles) != 0 { + t.Errorf("parseComposeLs = %+v, want the project with no files", projects) + } + }) + + t.Run("unparseable output", func(t *testing.T) { + _, err := parseComposeLs("not json at all") + if err == nil || !strings.Contains(err.Error(), "parse compose ls") { + t.Errorf("err = %v, want a parse compose ls error", err) + } + }) +} + +func TestParseComposePs(t *testing.T) { + t.Run("empty output", func(t *testing.T) { + for _, out := range []string{"", "null"} { + services, err := parseComposePs(out) + if err != nil { + t.Fatalf("parseComposePs(%q): %v", out, err) + } + if len(services) != 0 { + t.Errorf("parseComposePs(%q) = %+v, want none", out, services) + } + } + }) + + t.Run("json array", func(t *testing.T) { + out := `[{"Service":"web","State":"running","Status":"Up 2 hours","Image":"nginx","Project":"site"}]` + services, err := parseComposePs(out) + if err != nil { + t.Fatalf("parseComposePs: %v", err) + } + want := ServiceInfo{Name: "web", State: "running", Status: "Up 2 hours", Image: "nginx", Project: "site"} + if len(services) != 1 || services[0] != want { + t.Errorf("parseComposePs = %+v, want [%+v]", services, want) + } + }) + + t.Run("ndjson", func(t *testing.T) { + out := `{"Service":"web","State":"running"}` + "\n" + `{"Service":"db","State":"exited"}` + "\n" + services, err := parseComposePs(out) + if err != nil { + t.Fatalf("parseComposePs: %v", err) + } + if len(services) != 2 || services[0].Name != "web" || services[1].Name != "db" { + t.Errorf("parseComposePs = %+v, want web and db", services) + } + }) + + t.Run("falls back to the container name", func(t *testing.T) { + // Compose v2 reports Service; some versions only carry Name. + services, err := parseComposePs(`[{"Name":"site-web-1","State":"running"}]`) + if err != nil { + t.Fatalf("parseComposePs: %v", err) + } + if len(services) != 1 || services[0].Name != "site-web-1" { + t.Errorf("parseComposePs = %+v, want the container name as the service name", services) + } + }) + + t.Run("unparseable output", func(t *testing.T) { + if _, err := parseComposePs(`[{"Service":`); err == nil { + t.Error("expected an error for a truncated array") + } + if _, err := parseComposePs("plain text\n"); err == nil { + t.Error("expected an error for non-JSON lines") + } + }) +} diff --git a/sidecar/internal/engine/mode_test.go b/sidecar/internal/engine/mode_test.go new file mode 100644 index 0000000..32726ab --- /dev/null +++ b/sidecar/internal/engine/mode_test.go @@ -0,0 +1,129 @@ +package engine + +import ( + "os" + "path/filepath" + "testing" +) + +func tempStorePath(t *testing.T) string { + t.Helper() + return filepath.Join(t.TempDir(), "nested", "engine.json") +} + +func TestNewStoreDefaultsWhenNoFileExists(t *testing.T) { + cfg := NewStore(tempStorePath(t)).Get() + + if cfg.Mode != ModeAttach { + t.Errorf("Mode = %q, want %q — attach is the only mode that works today", cfg.Mode, ModeAttach) + } + if cfg.EmbedAvailable { + t.Error("EmbedAvailable should be false; the embed runtime is a scaffold") + } + if cfg.EmbedStatus != "not_implemented" { + t.Errorf("EmbedStatus = %q, want not_implemented", cfg.EmbedStatus) + } + if cfg.CPU != 4 || cfg.MemoryMiB != 4096 || cfg.DiskGiB != 64 || !cfg.ResourceSaver { + t.Errorf("resource defaults = %+v, want cpu=4 mem=4096 disk=64 saver=true", cfg) + } +} + +func TestSetModeEmbedRecordsTheRequestButNotAvailability(t *testing.T) { + s := NewStore(tempStorePath(t)) + if err := s.SetMode(ModeEmbed); err != nil { + t.Fatalf("SetMode: %v", err) + } + + cfg := s.Get() + if cfg.Mode != ModeEmbed { + t.Errorf("Mode = %q, want %q", cfg.Mode, ModeEmbed) + } + if cfg.EmbedAvailable { + t.Error("selecting embed must not claim the embed runtime is available") + } + if cfg.EmbedStatus == "" || cfg.EmbedStatus == "not_implemented" { + t.Errorf("EmbedStatus = %q, want an explanation of the scaffold state", cfg.EmbedStatus) + } +} + +func TestSetModeRejectsUnknownModes(t *testing.T) { + // The mode arrives from PUT /api/engine, so anything off the two-value + // enum falls back to attach rather than persisting a mode nothing honours. + for _, mode := range []Mode{"", "docker", "EMBED"} { + t.Run(string(mode), func(t *testing.T) { + s := NewStore(tempStorePath(t)) + if err := s.SetMode(mode); err != nil { + t.Fatalf("SetMode(%q): %v", mode, err) + } + if got := s.Get().Mode; got != ModeAttach { + t.Errorf("SetMode(%q) left Mode = %q, want %q", mode, got, ModeAttach) + } + }) + } +} + +func TestSetModePersistsAcrossStores(t *testing.T) { + path := tempStorePath(t) + if err := NewStore(path).SetMode(ModeEmbed); err != nil { + t.Fatalf("SetMode: %v", err) + } + + // A relaunch reads the file back rather than resetting to attach. + if got := NewStore(path).Get().Mode; got != ModeEmbed { + t.Errorf("reloaded Mode = %q, want %q", got, ModeEmbed) + } +} + +func TestUpdatePersistsMutations(t *testing.T) { + path := tempStorePath(t) + s := NewStore(path) + if err := s.Update(func(c *Config) { + c.CPU = 8 + c.VirtioFSShares = []string{"/srv/work"} + }); err != nil { + t.Fatalf("Update: %v", err) + } + + cfg := NewStore(path).Get() + if cfg.CPU != 8 { + t.Errorf("reloaded CPU = %d, want 8", cfg.CPU) + } + if len(cfg.VirtioFSShares) != 1 || cfg.VirtioFSShares[0] != "/srv/work" { + t.Errorf("reloaded VirtioFSShares = %v, want [/srv/work]", cfg.VirtioFSShares) + } +} + +func TestLoadFillsInAMissingMode(t *testing.T) { + path := tempStorePath(t) + if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(path, []byte(`{"cpu":2}`), 0o644); err != nil { + t.Fatal(err) + } + + cfg := NewStore(path).Get() + if cfg.Mode != ModeAttach { + t.Errorf("Mode = %q, want %q for a file that omits it", cfg.Mode, ModeAttach) + } + if cfg.CPU != 2 { + t.Errorf("CPU = %d, want the stored 2", cfg.CPU) + } +} + +func TestCorruptFileFallsBackToDefaults(t *testing.T) { + // A half-written engine.json must not leave the sidecar with a zero-value + // config (mode "", cpu 0) that the UI cannot render. + path := tempStorePath(t) + if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(path, []byte(`{"mode":`), 0o644); err != nil { + t.Fatal(err) + } + + cfg := NewStore(path).Get() + if cfg.Mode != ModeAttach || cfg.CPU != 4 { + t.Errorf("config = %+v, want the defaults", cfg) + } +} diff --git a/sidecar/internal/helm/service.go b/sidecar/internal/helm/service.go index ea44b67..a16e5af 100644 --- a/sidecar/internal/helm/service.go +++ b/sidecar/internal/helm/service.go @@ -44,6 +44,12 @@ func (s *Service) List(ctx context.Context, ns string, allNamespaces bool) ([]Re if err != nil { return nil, err } + return parseReleaseList(out) +} + +// parseReleaseList turns `helm list -o json` output into release summaries. +// Split out from List so it can be exercised without a helm binary. +func parseReleaseList(out string) ([]ReleaseSummary, error) { var raw []map[string]any if err := json.Unmarshal([]byte(out), &raw); err != nil { return nil, err @@ -53,7 +59,7 @@ func (s *Service) List(ctx context.Context, ns string, allNamespaces bool) ([]Re result = append(result, ReleaseSummary{ Name: str(item["name"]), Namespace: str(item["namespace"]), - Revision: fmt.Sprint(item["revision"]), + Revision: str(item["revision"]), Status: str(item["status"]), Chart: str(item["chart"]), AppVersion: str(item["app_version"]), diff --git a/sidecar/internal/helm/service_test.go b/sidecar/internal/helm/service_test.go new file mode 100644 index 0000000..2af73fb --- /dev/null +++ b/sidecar/internal/helm/service_test.go @@ -0,0 +1,141 @@ +package helm + +import ( + "os" + "strings" + "testing" +) + +func TestParseReleaseList(t *testing.T) { + t.Run("maps helm's snake_case fields", func(t *testing.T) { + out := `[{"name":"ingress","namespace":"kube-system","revision":3,"status":"deployed", + "chart":"ingress-nginx-4.10.0","app_version":"1.10.0","updated":"2026-01-02 10:00:00"}]` + releases, err := parseReleaseList(out) + if err != nil { + t.Fatalf("parseReleaseList: %v", err) + } + if len(releases) != 1 { + t.Fatalf("got %d releases, want 1", len(releases)) + } + want := ReleaseSummary{ + Name: "ingress", Namespace: "kube-system", Revision: "3", Status: "deployed", + Chart: "ingress-nginx-4.10.0", AppVersion: "1.10.0", Updated: "2026-01-02 10:00:00", + } + if releases[0] != want { + t.Errorf("release = %+v, want %+v", releases[0], want) + } + }) + + t.Run("revision is a JSON number but reaches the UI as a plain integer", func(t *testing.T) { + releases, err := parseReleaseList(`[{"name":"a","revision":12}]`) + if err != nil { + t.Fatalf("parseReleaseList: %v", err) + } + if releases[0].Revision != "12" { + t.Errorf("Revision = %q, want %q (not a float rendering)", releases[0].Revision, "12") + } + }) + + t.Run("missing fields render empty, not ", func(t *testing.T) { + releases, err := parseReleaseList(`[{"name":"a"}]`) + if err != nil { + t.Fatalf("parseReleaseList: %v", err) + } + got := releases[0] + if got.Revision != "" || got.Status != "" || got.AppVersion != "" { + t.Errorf("release = %+v, want empty strings for the absent fields", got) + } + }) + + t.Run("no releases", func(t *testing.T) { + releases, err := parseReleaseList(`[]`) + if err != nil { + t.Fatalf("parseReleaseList: %v", err) + } + if releases == nil || len(releases) != 0 { + t.Errorf("parseReleaseList([]) = %v, want an empty, non-nil slice", releases) + } + }) + + t.Run("unparseable output", func(t *testing.T) { + if _, err := parseReleaseList("Error: Kubernetes cluster unreachable"); err == nil { + t.Error("expected an error for non-JSON output") + } + }) +} + +func TestMaybeValuesFile(t *testing.T) { + t.Run("blank yaml adds nothing", func(t *testing.T) { + for _, yaml := range []string{"", " \n\t"} { + args := []string{"install", "web", "./chart"} + cleanup, err := maybeValuesFile(yaml, &args) + if err != nil { + t.Fatalf("maybeValuesFile(%q): %v", yaml, err) + } + if cleanup != nil { + t.Errorf("maybeValuesFile(%q) returned a cleanup func with no file written", yaml) + } + if len(args) != 3 { + t.Errorf("args = %q, want them untouched", args) + } + } + }) + + t.Run("yaml is written and passed with -f", func(t *testing.T) { + args := []string{"install", "web", "./chart"} + cleanup, err := maybeValuesFile("replicaCount: 2\n", &args) + if err != nil { + t.Fatalf("maybeValuesFile: %v", err) + } + if cleanup == nil { + t.Fatal("a written values file must come with a cleanup func") + } + if len(args) != 5 || args[3] != "-f" { + t.Fatalf("args = %q, want a trailing -f ", args) + } + + path := args[4] + body, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + if !strings.Contains(string(body), "replicaCount: 2") { + t.Errorf("values file = %q, want the request's YAML", body) + } + + // Values commonly carry credentials, so the temp file must not be + // readable by other local accounts. + st, err := os.Stat(path) + if err != nil { + t.Fatal(err) + } + if perm := st.Mode().Perm(); perm != 0o600 { + t.Errorf("values file mode = %o, want 600", perm) + } + + cleanup() + if _, err := os.Stat(path); !os.IsNotExist(err) { + t.Errorf("cleanup left %q behind (err=%v)", path, err) + } + }) +} + +func TestStr(t *testing.T) { + tests := []struct { + name string + in any + want string + }{ + {name: "nil", in: nil, want: ""}, + {name: "string", in: "deployed", want: "deployed"}, + {name: "json number", in: float64(7), want: "7"}, + {name: "bool", in: true, want: "true"}, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + if got := str(tc.in); got != tc.want { + t.Errorf("str(%v) = %q, want %q", tc.in, got, tc.want) + } + }) + } +}