Add OpsProof read-only status overview
Homelab Main / validate (push) Failing after 1m43s Details
Homelab Main / running-update (push) Has been skipped Details
Homelab Main / debian-ops (push) Has been skipped Details

This commit is contained in:
juvenal.diaz 2026-12-04 15:44:30 -06:00
parent abb8344e47
commit de7024935b
10 changed files with 489 additions and 6 deletions

View File

@ -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.

View File

@ -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,
})
}

View File

@ -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<Record<string, StatusRow[]>>((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 (
<section className="mb-8 overflow-hidden rounded-3xl border border-white/10 bg-[#0a141e]/95 shadow-2xl shadow-black/30">
<div className="flex flex-col gap-4 border-b border-white/10 px-6 py-5 sm:flex-row sm:items-center sm:justify-between">
<div>
<p className="text-xs uppercase tracking-[0.2em] text-slate-500">Live read-only inventory</p>
<h2 className="mt-1 text-xl font-semibold text-white">Homelab operational overview</h2>
<p className="mt-2 text-sm text-slate-500">{overview.message}</p>
</div>
<a href="/" className="w-fit rounded-lg border border-white/10 px-3 py-2 text-xs text-slate-300 hover:border-cyan-300/40 hover:text-cyan-200">
Refresh evidence
</a>
</div>
{!overview.available ? (
<div className="p-6">
<div className="rounded-xl border border-rose-300/20 bg-rose-300/[0.06] p-5">
<p className="font-medium text-rose-200">Jeannie control plane unavailable</p>
<p className="mt-2 text-sm leading-6 text-slate-400">
OpsProof failed closed. No cached state is presented as current and no action can be submitted.
</p>
</div>
</div>
) : (
<>
<div className="grid gap-px border-b border-white/10 bg-white/10 sm:grid-cols-4">
<div className="bg-[#0b1621] p-5">
<p className="text-xs text-slate-500">Healthy checks</p>
<p className="mt-2 text-2xl font-semibold text-emerald-300">{healthy}</p>
</div>
<div className="bg-[#0b1621] p-5">
<p className="text-xs text-slate-500">Needs attention</p>
<p className="mt-2 text-2xl font-semibold text-amber-200">{attention}</p>
</div>
<div className="bg-[#0b1621] p-5">
<p className="text-xs text-slate-500">Cluster profile</p>
<p className="mt-2 font-mono text-sm text-cyan-200">{overview.cluster.profile || 'not selected'}</p>
</div>
<div className="bg-[#0b1621] p-5">
<p className="text-xs text-slate-500">Runtime</p>
<p className="mt-2 font-mono text-sm text-cyan-200">{overview.cluster.runtime || 'unknown'}</p>
</div>
</div>
<div className="grid gap-5 p-6 lg:grid-cols-2">
{Object.entries(grouped).map(([area, rows]) => (
<div key={area} className="rounded-2xl border border-white/8 bg-white/[0.02] p-4">
<div className="mb-3 flex items-center justify-between">
<h3 className="font-medium text-white">{area}</h3>
<span className="font-mono text-[11px] text-slate-600">{rows.length} checks</span>
</div>
<div className="space-y-2">
{rows.map((row) => (
<div key={`${row.area}-${row.check}`} className="rounded-xl border border-white/8 bg-[#071019] p-3">
<div className="flex items-start justify-between gap-3">
<div>
<p className="text-sm font-medium text-slate-200">{row.check}</p>
<p className="mt-1 text-xs text-slate-500">
Desired: declared intent satisfied
</p>
<p className="mt-1 text-xs text-slate-400">
Observed: {row.summary || row.status}
</p>
</div>
<span className={`rounded-md border px-2 py-1 text-[10px] uppercase ${statusTone[row.status]}`}>
{row.status}
</span>
</div>
{(row.status === 'warn' || row.status === 'fail') && (
<code className="mt-3 block overflow-x-auto rounded-md bg-white/[0.03] px-2 py-1.5 text-[11px] text-cyan-200">
{doctorCommand(row)}
</code>
)}
</div>
))}
</div>
</div>
))}
</div>
<p className="border-t border-white/10 px-6 py-3 font-mono text-[10px] text-slate-600">
COLLECTED {overview.collectedAt || 'unknown'} · MODE {overview.mode || 'fast'} · bearer token retained server-side
</p>
</>
)}
</section>
);
}
export default function Welcome({ laravelVersion, overview }: Props) {
return (
<main className="min-h-screen bg-[#071019] text-slate-100 selection:bg-cyan-300 selection:text-slate-950">
<div className="pointer-events-none fixed inset-0 bg-[radial-gradient(circle_at_15%_10%,rgba(34,211,238,0.10),transparent_25%),radial-gradient(circle_at_85%_20%,rgba(99,102,241,0.12),transparent_28%)]" />
@ -39,11 +181,11 @@ export default function Welcome({ laravelVersion }: Props) {
</div>
</div>
<div className="flex items-center gap-3 text-xs">
<span className="hidden rounded-full border border-amber-300/30 bg-amber-300/10 px-3 py-1.5 text-amber-200 sm:inline">
Sanitized demo
<span className="hidden rounded-full border border-cyan-300/30 bg-cyan-300/10 px-3 py-1.5 text-cyan-200 sm:inline">
Read-only live view
</span>
<span className="rounded-full border border-emerald-300/30 bg-emerald-300/10 px-3 py-1.5 text-emerald-200">
Control plane available
<span className={`rounded-full border px-3 py-1.5 ${overview.available ? 'border-emerald-300/30 bg-emerald-300/10 text-emerald-200' : 'border-rose-300/30 bg-rose-300/10 text-rose-200'}`}>
Control plane {overview.available ? 'available' : 'unavailable'}
</span>
</div>
</header>
@ -73,10 +215,12 @@ export default function Welcome({ laravelVersion }: Props) {
</div>
</section>
<LiveOverview overview={overview} />
<section className="overflow-hidden rounded-3xl border border-white/10 bg-[#0a141e]/95 shadow-2xl shadow-black/30">
<div className="flex flex-col gap-4 border-b border-white/10 px-6 py-5 sm:flex-row sm:items-center sm:justify-between">
<div>
<p className="text-xs uppercase tracking-[0.2em] text-slate-500">Active incident · OP-0001</p>
<p className="text-xs uppercase tracking-[0.2em] text-slate-500">Sanitized incident scenario · OP-0001</p>
<h2 className="mt-1 text-xl font-semibold text-white">Orange Pi K3s storage became read-only</h2>
</div>
<div className="flex items-center gap-2">

View File

@ -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, &current); 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
}

View File

@ -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")
}
}

View File

@ -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)
}

View File

@ -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.

View File

@ -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?

View File

@ -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" \

View File

@ -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()