From de7024935be7928b1e566c8fdec8797d42a276f8 Mon Sep 17 00:00:00 2001 From: "juvenal.diaz" Date: Fri, 4 Dec 2026 15:44:30 -0600 Subject: [PATCH] Add OpsProof read-only status overview --- apps/opsproof/README.md | 8 + .../overlay/handlers/welcome/welcome.go | 46 +++++ .../overlay/resources/js/pages/Welcome.tsx | 156 ++++++++++++++++- apps/opsproof/overlay/services/jeannie.go | 158 ++++++++++++++++++ .../opsproof/overlay/services/jeannie_test.go | 67 ++++++++ apps/opsproof/overlay/services/services.go | 20 +++ docs/jeannie.1.md | 7 + docs/opsproof-architecture.md | 2 + lib/jeannie/pipeline.sh | 18 ++ .../jeannie/test_privacy_services_pipeline.py | 13 ++ 10 files changed, 489 insertions(+), 6 deletions(-) create mode 100644 apps/opsproof/overlay/handlers/welcome/welcome.go create mode 100644 apps/opsproof/overlay/services/jeannie.go create mode 100644 apps/opsproof/overlay/services/jeannie_test.go create mode 100644 apps/opsproof/overlay/services/services.go diff --git a/apps/opsproof/README.md b/apps/opsproof/README.md index 54d7e3b..0d2db0a 100644 --- a/apps/opsproof/README.md +++ b/apps/opsproof/README.md @@ -49,6 +49,14 @@ PostgreSQL. A successful redeployment explicitly restarts the systemd service so updated listen addresses and other environment values take effect. It does not replace Debian's system Go. +The landing page collects `status all --json` through the authenticated +Jeannie API on the server side. Browser props contain only the status, area, +check, and summary fields; the bearer token and raw diagnostic details remain +on Debian. If the API, token, execution, or JSON contract is unavailable, +OpsProof fails closed and labels the overview unavailable instead of presenting +stale data as current. Warning and failing checks show a read-only focused +Doctor command but cannot submit it. + ## Security boundary OpsProof is not a shell console. diff --git a/apps/opsproof/overlay/handlers/welcome/welcome.go b/apps/opsproof/overlay/handlers/welcome/welcome.go new file mode 100644 index 0000000..0ebeb0e --- /dev/null +++ b/apps/opsproof/overlay/handlers/welcome/welcome.go @@ -0,0 +1,46 @@ +package welcome + +import ( + "log" + + laravel "go.laravel.com" + "go.laravel.com/inertia" + "go.laravel.com/web" + + "app/services" +) + +type overview struct { + Available bool `json:"available"` + Message string `json:"message"` + Title string `json:"title"` + Mode string `json:"mode"` + Rows []services.StatusRow `json:"rows"` + Cluster services.ClusterIdentity `json:"cluster"` + CollectedAt string `json:"collectedAt"` +} + +func Show(request *web.Request) *web.Response { + status := overview{ + Message: "Jeannie status is temporarily unavailable.", + Rows: []services.StatusRow{}, + } + + snapshot, err := services.From(request.Context()).Jeannie.Status(request.Context()) + if err != nil { + log.Printf("OpsProof could not collect Jeannie status: %v", err) + } else { + status.Available = true + status.Message = "Live read-only status collected through the Jeannie API." + status.Title = snapshot.Title + status.Mode = snapshot.Mode + status.Rows = snapshot.Rows + status.Cluster = snapshot.Cluster + status.CollectedAt = snapshot.CollectedAt + } + + return inertia.Render("Welcome", inertia.Props{ + "laravelVersion": laravel.Version, + "overview": status, + }) +} diff --git a/apps/opsproof/overlay/resources/js/pages/Welcome.tsx b/apps/opsproof/overlay/resources/js/pages/Welcome.tsx index 845b682..f5595d8 100644 --- a/apps/opsproof/overlay/resources/js/pages/Welcome.tsx +++ b/apps/opsproof/overlay/resources/js/pages/Welcome.tsx @@ -1,5 +1,26 @@ interface Props { laravelVersion: string; + overview: Overview; +} + +interface StatusRow { + status: 'ok' | 'warn' | 'fail' | 'skip'; + area: string; + check: string; + summary: string; +} + +interface Overview { + available: boolean; + message: string; + title: string; + mode: string; + rows: StatusRow[]; + cluster: { + profile: string; + runtime: string; + }; + collectedAt: string; } const evidence = [ @@ -24,7 +45,128 @@ function Mark() { ); } -export default function Welcome({ laravelVersion }: Props) { +const statusTone = { + ok: 'border-emerald-300/20 bg-emerald-300/10 text-emerald-200', + warn: 'border-amber-300/20 bg-amber-300/10 text-amber-200', + fail: 'border-rose-300/20 bg-rose-300/10 text-rose-200', + skip: 'border-slate-500/20 bg-slate-500/10 text-slate-400', +}; + +function doctorCommand(row: StatusRow) { + if (row.area === 'Kubernetes apps') { + return `./jeannie doctor cluster ${row.check}`; + } + if (row.area.startsWith('Kubernetes')) { + return './jeannie doctor cluster'; + } + if (row.area.startsWith('Orange Pi')) { + return './jeannie doctor opi5'; + } + if (row.area.startsWith('RPi4')) { + return './jeannie doctor rpi'; + } + if (row.area.startsWith('OCI edge')) { + return './jeannie doctor oci'; + } + return './jeannie doctor debian'; +} + +function LiveOverview({ overview }: { overview: Overview }) { + const grouped = overview.rows.reduce>((areas, row) => { + (areas[row.area] ??= []).push(row); + return areas; + }, {}); + const healthy = overview.rows.filter((row) => row.status === 'ok').length; + const attention = overview.rows.filter((row) => row.status === 'warn' || row.status === 'fail').length; + + return ( +
+
+
+

Live read-only inventory

+

Homelab operational overview

+

{overview.message}

+
+ + Refresh evidence + +
+ + {!overview.available ? ( +
+
+

Jeannie control plane unavailable

+

+ OpsProof failed closed. No cached state is presented as current and no action can be submitted. +

+
+
+ ) : ( + <> +
+
+

Healthy checks

+

{healthy}

+
+
+

Needs attention

+

{attention}

+
+
+

Cluster profile

+

{overview.cluster.profile || 'not selected'}

+
+
+

Runtime

+

{overview.cluster.runtime || 'unknown'}

+
+
+ +
+ {Object.entries(grouped).map(([area, rows]) => ( +
+
+

{area}

+ {rows.length} checks +
+
+ {rows.map((row) => ( +
+
+
+

{row.check}

+

+ Desired: declared intent satisfied +

+

+ Observed: {row.summary || row.status} +

+
+ + {row.status} + +
+ {(row.status === 'warn' || row.status === 'fail') && ( + + {doctorCommand(row)} + + )} +
+ ))} +
+
+ ))} +
+

+ COLLECTED {overview.collectedAt || 'unknown'} · MODE {overview.mode || 'fast'} · bearer token retained server-side +

+ + )} +
+ ); +} + +export default function Welcome({ laravelVersion, overview }: Props) { return (
@@ -39,11 +181,11 @@ export default function Welcome({ laravelVersion }: Props) {
- - Sanitized demo + + Read-only live view - - Control plane available + + Control plane {overview.available ? 'available' : 'unavailable'}
@@ -73,10 +215,12 @@ export default function Welcome({ laravelVersion }: Props) { + +
-

Active incident · OP-0001

+

Sanitized incident scenario · OP-0001

Orange Pi K3s storage became read-only

diff --git a/apps/opsproof/overlay/services/jeannie.go b/apps/opsproof/overlay/services/jeannie.go new file mode 100644 index 0000000..041b563 --- /dev/null +++ b/apps/opsproof/overlay/services/jeannie.go @@ -0,0 +1,158 @@ +package services + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "os" + "strings" + "time" +) + +const maxJeannieResponseBytes = 2 << 20 + +type StatusRow struct { + Status string `json:"status"` + Area string `json:"area"` + Check string `json:"check"` + Summary string `json:"summary"` +} + +type ClusterIdentity struct { + Profile string `json:"profile"` + Runtime string `json:"runtime"` +} + +type StatusSnapshot struct { + Title string `json:"title"` + Mode string `json:"mode"` + Rows []StatusRow `json:"rows"` + Cluster ClusterIdentity `json:"cluster"` + CollectedAt string `json:"collectedAt"` +} + +type JeannieClient struct { + BaseURL string + Token string + HTTPClient *http.Client + PollInterval time.Duration +} + +func NewJeannieClient(baseURL string, token string) *JeannieClient { + return &JeannieClient{ + BaseURL: strings.TrimRight(baseURL, "/"), + Token: token, + HTTPClient: &http.Client{Timeout: 10 * time.Second}, + PollInterval: 250 * time.Millisecond, + } +} + +func NewJeannieClientFromEnv() *JeannieClient { + return NewJeannieClient( + os.Getenv("OPSPROOF_JEANNIE_URL"), + os.Getenv("OPSPROOF_JEANNIE_TOKEN"), + ) +} + +func (client *JeannieClient) Status(ctx context.Context) (StatusSnapshot, error) { + if client.BaseURL == "" || client.Token == "" { + return StatusSnapshot{}, errors.New("Jeannie API connection is not configured") + } + + ctx, cancel := context.WithTimeout(ctx, 30*time.Second) + defer cancel() + + payload, err := json.Marshal(map[string]any{ + "command": "status", + "args": []string{"all", "--json"}, + }) + if err != nil { + return StatusSnapshot{}, fmt.Errorf("encode status request: %w", err) + } + + var submitted execution + if err := client.request(ctx, http.MethodPost, "/v1/execute", bytes.NewReader(payload), &submitted); err != nil { + return StatusSnapshot{}, fmt.Errorf("submit status request: %w", err) + } + if submitted.ID == "" { + return StatusSnapshot{}, errors.New("Jeannie API returned an empty execution ID") + } + + for { + var current execution + if err := client.request(ctx, http.MethodGet, "/v1/executions/"+submitted.ID, nil, ¤t); err != nil { + return StatusSnapshot{}, fmt.Errorf("read status execution: %w", err) + } + + switch current.Status { + case "queued", "running": + timer := time.NewTimer(client.PollInterval) + select { + case <-ctx.Done(): + timer.Stop() + return StatusSnapshot{}, fmt.Errorf("wait for status execution: %w", ctx.Err()) + case <-timer.C: + } + case "succeeded", "failed": + snapshot, err := decodeStatusOutput(current.Output) + if err != nil { + return StatusSnapshot{}, err + } + snapshot.CollectedAt = time.Now().UTC().Format(time.RFC3339) + return snapshot, nil + default: + return StatusSnapshot{}, fmt.Errorf("Jeannie API returned unknown execution state %q", current.Status) + } + } +} + +type execution struct { + ID string `json:"id"` + Status string `json:"status"` + Output string `json:"output"` +} + +func (client *JeannieClient) request(ctx context.Context, method string, path string, body io.Reader, target any) error { + request, err := http.NewRequestWithContext(ctx, method, client.BaseURL+path, body) + if err != nil { + return err + } + request.Header.Set("Authorization", "Bearer "+client.Token) + if body != nil { + request.Header.Set("Content-Type", "application/json") + } + + response, err := client.HTTPClient.Do(request) + if err != nil { + return err + } + defer response.Body.Close() + if response.StatusCode < 200 || response.StatusCode >= 300 { + _, _ = io.Copy(io.Discard, io.LimitReader(response.Body, 4096)) + return fmt.Errorf("Jeannie API returned HTTP %d", response.StatusCode) + } + if err := json.NewDecoder(io.LimitReader(response.Body, maxJeannieResponseBytes)).Decode(target); err != nil { + return fmt.Errorf("decode Jeannie API response: %w", err) + } + return nil +} + +func decodeStatusOutput(output string) (StatusSnapshot, error) { + start := strings.Index(output, "{") + if start < 0 { + return StatusSnapshot{}, errors.New("Jeannie status output did not contain JSON") + } + + var snapshot StatusSnapshot + if err := json.Unmarshal([]byte(output[start:]), &snapshot); err != nil { + return StatusSnapshot{}, fmt.Errorf("decode Jeannie status output: %w", err) + } + if snapshot.Rows == nil { + return StatusSnapshot{}, errors.New("Jeannie status output did not contain rows") + } + return snapshot, nil +} diff --git a/apps/opsproof/overlay/services/jeannie_test.go b/apps/opsproof/overlay/services/jeannie_test.go new file mode 100644 index 0000000..3c7254f --- /dev/null +++ b/apps/opsproof/overlay/services/jeannie_test.go @@ -0,0 +1,67 @@ +package services + +import ( + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "testing" + "time" +) + +func TestStatusUsesAuthenticatedReadOnlyCommand(t *testing.T) { + requestCount := 0 + server := httptest.NewServer(http.HandlerFunc(func(response http.ResponseWriter, request *http.Request) { + if request.Header.Get("Authorization") != "Bearer test-token" { + t.Fatalf("authorization header was not set") + } + + switch request.URL.Path { + case "/v1/execute": + var payload struct { + Command string `json:"command"` + Args []string `json:"args"` + } + if err := json.NewDecoder(request.Body).Decode(&payload); err != nil { + t.Fatal(err) + } + if payload.Command != "status" || len(payload.Args) != 2 || payload.Args[0] != "all" || payload.Args[1] != "--json" { + t.Fatalf("unexpected command payload: %#v", payload) + } + response.WriteHeader(http.StatusAccepted) + _, _ = response.Write([]byte(`{"id":"status-1","status":"queued"}`)) + case "/v1/executions/status-1": + requestCount++ + _, _ = response.Write([]byte(`{"id":"status-1","status":"failed","output":"OCI config loaded\n{\"title\":\"Jeannie Status: all\",\"mode\":\"fast\",\"cluster\":{\"profile\":\"k3s\",\"runtime\":\"k3s\"},\"rows\":[{\"status\":\"fail\",\"area\":\"Kubernetes apps\",\"check\":\"n8n\",\"summary\":\"health=Progressing\",\"detail\":\"private detail\"}]}"}`)) + default: + http.NotFound(response, request) + } + })) + defer server.Close() + + client := NewJeannieClient(server.URL, "test-token") + client.PollInterval = time.Millisecond + snapshot, err := client.Status(context.Background()) + if err != nil { + t.Fatal(err) + } + if requestCount != 1 || snapshot.Cluster.Profile != "k3s" || len(snapshot.Rows) != 1 { + t.Fatalf("unexpected snapshot: %#v", snapshot) + } + if snapshot.Rows[0].Check != "n8n" || snapshot.Rows[0].Summary != "health=Progressing" { + t.Fatalf("unexpected sanitized row: %#v", snapshot.Rows[0]) + } +} + +func TestStatusFailsClosedWithoutCredentials(t *testing.T) { + client := NewJeannieClient("http://127.0.0.1:8787", "") + if _, err := client.Status(context.Background()); err == nil { + t.Fatal("expected missing token to fail") + } +} + +func TestDecodeStatusOutputRejectsNonJSON(t *testing.T) { + if _, err := decodeStatusOutput("status unavailable"); err == nil { + t.Fatal("expected invalid output to fail") + } +} diff --git a/apps/opsproof/overlay/services/services.go b/apps/opsproof/overlay/services/services.go new file mode 100644 index 0000000..e1f0522 --- /dev/null +++ b/apps/opsproof/overlay/services/services.go @@ -0,0 +1,20 @@ +package services + +import ( + "context" + + laravel "go.laravel.com" + "go.laravel.com/config" +) + +type Services struct { + Jeannie *JeannieClient +} + +func New(env *config.Env, app *laravel.App) Services { + return Services{Jeannie: NewJeannieClientFromEnv()} +} + +func From(ctx context.Context) *Services { + return laravel.ServicesOf[*Services](ctx) +} diff --git a/docs/jeannie.1.md b/docs/jeannie.1.md index 63aed9d..a782a23 100644 --- a/docs/jeannie.1.md +++ b/docs/jeannie.1.md @@ -656,6 +656,13 @@ be a full Git SHA. Defaults are `docker.io/postgres:18-alpine` and `55439`. The deployment preserves generated database credentials and data under the OpsProof root. +`LAB_OPSPROOF_JEANNIE_URL`, `LAB_OPSPROOF_JEANNIE_TOKEN` +: Configure OpsProof's server-side Jeannie API connection. The URL defaults to + the loopback Jeannie API. The deployment reads the existing API token from + `/etc/jeannie/temporal.env` when no explicit token is provided; the token is + stored only in OpsProof's private environment file and is never sent to the + browser. + `LAB_RPI_INSTALL_DOCKER=true` : Allow `rpi-services` to install Docker through `get.docker.com` on the Raspberry Pi when Docker is missing. Default is to fail. diff --git a/docs/opsproof-architecture.md b/docs/opsproof-architecture.md index 25ab50e..0c9da56 100644 --- a/docs/opsproof-architecture.md +++ b/docs/opsproof-architecture.md @@ -63,6 +63,8 @@ confirmed by deterministic validation. mode. - Fail closed when Jeannie is unreachable or its advertised command surface differs from the proposal. +- Collect the overview through Jeannie's authenticated, read-only status + command and expose only sanitized status fields to browser props. ## Why not Laravel Rust now? diff --git a/lib/jeannie/pipeline.sh b/lib/jeannie/pipeline.sh index 61b85f6..204239f 100644 --- a/lib/jeannie/pipeline.sh +++ b/lib/jeannie/pipeline.sh @@ -5681,6 +5681,9 @@ deploy_opsproof() { local postgres_container="${LAB_OPSPROOF_POSTGRES_CONTAINER:-opsproof-postgres}" local postgres_db="${LAB_OPSPROOF_POSTGRES_DB:-opsproof}" local postgres_user="${LAB_OPSPROOF_POSTGRES_USER:-opsproof}" + local jeannie_api_url="${LAB_OPSPROOF_JEANNIE_URL:-http://127.0.0.1:${LAB_JEANNIE_API_BACKEND_PORT:-8787}}" + local jeannie_api_token="${LAB_OPSPROOF_JEANNIE_TOKEN:-${JEANNIE_SERVER_TOKEN:-${JEANNIE_REMOTE_TOKEN:-}}}" + local jeannie_api_env="${LAB_OPSPROOF_JEANNIE_ENV_FILE:-/etc/jeannie/temporal.env}" local toolchain_dir="${install_dir}/toolchains/go${go_version}" local release_dir="${install_dir}/releases/${starter_commit}" local database_env="${install_dir}/.database.env" @@ -5727,6 +5730,19 @@ deploy_opsproof() { echo "OpsProof PostgreSQL container, database, or user name is invalid." >&2 return 1 fi + if [[ -z "${jeannie_api_token}" && -r "${jeannie_api_env}" ]]; then + jeannie_api_token="$(sed -n 's/^JEANNIE_SERVER_TOKEN=//p' "${jeannie_api_env}" | head -n 1)" + elif [[ -z "${jeannie_api_token}" ]] && sudo test -r "${jeannie_api_env}"; then + jeannie_api_token="$(sudo sed -n 's/^JEANNIE_SERVER_TOKEN=//p' "${jeannie_api_env}" | head -n 1)" + fi + if ! [[ "${jeannie_api_url}" =~ ^https?://[^[:space:]]+$ ]]; then + echo "LAB_OPSPROOF_JEANNIE_URL must be an HTTP or HTTPS URL." >&2 + return 1 + fi + if [[ -z "${jeannie_api_token}" || "${jeannie_api_token}" == *[[:space:]]* ]]; then + echo "OpsProof requires the Jeannie API token through LAB_OPSPROOF_JEANNIE_TOKEN, JEANNIE_SERVER_TOKEN, or ${jeannie_api_env}." >&2 + return 1 + fi for required in curl docker git npm openssl sha256sum stat systemctl tar; do if ! command -v "${required}" >/dev/null 2>&1; then @@ -5867,6 +5883,8 @@ COMPOSE_EOF "SERVER_HOST=${bind_ip}" \ "SERVER_PORT=${http_port}" \ "DATABASE_URL=${database_url}" \ + "OPSPROOF_JEANNIE_URL=${jeannie_api_url}" \ + "OPSPROOF_JEANNIE_TOKEN=${jeannie_api_token}" \ "SESSION_DRIVER=memory" \ "CACHE_STORE=memory" \ "QUEUE_CONNECTION=sync" \ diff --git a/tests/jeannie/test_privacy_services_pipeline.py b/tests/jeannie/test_privacy_services_pipeline.py index 4906f57..82c8880 100644 --- a/tests/jeannie/test_privacy_services_pipeline.py +++ b/tests/jeannie/test_privacy_services_pipeline.py @@ -68,6 +68,9 @@ class OpsProofPipelineTests(unittest.TestCase): self.assertIn('"CACHE_STORE=memory"', pipeline) self.assertNotIn('"SESSION_DRIVER=file"', pipeline) self.assertNotIn('"CACHE_STORE=file"', pipeline) + self.assertIn('"OPSPROOF_JEANNIE_URL=${jeannie_api_url}"', pipeline) + self.assertIn('"OPSPROOF_JEANNIE_TOKEN=${jeannie_api_token}"', pipeline) + self.assertIn("JEANNIE_SERVER_TOKEN=//p", pipeline) self.assertIn('"${release_dir}/opsproof" migrate --force', pipeline) self.assertIn( 'postgres_uid="$(sudo docker run --rm --entrypoint id "${postgres_image}" -u postgres)"', @@ -101,8 +104,18 @@ class OpsProofPipelineTests(unittest.TestCase): self.assertIn("Command-backed evidence", page) self.assertIn("Operator approval required", page) self.assertIn("Demo mode cannot submit changes", page) + self.assertIn("Live read-only inventory", page) + self.assertIn("Desired: declared intent satisfied", page) + self.assertIn("bearer token retained server-side", page) self.assertIn("./jeannie doctor opi5 --repair-k3s", page) + client = (ROOT / "apps/opsproof/overlay/services/jeannie.go").read_text( + encoding="utf-8" + ) + self.assertIn('"command": "status"', client) + self.assertIn('[]string{"all", "--json"}', client) + self.assertNotIn("Detail string", client) + if __name__ == "__main__": unittest.main()