package libraryfreeze import ( "context" "encoding/json" "net" "net/http" "os" "path/filepath" "strings" "testing" "time" ) func TestDockerControllerRefusesWrongScopeAndUnsafeRuntime(t *testing.T) { for _, mode := range []string{"production", "wrong-source", "storage", "paused", "restarting", "dead", "no-health", "short-id", "wrong-response-id", "duplicate"} { t.Run(mode, func(t *testing.T) { root, err := os.MkdirTemp(os.TempDir(), "kgf-") if err != nil { t.Fatal(err) } defer os.RemoveAll(root) socket := filepath.Join(root, "s") listener, err := net.Listen("unix", socket) if err != nil { t.Fatal(err) } id := strings.Repeat("a", 64) if mode == "short-id" { id = "aaa" } writes := 0 server := &http.Server{Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.Method != "GET" { writes++ w.WriteHeader(204) return } if strings.HasSuffix(r.URL.Path, "/containers/json") { items := []map[string]string{{"Id": id}} if mode == "duplicate" { items = append(items, items[0]) } _ = json.NewEncoder(w).Encode(items) return } labels := map[string]string{sourceLabel: "test-source", environmentLabel: "test", roleLabel: "writer"} switch mode { case "production": labels[environmentLabel] = "production" case "wrong-source": labels[sourceLabel] = "different-source" case "storage": labels[roleLabel] = "database" } state := map[string]any{"Running": true, "Status": "running", "Health": map[string]string{"Status": "healthy"}} switch mode { case "paused": state["Paused"] = true case "restarting": state["Restarting"] = true case "dead": state["Dead"] = true case "no-health": delete(state, "Health") } actualID := id if mode == "wrong-response-id" { actualID = strings.Repeat("b", 64) } _ = json.NewEncoder(w).Encode(map[string]any{"Id": actualID, "Config": map[string]any{"Labels": labels}, "State": state}) })} go server.Serve(listener) defer server.Close() d, err := NewDockerController(socket, "test-source", time.Second) if err != nil { t.Fatal(err) } defer d.Close() journalRoot := filepath.Join(root, "j") if err = os.Mkdir(journalRoot, 0700); err != nil { t.Fatal(err) } e, err := Open(journalRoot, "test-source", d) if err != nil { t.Fatal(err) } defer e.Close() _, err = e.Run(context.Background(), "blocked", func(context.Context) (string, error) { t.Fatal("unsafe capture"); return "", nil }) if err == nil || writes != 0 { t.Fatalf("unsafe source changed: err=%v writes=%d", err, writes) } }) } }