From 55d5371a240e0c482a19bf8d364e1aa80ce31013 Mon Sep 17 00:00:00 2001 From: "juvenal.diaz" Date: Thu, 15 Oct 2026 09:06:19 -0600 Subject: [PATCH] feat: add remote Jeannie execution API --- cmd/jeannie-server/main.go | 217 ++++++++++++++++++++++++++++++++ cmd/jeannie-server/main_test.go | 68 ++++++++++ docs/jeannie-remote-api.md | 26 ++++ jeannie | 4 + scripts/jeannie-remote | 40 ++++++ scripts/jeannie-server | 17 +++ 6 files changed, 372 insertions(+) create mode 100644 cmd/jeannie-server/main.go create mode 100644 cmd/jeannie-server/main_test.go create mode 100644 docs/jeannie-remote-api.md create mode 100755 scripts/jeannie-remote create mode 100755 scripts/jeannie-server diff --git a/cmd/jeannie-server/main.go b/cmd/jeannie-server/main.go new file mode 100644 index 0000000..180c4d6 --- /dev/null +++ b/cmd/jeannie-server/main.go @@ -0,0 +1,217 @@ +package main + +import ( + "context" + "crypto/rand" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "net/http" + "os" + "os/exec" + "path/filepath" + "sort" + "strings" + "sync" + "time" +) + +const maxOutputBytes = 1 << 20 + +var allowedCommands = map[string]bool{ + "capacity": true, "capacity-advisor": true, "capacity-limits": true, + "cluster-profile": true, "doctor-cluster": true, "doctor-edge": true, + "doctor-gitea": true, "doctor-homelab": true, "doctor-k8s": true, + "doctor-rpi": true, "explain": true, "inventory-check": true, + "map": true, "route-inventory": true, "scorecard": true, "status": true, +} + +type executeRequest struct { + Command string `json:"command"` + Args []string `json:"args,omitempty"` +} + +type execution struct { + ID string `json:"id"` + Command string `json:"command"` + Args []string `json:"args,omitempty"` + Status string `json:"status"` + Output string `json:"output,omitempty"` + ExitCode int `json:"exit_code,omitempty"` + Error string `json:"error,omitempty"` + StartedAt time.Time `json:"started_at"` + EndedAt *time.Time `json:"ended_at,omitempty"` +} + +type server struct { + mu sync.RWMutex + exec map[string]*execution + repoRoot string + token string +} + +func main() { + root := os.Getenv("JEANNIE_SERVER_REPO_ROOT") + if root == "" { + root, _ = os.Getwd() + } + root, _ = filepath.Abs(root) + s := &server{exec: make(map[string]*execution), repoRoot: root, token: os.Getenv("JEANNIE_SERVER_TOKEN")} + mux := http.NewServeMux() + mux.HandleFunc("/v1/health", s.auth(s.health)) + mux.HandleFunc("/v1/commands", s.auth(s.commands)) + mux.HandleFunc("/v1/execute", s.auth(s.execute)) + mux.HandleFunc("/v1/executions/", s.auth(s.execution)) + addr := os.Getenv("JEANNIE_SERVER_ADDR") + if addr == "" { + addr = "127.0.0.1:8787" + } + if os.Getenv("JEANNIE_SERVER_TOKEN") == "" && !strings.HasPrefix(addr, "127.0.0.1:") && !strings.HasPrefix(addr, "localhost:") { + fmt.Fprintln(os.Stderr, "JEANNIE_SERVER_TOKEN is required when the API is not loopback-bound") + os.Exit(2) + } + httpServer := &http.Server{Addr: addr, Handler: logging(mux), ReadHeaderTimeout: 5 * time.Second} + fmt.Printf("Jeannie API listening on %s\n", addr) + if err := httpServer.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) { + fmt.Fprintln(os.Stderr, err) + os.Exit(1) + } +} + +func (s *server) auth(next http.HandlerFunc) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + if s.token != "" && r.Header.Get("Authorization") != "Bearer "+s.token { + writeJSON(w, http.StatusUnauthorized, map[string]string{"error": "unauthorized"}) + return + } + next(w, r) + } +} + +func (s *server) health(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodGet { + writeJSON(w, http.StatusMethodNotAllowed, map[string]string{"error": "method not allowed"}) + return + } + writeJSON(w, http.StatusOK, map[string]string{"status": "ok"}) +} + +func (s *server) commands(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodGet { + writeJSON(w, http.StatusMethodNotAllowed, map[string]string{"error": "method not allowed"}) + return + } + commands := make([]string, 0, len(allowedCommands)) + for command := range allowedCommands { + commands = append(commands, command) + } + sort.Strings(commands) + writeJSON(w, http.StatusOK, map[string]any{"commands": commands}) +} + +func (s *server) execute(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodPost { + writeJSON(w, http.StatusMethodNotAllowed, map[string]string{"error": "method not allowed"}) + return + } + var request executeRequest + if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 64*1024)).Decode(&request); err != nil { + writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid JSON"}) + return + } + request.Command = strings.TrimSpace(request.Command) + if !allowedCommands[request.Command] { + writeJSON(w, http.StatusForbidden, map[string]string{"error": "command is not remotely enabled"}) + return + } + item := &execution{ID: newID(), Command: request.Command, Args: request.Args, Status: "queued", StartedAt: time.Now().UTC()} + s.mu.Lock() + s.exec[item.ID] = item + s.mu.Unlock() + go s.run(item) + writeJSON(w, http.StatusAccepted, item) +} + +func (s *server) run(item *execution) { + s.update(item.ID, func(item *execution) { item.Status = "running" }) + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Minute) + defer cancel() + args := append([]string{item.Command}, item.Args...) + command := exec.CommandContext(ctx, filepath.Join(s.repoRoot, "jeannie"), args...) + command.Dir = s.repoRoot + command.Env = append(os.Environ(), "JEANNIE_REMOTE_SERVER=true") + output, err := command.CombinedOutput() + if len(output) > maxOutputBytes { + output = append(output[:maxOutputBytes], []byte("\n[output truncated]\n")...) + } + ended := time.Now().UTC() + s.update(item.ID, func(item *execution) { + item.Output, item.EndedAt, item.Status = redact(string(output)), &ended, "succeeded" + if err == nil { + return + } + item.Status, item.Error, item.ExitCode = "failed", err.Error(), 1 + if exitErr, ok := err.(*exec.ExitError); ok { + item.ExitCode = exitErr.ExitCode() + } + }) +} + +func (s *server) execution(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodGet { + writeJSON(w, http.StatusMethodNotAllowed, map[string]string{"error": "method not allowed"}) + return + } + id := strings.TrimPrefix(r.URL.Path, "/v1/executions/") + s.mu.RLock() + item, ok := s.exec[id] + if ok { + copy := *item + item = © + } + s.mu.RUnlock() + if !ok { + writeJSON(w, http.StatusNotFound, map[string]string{"error": "execution not found"}) + return + } + writeJSON(w, http.StatusOK, item) +} + +func (s *server) update(id string, fn func(*execution)) { + s.mu.Lock() + defer s.mu.Unlock() + if item, ok := s.exec[id]; ok { + fn(item) + } +} + +func newID() string { + var data [16]byte + if _, err := rand.Read(data[:]); err != nil { + return fmt.Sprintf("execution-%d", time.Now().UnixNano()) + } + return hex.EncodeToString(data[:]) +} + +func redact(value string) string { + for _, key := range []string{"JEANNIE_SERVER_TOKEN", "OPENROUTER_API_KEY", "NVIDIA_API_KEY"} { + if secret := os.Getenv(key); secret != "" { + value = strings.ReplaceAll(value, secret, "[REDACTED]") + } + } + return value +} + +func writeJSON(w http.ResponseWriter, status int, value any) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(status) + _ = json.NewEncoder(w).Encode(value) +} + +func logging(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + fmt.Printf("%s %s %s\n", time.Now().UTC().Format(time.RFC3339), r.Method, r.URL.Path) + next.ServeHTTP(w, r) + }) +} diff --git a/cmd/jeannie-server/main_test.go b/cmd/jeannie-server/main_test.go new file mode 100644 index 0000000..e380db2 --- /dev/null +++ b/cmd/jeannie-server/main_test.go @@ -0,0 +1,68 @@ +package main + +import ( + "bytes" + "encoding/json" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "testing" + "time" +) + +func TestServerRequiresTokenAndAllowlistsCommands(t *testing.T) { + s := &server{exec: make(map[string]*execution), token: "secret"} + mux := http.NewServeMux() + mux.HandleFunc("/v1/execute", s.auth(s.execute)) + requestBody, _ := json.Marshal(executeRequest{Command: "nuke"}) + body := bytes.NewBuffer(requestBody) + req, err := http.NewRequest(http.MethodPost, "/v1/execute", body) + if err != nil { t.Fatal(err) } + req.Header.Set("Content-Type", "application/json") + response := httptest.NewRecorder() + mux.ServeHTTP(response, req) + if response.Code != http.StatusUnauthorized { t.Fatalf("status = %d", response.Code) } + + body = bytes.NewBuffer(requestBody) + req, err = http.NewRequest(http.MethodPost, "/v1/execute", body) + if err != nil { t.Fatal(err) } + req.Header.Set("Authorization", "Bearer secret") + response = httptest.NewRecorder() + mux.ServeHTTP(response, req) + if response.Code != http.StatusForbidden { t.Fatalf("status = %d", response.Code) } +} + +func TestServerExecutesAllowlistedCommand(t *testing.T) { + repo := t.TempDir() + jeannie := filepath.Join(repo, "jeannie") + if err := os.WriteFile(jeannie, []byte("#!/bin/sh\nprintf 'remote-ok %s\\n' \"$1\"\n"), 0755); err != nil { t.Fatal(err) } + s := &server{exec: make(map[string]*execution), repoRoot: repo} + mux := http.NewServeMux() + mux.HandleFunc("/v1/execute", s.auth(s.execute)) + mux.HandleFunc("/v1/executions/", s.auth(s.execution)) + payload, _ := json.Marshal(executeRequest{Command: "status"}) + req, err := http.NewRequest(http.MethodPost, "/v1/execute", bytes.NewReader(payload)) + if err != nil { t.Fatal(err) } + req.Header.Set("Content-Type", "application/json") + response := httptest.NewRecorder() + mux.ServeHTTP(response, req) + if response.Code != http.StatusAccepted { t.Fatalf("status = %d", response.Code) } + var queued execution + if err := json.NewDecoder(response.Body).Decode(&queued); err != nil { t.Fatal(err) } + + var completed execution + for deadline := time.Now().Add(2 * time.Second); time.Now().Before(deadline); { + req, err = http.NewRequest(http.MethodGet, "/v1/executions/"+queued.ID, nil) + if err != nil { t.Fatal(err) } + response = httptest.NewRecorder() + mux.ServeHTTP(response, req) + if err := json.NewDecoder(response.Body).Decode(&completed); err != nil { t.Fatal(err) } + if completed.Status == "succeeded" { break } + time.Sleep(10 * time.Millisecond) + } + if completed.Status != "succeeded" || !strings.Contains(completed.Output, "remote-ok status") { + t.Fatalf("unexpected execution: %+v", completed) + } +} diff --git a/docs/jeannie-remote-api.md b/docs/jeannie-remote-api.md new file mode 100644 index 0000000..4564a4e --- /dev/null +++ b/docs/jeannie-remote-api.md @@ -0,0 +1,26 @@ +# Jeannie Remote API + +Phase 1 adds a private remote-execution API. The local Jeannie remote client +submits a read-only command to a Jeannie API running on Debian. The Debian +process executes the existing Jeannie entrypoint; command logic is not +duplicated in the API. + +## Run locally + +Start the server from the Debian checkout: + + JEANNIE_SERVER_ADDR=127.0.0.1:8787 + JEANNIE_SERVER_TOKEN='replace-with-a-secret' + JEANNIE_SERVER_REPO_ROOT=/path/to/my-homelab-configs + ./scripts/jeannie-server + +From a client with network access: + + JEANNIE_REMOTE_URL=http://debian:8787 + JEANNIE_REMOTE_TOKEN='replace-with-a-secret' + ./jeannie remote status + +The initial allowlist contains read-only commands only. Execution state is +stored in memory and command output is returned through +GET /v1/executions/{id}. It is not a public edge service and does not accept +arbitrary shell commands. diff --git a/jeannie b/jeannie index 812db0d..af50200 100755 --- a/jeannie +++ b/jeannie @@ -102,6 +102,7 @@ Operator View And Reports impact [--since REF] [PATH...] Explain affected lab areas before changes. review-last-change [REF] Summarize changed files, impact, validation. map [--dot] Print the homelab dependency map. + remote [args...] Execute an allowlisted command on Debian. change-journal {list|path} Show risky-command journal entries. release-snapshot Write a pre-change release snapshot. @@ -362,6 +363,9 @@ case "${1:-}" in map) homelab_map "$@" ;; + remote) + "${REPO_ROOT}/scripts/jeannie-remote" "${@:2}" + ;; validate) validate_homelab ;; diff --git a/scripts/jeannie-remote b/scripts/jeannie-remote new file mode 100755 index 0000000..108bd65 --- /dev/null +++ b/scripts/jeannie-remote @@ -0,0 +1,40 @@ +#!/usr/bin/env bash +set -euo pipefail +REMOTE_URL="${JEANNIE_REMOTE_URL:-http://127.0.0.1:8787}" +REMOTE_TOKEN="${JEANNIE_REMOTE_TOKEN:-${JEANNIE_SERVER_TOKEN:-}}" +if [[ $# -lt 1 ]]; then + echo "Usage: ./jeannie remote [args...]" >&2 + exit 2 +fi +export JEANNIE_REMOTE_URL="${REMOTE_URL}" REMOTE_TOKEN +python3 - "$@" <<'PY' +import json, os, sys, time, urllib.error, urllib.request +url = os.environ["JEANNIE_REMOTE_URL"].rstrip("/") +command, *args = sys.argv[1:] +headers = {"Content-Type": "application/json"} +if os.environ.get("REMOTE_TOKEN"): + headers["Authorization"] = "Bearer " + os.environ["REMOTE_TOKEN"] +def request(method, path, body=None): + payload = None if body is None else json.dumps(body).encode() + req = urllib.request.Request(url + path, data=payload, headers=headers, method=method) + try: + with urllib.request.urlopen(req, timeout=15) as response: + return response.status, json.loads(response.read()) + except urllib.error.HTTPError as exc: + print(exc.read().decode(errors="replace"), file=sys.stderr) + return exc.code, {} +status, result = request("POST", "/v1/execute", {"command": command, "args": args}) +if status != 202: + sys.exit(1) +execution_id = result["id"] +while True: + status, result = request("GET", "/v1/executions/" + execution_id) + if status != 200: + sys.exit(1) + if result["status"] in ("succeeded", "failed"): + output = result.get("output", "") + if output: + print(output, end="" if output.endswith("\n") else "\n") + sys.exit(int(result.get("exit_code", 0))) + time.sleep(0.5) +PY diff --git a/scripts/jeannie-server b/scripts/jeannie-server new file mode 100755 index 0000000..537a82f --- /dev/null +++ b/scripts/jeannie-server @@ -0,0 +1,17 @@ +#!/usr/bin/env bash +set -euo pipefail +REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +SERVER_BIN="${JEANNIE_SERVER_BIN:-${REPO_ROOT}/.lab/bin/jeannie-server}" +server_sources_newer() { + local source + while IFS= read -r source; do + [[ "${source}" -nt "${SERVER_BIN}" ]] && return 0 + done < <(find "${REPO_ROOT}/cmd/jeannie-server" -name '*.go' -type f) + return 1 +} +if [[ ! -x "${SERVER_BIN}" || "${REPO_ROOT}/go.mod" -nt "${SERVER_BIN}" ]] || server_sources_newer; then + command -v go >/dev/null 2>&1 || { echo "go is required to build ${SERVER_BIN}" >&2; exit 1; } + mkdir -p "$(dirname "${SERVER_BIN}")" + GOCACHE="${GOCACHE:-${REPO_ROOT}/.lab/go-build-cache}" go build -o "${SERVER_BIN}" "${REPO_ROOT}/cmd/jeannie-server" +fi +exec "${SERVER_BIN}" "$@"