Remove the admin panel's Environment tab and env-apply
Test and deploy / test (push) Successful in 2m2s
Test and deploy / deploy (push) Successful in 1m35s

.env is edited by hand again. Drops the /admin/env endpoints, EnvManager
and its registry, the host-side apply.py watcher and its install script,
the backend's env-apply bind mount, and the Environment tab.

The deploy and maintenance workflows still serialise docker compose, now
on .compose.lock in the checkout instead of env-apply/run/lock.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
2026-10-15 15:29:55 +01:00
co-authored by Claude Opus 5.5
parent c9d599a371
commit 604ac32028
27 changed files with 54 additions and 2270 deletions
+1 -2
View File
@@ -10,8 +10,7 @@ import (
// 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).
// the data model the GraphQL schema describes.
// 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
-133
View File
@@ -1,133 +0,0 @@
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())
}
-148
View File
@@ -1,148 +0,0 @@
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")
}
})
}
-4
View File
@@ -38,10 +38,6 @@ type Store struct {
// services.CallPython: reading a rowing display photo (handle_rowing.go).
PythonURL string
// 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".