Manage .env from the admin panel
Add an Environment tab to /admin that lists every variable in .env.example and lets keys, OAuth settings, email settings and generated secrets be changed without SSH. Secrets are write-only; infrastructure variables are shown read-only. The backend never writes .env or touches Docker. It validates an edit and queues it in env-apply/run/request.json; env-apply/apply.py, run on the host by a systemd path unit (env-apply/install.sh), rewrites .env atomically, keeps .env.bak, and recreates only the services that read the change. backend/services/env_registry.json is the single list of variables, shared by the backend and the host script; a test keeps it in step with .env.example. It replaces the drifted checklist in handle_admin.go. The job capture token card moves to the new tab. Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
@@ -8,95 +8,10 @@ import (
|
||||
"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})
|
||||
}
|
||||
// This file backs the admin diagnostics panel's log tail. It is an admin-only
|
||||
// REST endpoint rather than GraphQL because it reads the filesystem — outside
|
||||
// the data model the GraphQL schema describes. The configuration report that
|
||||
// used to live here is now the Environment tab (handle_env.go).
|
||||
|
||||
// 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
|
||||
|
||||
@@ -0,0 +1,133 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
"adam-french.co.uk/backend/services"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// This file backs the admin panel's Environment tab: a report on every
|
||||
// variable in .env, and a way to change the ones that are safe to change.
|
||||
//
|
||||
// The handlers never read or write .env. State is this process's own
|
||||
// environment, and a change is a request left for the host to apply (see
|
||||
// services.EnvManager). REST rather than GraphQL for the same reason as the
|
||||
// rest of the admin endpoints: this is process and host state, not the data
|
||||
// model the schema describes.
|
||||
|
||||
// envSecretHintMinLen is the shortest secret that gets its last four
|
||||
// characters shown. Below it, four characters is too much of the value.
|
||||
const envSecretHintMinLen = 12
|
||||
|
||||
type envVarView struct {
|
||||
services.EnvVar
|
||||
Secret bool `json:"secret"`
|
||||
Set bool `json:"set"`
|
||||
// Value is sent only for non-secret variables; Hint (the last four
|
||||
// characters) is all a secret ever reveals.
|
||||
Value string `json:"value,omitempty"`
|
||||
Hint string `json:"hint,omitempty"`
|
||||
}
|
||||
|
||||
type envGroupView struct {
|
||||
Name string `json:"name"`
|
||||
Vars []envVarView `json:"vars"`
|
||||
}
|
||||
|
||||
// GetEnv backs GET /admin/env: every registry variable grouped for display,
|
||||
// plus the state of the latest change.
|
||||
//
|
||||
// Values are what this process was started with, not what .env holds now —
|
||||
// the two differ between a save and the recreate that follows it, which is
|
||||
// what the status's pending list is for.
|
||||
func (store *Store) GetEnv(ctx *gin.Context) {
|
||||
var groups []envGroupView
|
||||
index := map[string]int{}
|
||||
for _, v := range store.Env.Vars() {
|
||||
value := os.Getenv(v.Name)
|
||||
view := envVarView{EnvVar: v, Secret: v.Secret(), Set: strings.TrimSpace(value) != ""}
|
||||
switch {
|
||||
case !view.Set:
|
||||
case !view.Secret:
|
||||
view.Value = value
|
||||
case len(value) >= envSecretHintMinLen:
|
||||
view.Hint = value[len(value)-4:]
|
||||
}
|
||||
|
||||
i, seen := index[v.Group]
|
||||
if !seen {
|
||||
i = len(groups)
|
||||
index[v.Group] = i
|
||||
groups = append(groups, envGroupView{Name: v.Group})
|
||||
}
|
||||
groups[i].Vars = append(groups[i].Vars, view)
|
||||
}
|
||||
ctx.JSON(http.StatusOK, gin.H{"groups": groups, "status": store.Env.Status()})
|
||||
}
|
||||
|
||||
type updateEnvRequest struct {
|
||||
// Set maps a variable to its new value; "" clears it.
|
||||
Set map[string]string `json:"set"`
|
||||
// Generate names "generated" variables to mint a random value for.
|
||||
Generate []string `json:"generate"`
|
||||
}
|
||||
|
||||
// UpdateEnv backs PUT /admin/env. It queues the change for the host and
|
||||
// returns straight away; the panel follows progress on GET /admin/env/status,
|
||||
// through the backend's own restart.
|
||||
//
|
||||
// The response is the only time a generated value is sent anywhere.
|
||||
func (store *Store) UpdateEnv(ctx *gin.Context) {
|
||||
var body updateEnvRequest
|
||||
if err := ctx.ShouldBindJSON(&body); err != nil {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "invalid request body"})
|
||||
return
|
||||
}
|
||||
|
||||
generated, recreates, err := store.Env.Submit(body.Set, body.Generate)
|
||||
if errors.Is(err, services.ErrEnvApplying) {
|
||||
ctx.JSON(http.StatusConflict, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
// Validation messages name the variable, never the value.
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
names := make([]string, 0, len(body.Set)+len(body.Generate))
|
||||
for name := range body.Set {
|
||||
names = append(names, name)
|
||||
}
|
||||
names = append(names, body.Generate...)
|
||||
log.Printf("[Env] change queued for %s", strings.Join(names, ", "))
|
||||
|
||||
ctx.Header("Cache-Control", "no-store")
|
||||
ctx.JSON(http.StatusAccepted, gin.H{
|
||||
"generated": generated,
|
||||
"services": recreates,
|
||||
"status": store.Env.Status(),
|
||||
})
|
||||
}
|
||||
|
||||
// GetEnvStatus backs GET /admin/env/status.
|
||||
func (store *Store) GetEnvStatus(ctx *gin.Context) {
|
||||
ctx.JSON(http.StatusOK, store.Env.Status())
|
||||
}
|
||||
|
||||
// CancelEnv backs DELETE /admin/env/pending: withdraw a request nothing on
|
||||
// the host has picked up, so new secrets do not sit in the shared directory
|
||||
// waiting for a watcher that is not there.
|
||||
func (store *Store) CancelEnv(ctx *gin.Context) {
|
||||
if err := store.Env.Cancel(); err != nil {
|
||||
log.Println("Cancelling env request failed:", err)
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to cancel the request"})
|
||||
return
|
||||
}
|
||||
ctx.JSON(http.StatusOK, store.Env.Status())
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"adam-french.co.uk/backend/services"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func envRouter(t *testing.T) (*gin.Engine, string) {
|
||||
t.Helper()
|
||||
gin.SetMode(gin.TestMode)
|
||||
dir := t.TempDir()
|
||||
env, err := services.NewEnvManager(dir)
|
||||
if err != nil {
|
||||
t.Fatalf("NewEnvManager: %v", err)
|
||||
}
|
||||
store := &Store{Env: env}
|
||||
r := gin.New()
|
||||
r.GET("/admin/env", store.GetEnv)
|
||||
r.PUT("/admin/env", store.UpdateEnv)
|
||||
r.GET("/admin/env/status", store.GetEnvStatus)
|
||||
r.DELETE("/admin/env/pending", store.CancelEnv)
|
||||
return r, dir
|
||||
}
|
||||
|
||||
func envDo(r *gin.Engine, method, path, body string) *httptest.ResponseRecorder {
|
||||
req := httptest.NewRequest(method, path, strings.NewReader(body))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
rec := httptest.NewRecorder()
|
||||
r.ServeHTTP(rec, req)
|
||||
return rec
|
||||
}
|
||||
|
||||
// The property the whole tab rests on: a secret's value never leaves the
|
||||
// server, while a non-secret's does so it can be edited in place.
|
||||
func TestGetEnvNeverReturnsSecrets(t *testing.T) {
|
||||
r, _ := envRouter(t)
|
||||
t.Setenv("CLAUDE_API_KEY", "sk-ant-very-secret-value-9f3a")
|
||||
t.Setenv("POSTGRES_PASSWORD", "hunter2")
|
||||
t.Setenv("STEAM_ID", "76561198000000000")
|
||||
t.Setenv("TFL_APP_KEY", "")
|
||||
|
||||
rec := envDo(r, http.MethodGet, "/admin/env", "")
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, want 200", rec.Code)
|
||||
}
|
||||
body := rec.Body.String()
|
||||
for _, secret := range []string{"sk-ant-very-secret-value-9f3a", "hunter2"} {
|
||||
if strings.Contains(body, secret) {
|
||||
t.Fatalf("response contains the secret %q", secret)
|
||||
}
|
||||
}
|
||||
|
||||
var parsed struct {
|
||||
Groups []struct {
|
||||
Vars []envVarView `json:"vars"`
|
||||
} `json:"groups"`
|
||||
}
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &parsed); err != nil {
|
||||
t.Fatalf("parsing response: %v", err)
|
||||
}
|
||||
byName := map[string]envVarView{}
|
||||
for _, g := range parsed.Groups {
|
||||
for _, v := range g.Vars {
|
||||
byName[v.Name] = v
|
||||
}
|
||||
}
|
||||
|
||||
if v := byName["CLAUDE_API_KEY"]; !v.Set || !v.Secret || v.Value != "" || v.Hint != "9f3a" {
|
||||
t.Errorf("CLAUDE_API_KEY = %+v, want set, secret, no value, hint 9f3a", v)
|
||||
}
|
||||
// Too short for four characters to be a safe hint.
|
||||
if v := byName["POSTGRES_PASSWORD"]; !v.Set || v.Hint != "" || v.Editable {
|
||||
t.Errorf("POSTGRES_PASSWORD = %+v, want set, no hint, locked", v)
|
||||
}
|
||||
if v := byName["STEAM_ID"]; v.Value != "76561198000000000" || v.Secret {
|
||||
t.Errorf("STEAM_ID = %+v, want its value shown", v)
|
||||
}
|
||||
if v := byName["TFL_APP_KEY"]; v.Set {
|
||||
t.Errorf("TFL_APP_KEY = %+v, want unset", v)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUpdateEnv(t *testing.T) {
|
||||
r, dir := envRouter(t)
|
||||
requestPath := filepath.Join(dir, "request.json")
|
||||
|
||||
t.Run("a locked variable is refused and nothing is queued", func(t *testing.T) {
|
||||
rec := envDo(r, http.MethodPut, "/admin/env", `{"set":{"POSTGRES_PASSWORD":"x"}}`)
|
||||
if rec.Code != http.StatusBadRequest {
|
||||
t.Fatalf("status = %d, want 400", rec.Code)
|
||||
}
|
||||
if _, err := os.Stat(requestPath); err == nil {
|
||||
t.Fatal("a refused change left a request behind")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("a malformed body is refused", func(t *testing.T) {
|
||||
if rec := envDo(r, http.MethodPut, "/admin/env", `{"set":`); rec.Code != http.StatusBadRequest {
|
||||
t.Fatalf("status = %d, want 400", rec.Code)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("a valid change is queued and a generated value returned once", func(t *testing.T) {
|
||||
rec := envDo(r, http.MethodPut, "/admin/env", `{"set":{"STEAM_ID":"42"},"generate":["BACKEND_SECRET"]}`)
|
||||
if rec.Code != http.StatusAccepted {
|
||||
t.Fatalf("status = %d, want 202: %s", rec.Code, rec.Body)
|
||||
}
|
||||
var parsed struct {
|
||||
Generated map[string]string `json:"generated"`
|
||||
Status services.EnvApplyStatus `json:"status"`
|
||||
}
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &parsed); err != nil {
|
||||
t.Fatalf("parsing response: %v", err)
|
||||
}
|
||||
secret := parsed.Generated["BACKEND_SECRET"]
|
||||
if len(secret) != 64 {
|
||||
t.Fatalf("generated BACKEND_SECRET = %q, want 64 hex characters", secret)
|
||||
}
|
||||
if parsed.Status.State != "pending" {
|
||||
t.Fatalf("status = %+v, want pending", parsed.Status)
|
||||
}
|
||||
|
||||
// Reading the state back must not repeat it.
|
||||
for _, path := range []string{"/admin/env", "/admin/env/status"} {
|
||||
if strings.Contains(envDo(r, http.MethodGet, path, "").Body.String(), secret) {
|
||||
t.Fatalf("GET %s repeats the generated secret", path)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("a pending change can be withdrawn", func(t *testing.T) {
|
||||
rec := envDo(r, http.MethodDelete, "/admin/env/pending", "")
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, want 200", rec.Code)
|
||||
}
|
||||
if _, err := os.Stat(requestPath); err == nil {
|
||||
t.Fatal("the request file survived the cancel")
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -44,6 +44,10 @@ type Store struct {
|
||||
// routes are switched off, not open.
|
||||
CaptureToken *services.CaptureToken
|
||||
|
||||
// Registry of .env variables and the request/status hand-off with the
|
||||
// host that applies changes to them (handle_env.go).
|
||||
Env *services.EnvManager
|
||||
|
||||
// Cached "recently played" tracks, refreshed at most once a minute by the
|
||||
// GraphQL spotifyRecent resolver. A pointer to a slice so that nil can
|
||||
// mean "never fetched" distinctly from "fetched, empty".
|
||||
|
||||
Reference in New Issue
Block a user