diff --git a/backend/handlers/handle_admin.go b/backend/handlers/handle_admin.go new file mode 100644 index 0000000..a9ba8ac --- /dev/null +++ b/backend/handlers/handle_admin.go @@ -0,0 +1,178 @@ +package handlers + +import ( + "net/http" + "os" + "strings" + + "github.com/gin-gonic/gin" +) + +// This file backs the admin diagnostics panel: a configuration report and a +// log tail. Both are admin-only REST endpoints rather than GraphQL because +// they read the process environment and the filesystem — things outside the +// data model the GraphQL schema describes. + +// ConfigVar describes one piece of configuration the backend can report on. +// Required marks vars whose absence visibly breaks a feature; Optional vars +// have a working default. +type ConfigVar struct { + Name string `json:"name"` + Purpose string `json:"purpose"` + Required bool `json:"required"` +} + +// configVars is the checklist the panel renders. Sensitive values are never +// returned — only whether each var is present — so the endpoint cannot leak +// credentials even to an admin client. +var configVars = []ConfigVar{ + {"POSTGRES_HOST", "Database connectivity", true}, + {"POSTGRES_USER", "Database connectivity", true}, + {"POSTGRES_PASSWORD", "Database connectivity", true}, + {"POSTGRES_DB", "Database connectivity", true}, + {"DOMAIN", "Site origin, JWT cookie domain", true}, + {"AUTH_SECRET", "JWT signing", true}, + {"SPOTIFY_CLIENT_ID", "Spotify listening widget", true}, + {"SPOTIFY_CLIENT_SECRET", "Spotify listening widget", true}, + {"SPOTIFY_REDIRECT_URI", "Spotify listening widget", true}, + {"STEAM_API_KEY", "Steam status widget", false}, + {"STEAM_ID", "Steam status widget", false}, + {"CLAUDE_API_KEY", "Email summarisation", false}, + {"EMAIL_BACKEND", "Email sync (graph/imap)", false}, + {"MSGRAPH_CLIENT_ID", "Email sync (Microsoft Graph)", false}, + {"MSGRAPH_CLIENT_SECRET", "Email sync (Microsoft Graph)", false}, + {"MSGRAPH_REDIRECT_URI", "Email sync (Microsoft Graph)", false}, + {"MSGRAPH_TENANT_ID", "Email sync (Microsoft Graph)", false}, + {"IMAP_HOST", "Email sync (IMAP fallback)", false}, + {"IMAP_EMAIL", "Email sync (IMAP fallback)", false}, + {"IMAP_PASSWORD", "Email sync (IMAP fallback)", false}, + {"GITEA_HOST", "Gitea activity feed", false}, + {"GITEA_PORT", "Gitea activity feed", false}, + {"JWT_COOKIE_SECURE", "Cookie security in dev", false}, + {"ICECAST_URL", "Radio queue widget", false}, +} + +// ConfigCheck backs GET /admin/config. It reports one entry per known var: +// set or empty, plus the value only for vars flagged non-sensitive (none of +// the credentials are). A var not in the list at all is not reported — the +// point is a checklist, not a full env dump. +func (store *Store) ConfigCheck(ctx *gin.Context) { + type entry struct { + ConfigVar + Set bool `json:"set"` + Value string `json:"value,omitempty"` + Secret bool `json:"secret"` + } + + // Vars whose *value* may come back (bad values like "consumers" are fine; + // they contain no credential). + visible := map[string]bool{ + "EMAIL_BACKEND": true, + "MSGRAPH_TENANT_ID": true, + "ICECAST_URL": true, + "STEAM_ID": true, + } + + // Explicitly-credentialled vars get the secret badge so the panel can + // label them "present" instead of showing a masked string. + secrets := map[string]bool{ + "POSTGRES_PASSWORD": true, + "AUTH_SECRET": true, + "SPOTIFY_CLIENT_SECRET": true, + "MSGRAPH_CLIENT_SECRET": true, + "CLAUDE_API_KEY": true, + "STEAM_API_KEY": true, + "IMAP_PASSWORD": true, + } + + result := make([]entry, 0, len(configVars)) + for _, v := range configVars { + val := os.Getenv(v.Name) + e := entry{ConfigVar: v, Set: strings.TrimSpace(val) != "", Secret: secrets[v.Name]} + if e.Set && visible[v.Name] { + e.Value = val + } + result = append(result, e) + } + + ctx.JSON(http.StatusOK, gin.H{"vars": result}) +} + +// logTailBytes and logTailLines bound how much of the log file one request +// moves: 256 KiB is beyond any useful screen at log-ish line lengths, and is +// cheap even on the Pi. +const ( + logTailBytes = 256 << 10 + logTailLines = 500 +) + +// Logs backs GET /admin/logs. It returns the tail of the backend's own log +// file (go.log — Gin traffic plus application log lines), which lives on the +// bind-mounted ./logs volume. +// +// Why tail and not offer a range: the panel wants "what happened recently", +// and the file can grow unboundedly between rotations, so anything else +// invites reading the whole thing into memory. +func (store *Store) Logs(ctx *gin.Context) { + lines, size, err := tailLogFile(logPath) + if err != nil { + // The mount being absent is a deployment problem worth surfacing + // distinctly from "log file empty". + ctx.JSON(http.StatusInternalServerError, gin.H{"error": "log unavailable: " + err.Error()}) + return + } + + ctx.JSON(http.StatusOK, gin.H{"lines": lines, "total_bytes": size}) +} + +// logPath matches the file main.go opens for gin.DefaultWriter. +const logPath = "/backend/logs/go.log" + +// tailLogFile returns the last logTailLines lines of a file, reading at most +// logTailBytes from the end. Split out from the handler so the offset and +// partial-line rules are testable without a filesystem mount. +func tailLogFile(path string) ([]string, int64, error) { + f, err := os.Open(path) + if err != nil { + return nil, 0, err + } + defer f.Close() + + info, err := f.Stat() + if err != nil { + return nil, 0, err + } + + // Read from near the end rather than head-to-toe so the read stays + // constant-size regardless of how old the file is. + start := int64(0) + if info.Size() > logTailBytes { + start = info.Size() - logTailBytes + } + buf := make([]byte, info.Size()-start) + if len(buf) > 0 { + if _, err := f.ReadAt(buf, start); err != nil { + return nil, 0, err + } + } + + // Starting mid-file almost certainly lands mid-line; drop that fragment + // so the panel never renders a truncated first entry. + text := string(buf) + if start > 0 { + if i := strings.IndexByte(text, '\n'); i >= 0 { + text = text[i+1:] + } + } + + text = strings.TrimRight(text, "\n") + if text == "" { + return []string{}, info.Size(), nil + } + + lines := strings.Split(text, "\n") + if len(lines) > logTailLines { + lines = lines[len(lines)-logTailLines:] + } + return lines, info.Size(), nil +} diff --git a/backend/handlers/handle_admin_test.go b/backend/handlers/handle_admin_test.go new file mode 100644 index 0000000..6f26ba2 --- /dev/null +++ b/backend/handlers/handle_admin_test.go @@ -0,0 +1,76 @@ +package handlers + +import ( + "os" + "path/filepath" + "strings" + "testing" +) + +// tailLogFile's rules that are easy to get wrong: the line cap, and dropping +// the partial first line when the read started mid-file. + +func writeLog(t *testing.T, content string) string { + t.Helper() + path := filepath.Join(t.TempDir(), "go.log") + if err := os.WriteFile(path, []byte(content), 0o644); err != nil { + t.Fatalf("writing fixture: %v", err) + } + return path +} + +func TestTailLogFileCapsLines(t *testing.T) { + var b strings.Builder + for range logTailLines + 50 { + b.WriteString("line\n") + } + lines, _, err := tailLogFile(writeLog(t, b.String())) + if err != nil { + t.Fatalf("tailLogFile: %v", err) + } + if len(lines) != logTailLines { + t.Fatalf("got %d lines, want the cap of %d", len(lines), logTailLines) + } +} + +func TestTailLogFileDropsPartialFirstLine(t *testing.T) { + // A file larger than the byte window: the read starts mid-file, so the + // first line it sees is a fragment and must be discarded. + filler := strings.Repeat("x", 100) + "\n" + var b strings.Builder + for b.Len() < logTailBytes+len(filler) { + b.WriteString(filler) + } + b.WriteString("FINAL\n") + + lines, _, err := tailLogFile(writeLog(t, b.String())) + if err != nil { + t.Fatalf("tailLogFile: %v", err) + } + if len(lines) == 0 { + t.Fatal("expected some lines") + } + if lines[len(lines)-1] != "FINAL" { + t.Fatalf("last line = %q, want FINAL", lines[len(lines)-1]) + } + // Every surviving line must be whole, i.e. a full filler line. + if got := lines[0]; got != strings.TrimSuffix(filler, "\n") { + t.Fatalf("first line = %q, want a complete filler line", got) + } +} + +func TestTailLogFileEmpty(t *testing.T) { + lines, size, err := tailLogFile(writeLog(t, "")) + if err != nil { + t.Fatalf("tailLogFile: %v", err) + } + if len(lines) != 0 || size != 0 { + t.Fatalf("got %d lines / %d bytes, want 0 / 0", len(lines), size) + } +} + +func TestTailLogFileMissing(t *testing.T) { + if _, _, err := tailLogFile(filepath.Join(t.TempDir(), "absent.log")); err == nil { + t.Fatal("expected an error for a missing log file") + } +} diff --git a/backend/main.go b/backend/main.go index 0e2735c..50afe6d 100644 --- a/backend/main.go +++ b/backend/main.go @@ -189,6 +189,10 @@ func main() { // NOTES admin.GET("/notes/*path", store.GetNoteFile) + // ADMIN DIAGNOSTICS: env-var checklist and log tail for the admin panel. + admin.GET("/admin/config", store.ConfigCheck) + admin.GET("/admin/logs", store.Logs) + // GRAPHQL // GraphQL is assembled by hand rather than with handler.NewDefaultServer // so the transports and extensions below are explicit. diff --git a/vue/src/views/admin/Admin.vue b/vue/src/views/admin/Admin.vue index 240cdd4..c8b3ad8 100644 --- a/vue/src/views/admin/Admin.vue +++ b/vue/src/views/admin/Admin.vue @@ -18,6 +18,7 @@ import CreateBookmark from "./CreateBookmark.vue"; import CreatePlace from "./CreatePlace.vue"; import ManageUsers from "./ManageUsers.vue"; import ManageRadio from "./ManageRadio.vue"; +import Diagnostics from "./Diagnostics.vue"; const auth = useAuthStore(); @@ -31,6 +32,7 @@ const sections = [ { id: "place", label: "Place / Thing To Do", component: CreatePlace }, { id: "users", label: "Manage Users", component: ManageUsers }, { id: "radio", label: "Manage Radio", component: ManageRadio }, + { id: "diagnostics", label: "Diagnostics", component: Diagnostics }, ]; const active = ref("place"); diff --git a/vue/src/views/admin/Diagnostics.vue b/vue/src/views/admin/Diagnostics.vue new file mode 100644 index 0000000..e0d3c8b --- /dev/null +++ b/vue/src/views/admin/Diagnostics.vue @@ -0,0 +1,154 @@ + + + + +