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:
@@ -0,0 +1,377 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
_ "embed"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io/fs"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"syscall"
|
||||
"time"
|
||||
)
|
||||
|
||||
// ENV_APPLY_DIR is the directory shared with the host (./env-apply/run in the
|
||||
// checkout, bind-mounted by docker-compose). It is the whole interface
|
||||
// between this process and the host script that edits .env.
|
||||
const ENV_APPLY_DIR = "/backend/env-apply"
|
||||
|
||||
// The registry is JSON rather than a Go literal because the host script
|
||||
// (env-apply/apply.py) reads the same file from the checkout: one list
|
||||
// decides both what the panel offers and what the host will accept.
|
||||
//
|
||||
//go:embed env_registry.json
|
||||
var envRegistryJSON []byte
|
||||
|
||||
// EnvVar is one registry entry.
|
||||
//
|
||||
// Kind decides how a value is validated and how the panel renders it:
|
||||
// "secret" and "generated" are never sent to the browser; "generated" can
|
||||
// also be minted here. Services lists the compose services that read the
|
||||
// variable, which is what the host recreates after a change.
|
||||
type EnvVar struct {
|
||||
Name string `json:"name"`
|
||||
Group string `json:"group"`
|
||||
Purpose string `json:"purpose"`
|
||||
Kind string `json:"kind"`
|
||||
Editable bool `json:"editable"`
|
||||
LockedReason string `json:"lockedReason,omitempty"`
|
||||
Services []string `json:"services,omitempty"`
|
||||
DocsURL string `json:"docsUrl,omitempty"`
|
||||
Options []string `json:"options,omitempty"`
|
||||
Warning string `json:"warning,omitempty"`
|
||||
}
|
||||
|
||||
// Secret reports whether the variable's value must stay on the server.
|
||||
func (v EnvVar) Secret() bool {
|
||||
return v.Kind == "secret" || v.Kind == "generated"
|
||||
}
|
||||
|
||||
// EnvManager turns an edit made in the admin panel into a request for the
|
||||
// host to apply.
|
||||
//
|
||||
// The backend deliberately cannot write .env or restart containers itself:
|
||||
// it is the internet-facing process, and either ability would make a
|
||||
// compromised admin session a compromised host. Instead it validates the
|
||||
// change and leaves request.json in the shared directory; the host's watcher
|
||||
// (env-apply/apply.py, run by a systemd path unit) merges it into .env,
|
||||
// recreates the affected containers and reports back through status.json.
|
||||
type EnvManager struct {
|
||||
dir string
|
||||
vars []EnvVar
|
||||
byName map[string]EnvVar
|
||||
|
||||
// Serialises Submit and Cancel so two requests cannot interleave their
|
||||
// read-merge-write of request.json. The host is a separate process and is
|
||||
// handled by renames instead (see Submit).
|
||||
mu sync.Mutex
|
||||
}
|
||||
|
||||
// envApplyRequest is request.json. Clearing a variable is setting it to "".
|
||||
type envApplyRequest struct {
|
||||
ID string `json:"id"`
|
||||
RequestedAt time.Time `json:"requestedAt"`
|
||||
Set map[string]string `json:"set"`
|
||||
}
|
||||
|
||||
// EnvApplyStatus is what the panel polls. State is one of idle, pending
|
||||
// (request written, host has not picked it up), applying, applied, failed.
|
||||
type EnvApplyStatus struct {
|
||||
State string `json:"state"`
|
||||
ID string `json:"id,omitempty"`
|
||||
// When the state was entered.
|
||||
At *time.Time `json:"at,omitempty"`
|
||||
// Names in a pending request. Values are never reported.
|
||||
Pending []string `json:"pending,omitempty"`
|
||||
Services []string `json:"services,omitempty"`
|
||||
Changed []string `json:"changed,omitempty"`
|
||||
Output string `json:"output,omitempty"`
|
||||
// False once a request has waited long enough that nothing on the host
|
||||
// can be watching for it (a dev machine, or the units not installed).
|
||||
Watcher bool `json:"watcher"`
|
||||
}
|
||||
|
||||
const (
|
||||
envRequestFile = "request.json"
|
||||
envStatusFile = "status.json"
|
||||
|
||||
// The path unit fires within a second, so a request still unclaimed
|
||||
// after this long means there is no watcher.
|
||||
envWatcherGrace = 15 * time.Second
|
||||
// An "applying" status older than this is a host script that died
|
||||
// mid-run; stop letting it block new requests.
|
||||
envApplyingStale = 5 * time.Minute
|
||||
|
||||
envValueMaxLen = 4096
|
||||
)
|
||||
|
||||
// ErrEnvApplying is returned by Submit while the host is mid-apply.
|
||||
var ErrEnvApplying = errors.New("a change is being applied; try again in a moment")
|
||||
|
||||
// NewEnvManager parses the embedded registry. dir need not exist yet: without
|
||||
// the bind mount, reads report "idle" and Submit fails with a clear error.
|
||||
func NewEnvManager(dir string) (*EnvManager, error) {
|
||||
var vars []EnvVar
|
||||
if err := json.Unmarshal(envRegistryJSON, &vars); err != nil {
|
||||
return nil, fmt.Errorf("parsing env registry: %w", err)
|
||||
}
|
||||
byName := make(map[string]EnvVar, len(vars))
|
||||
for _, v := range vars {
|
||||
if _, dup := byName[v.Name]; dup {
|
||||
return nil, fmt.Errorf("env registry lists %s twice", v.Name)
|
||||
}
|
||||
byName[v.Name] = v
|
||||
}
|
||||
return &EnvManager{dir: dir, vars: vars, byName: byName}, nil
|
||||
}
|
||||
|
||||
// Vars returns the registry in file order, which is the order the panel
|
||||
// shows.
|
||||
func (m *EnvManager) Vars() []EnvVar {
|
||||
return m.vars
|
||||
}
|
||||
|
||||
// Validate checks one proposed value. The empty string clears the variable
|
||||
// and is always acceptable for an editable one.
|
||||
//
|
||||
// The control-character rule is the security-relevant one: .env is line
|
||||
// oriented, so a newline in a value would let an edit to an allowed variable
|
||||
// write a second, arbitrary one.
|
||||
func (m *EnvManager) Validate(name, value string) error {
|
||||
v, ok := m.byName[name]
|
||||
if !ok {
|
||||
return fmt.Errorf("%s is not a known variable", name)
|
||||
}
|
||||
if !v.Editable {
|
||||
return fmt.Errorf("%s cannot be changed from the panel", name)
|
||||
}
|
||||
if value == "" {
|
||||
return nil
|
||||
}
|
||||
if len(value) > envValueMaxLen {
|
||||
return fmt.Errorf("%s is too long", name)
|
||||
}
|
||||
for _, r := range value {
|
||||
if r < 0x20 || r == 0x7f {
|
||||
return fmt.Errorf("%s contains a control character", name)
|
||||
}
|
||||
}
|
||||
// The host writes values single-quoted, and a dotenv single-quoted
|
||||
// string has no escape for the quote itself.
|
||||
if strings.ContainsRune(value, '\'') {
|
||||
return fmt.Errorf("%s cannot contain a single quote", name)
|
||||
}
|
||||
|
||||
switch v.Kind {
|
||||
case "url":
|
||||
u, err := url.Parse(value)
|
||||
if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" {
|
||||
return fmt.Errorf("%s must be an http(s) URL", name)
|
||||
}
|
||||
case "bool":
|
||||
if value != "true" && value != "false" {
|
||||
return fmt.Errorf("%s must be true or false", name)
|
||||
}
|
||||
case "duration":
|
||||
if d, err := time.ParseDuration(value); err != nil || d <= 0 {
|
||||
return fmt.Errorf("%s must be a duration such as 30m", name)
|
||||
}
|
||||
case "number":
|
||||
if n, err := strconv.Atoi(value); err != nil || n <= 0 {
|
||||
return fmt.Errorf("%s must be a positive whole number", name)
|
||||
}
|
||||
case "enum":
|
||||
if !slices.Contains(v.Options, value) {
|
||||
return fmt.Errorf("%s must be one of: %s", name, strings.Join(v.Options, ", "))
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ServicesFor is the set of compose services a change to names recreates.
|
||||
// The backend is always among them: the panel reports state from this
|
||||
// process's own environment, which only a recreate refreshes.
|
||||
func (m *EnvManager) ServicesFor(names []string) []string {
|
||||
services := []string{"backend"}
|
||||
for _, name := range names {
|
||||
for _, s := range m.byName[name].Services {
|
||||
if !slices.Contains(services, s) {
|
||||
services = append(services, s)
|
||||
}
|
||||
}
|
||||
}
|
||||
slices.Sort(services)
|
||||
return services
|
||||
}
|
||||
|
||||
// Submit validates a batch of edits and hands it to the host. set holds
|
||||
// explicit values ("" clears); generate names variables to mint a random
|
||||
// value for. The generated values are returned and exist nowhere else on
|
||||
// this side — the caller shows them once.
|
||||
//
|
||||
// Nothing is written unless the whole batch is valid.
|
||||
//
|
||||
// A request the host has not yet claimed is merged into rather than
|
||||
// refused, so edits are not stuck behind an absent watcher. The host claims
|
||||
// a request by renaming it, so the worst a race can do is hand it values it
|
||||
// has already applied.
|
||||
func (m *EnvManager) Submit(set map[string]string, generate []string) (map[string]string, []string, error) {
|
||||
changes := make(map[string]string, len(set)+len(generate))
|
||||
for name, value := range set {
|
||||
value = strings.TrimSpace(value)
|
||||
if err := m.Validate(name, value); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
changes[name] = value
|
||||
}
|
||||
generated := make(map[string]string, len(generate))
|
||||
for _, name := range generate {
|
||||
if v, ok := m.byName[name]; !ok || !v.Editable || v.Kind != "generated" {
|
||||
return nil, nil, fmt.Errorf("%s cannot be generated", name)
|
||||
}
|
||||
raw := make([]byte, 32)
|
||||
if _, err := rand.Read(raw); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
generated[name] = hex.EncodeToString(raw)
|
||||
changes[name] = generated[name]
|
||||
}
|
||||
if len(changes) == 0 {
|
||||
return nil, nil, errors.New("no changes given")
|
||||
}
|
||||
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
|
||||
if status := m.readStatus(); status != nil && status.State == "applying" &&
|
||||
status.At != nil && time.Since(*status.At) < envApplyingStale {
|
||||
return nil, nil, ErrEnvApplying
|
||||
}
|
||||
|
||||
request := envApplyRequest{Set: changes}
|
||||
if pending := m.readRequest(); pending != nil {
|
||||
for name, value := range pending.Set {
|
||||
if _, replaced := changes[name]; !replaced {
|
||||
request.Set[name] = value
|
||||
}
|
||||
}
|
||||
}
|
||||
id := make([]byte, 8)
|
||||
if _, err := rand.Read(id); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
request.ID = hex.EncodeToString(id)
|
||||
request.RequestedAt = time.Now().UTC()
|
||||
|
||||
if err := m.writeRequest(&request); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
names := make([]string, 0, len(request.Set))
|
||||
for name := range request.Set {
|
||||
names = append(names, name)
|
||||
}
|
||||
return generated, m.ServicesFor(names), nil
|
||||
}
|
||||
|
||||
// writeRequest writes request.json so the host only ever sees a complete
|
||||
// file it can read: temp name, owner and mode set, then rename.
|
||||
//
|
||||
// This process runs as root in the container while the host script runs as
|
||||
// the checkout's owner, so the file is handed to whoever owns the shared
|
||||
// directory. 0600 because it holds the new secrets in the clear until the
|
||||
// host consumes it.
|
||||
func (m *EnvManager) writeRequest(request *envApplyRequest) error {
|
||||
info, err := os.Stat(m.dir)
|
||||
if err != nil {
|
||||
return fmt.Errorf("the env-apply directory is not mounted: %w", err)
|
||||
}
|
||||
data, err := json.Marshal(request)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
tmp := filepath.Join(m.dir, envRequestFile+".tmp")
|
||||
if err := os.WriteFile(tmp, data, 0600); err != nil {
|
||||
return fmt.Errorf("writing env request: %w", err)
|
||||
}
|
||||
if stat, ok := info.Sys().(*syscall.Stat_t); ok {
|
||||
if err := os.Chown(tmp, int(stat.Uid), int(stat.Gid)); err != nil {
|
||||
os.Remove(tmp)
|
||||
return fmt.Errorf("handing env request to the host user: %w", err)
|
||||
}
|
||||
}
|
||||
if err := os.Rename(tmp, filepath.Join(m.dir, envRequestFile)); err != nil {
|
||||
os.Remove(tmp)
|
||||
return fmt.Errorf("writing env request: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Cancel withdraws a request the host has not claimed. Once claimed it is
|
||||
// too late, and this is a no-op.
|
||||
func (m *EnvManager) Cancel() error {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
if err := os.Remove(filepath.Join(m.dir, envRequestFile)); err != nil && !errors.Is(err, fs.ErrNotExist) {
|
||||
return fmt.Errorf("removing env request: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *EnvManager) readRequest() *envApplyRequest {
|
||||
raw, err := os.ReadFile(filepath.Join(m.dir, envRequestFile))
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
var request envApplyRequest
|
||||
if json.Unmarshal(raw, &request) != nil {
|
||||
return nil
|
||||
}
|
||||
return &request
|
||||
}
|
||||
|
||||
func (m *EnvManager) readStatus() *EnvApplyStatus {
|
||||
raw, err := os.ReadFile(filepath.Join(m.dir, envStatusFile))
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
var status EnvApplyStatus
|
||||
if json.Unmarshal(raw, &status) != nil {
|
||||
return nil
|
||||
}
|
||||
return &status
|
||||
}
|
||||
|
||||
// Status reports where the latest change has got to. An unclaimed request
|
||||
// takes precedence over status.json, which then describes an older change.
|
||||
func (m *EnvManager) Status() EnvApplyStatus {
|
||||
if request := m.readRequest(); request != nil {
|
||||
names := make([]string, 0, len(request.Set))
|
||||
for name := range request.Set {
|
||||
names = append(names, name)
|
||||
}
|
||||
slices.Sort(names)
|
||||
at := request.RequestedAt
|
||||
return EnvApplyStatus{
|
||||
State: "pending",
|
||||
ID: request.ID,
|
||||
At: &at,
|
||||
Pending: names,
|
||||
Services: m.ServicesFor(names),
|
||||
Watcher: time.Since(at) < envWatcherGrace,
|
||||
}
|
||||
}
|
||||
if status := m.readStatus(); status != nil {
|
||||
status.Watcher = true
|
||||
return *status
|
||||
}
|
||||
return EnvApplyStatus{State: "idle", Watcher: true}
|
||||
}
|
||||
@@ -0,0 +1,279 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func newEnvManager(t *testing.T) *EnvManager {
|
||||
t.Helper()
|
||||
m, err := NewEnvManager(t.TempDir())
|
||||
if err != nil {
|
||||
t.Fatalf("NewEnvManager: %v", err)
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
func readRequestFile(t *testing.T, m *EnvManager) envApplyRequest {
|
||||
t.Helper()
|
||||
raw, err := os.ReadFile(filepath.Join(m.dir, envRequestFile))
|
||||
if err != nil {
|
||||
t.Fatalf("reading request: %v", err)
|
||||
}
|
||||
var request envApplyRequest
|
||||
if err := json.Unmarshal(raw, &request); err != nil {
|
||||
t.Fatalf("parsing request: %v", err)
|
||||
}
|
||||
return request
|
||||
}
|
||||
|
||||
// The registry and .env.example describe the same variables; a name added to
|
||||
// one and not the other is either invisible in the panel or undocumented.
|
||||
func TestEnvRegistryMatchesEnvExample(t *testing.T) {
|
||||
raw, err := os.ReadFile("../../.env.example")
|
||||
if err != nil {
|
||||
t.Fatalf("reading .env.example: %v", err)
|
||||
}
|
||||
var example []string
|
||||
for _, match := range regexp.MustCompile(`(?m)^([A-Z][A-Z0-9_]*)=`).FindAllStringSubmatch(string(raw), -1) {
|
||||
example = append(example, match[1])
|
||||
}
|
||||
|
||||
var registry []string
|
||||
for _, v := range newEnvManager(t).Vars() {
|
||||
registry = append(registry, v.Name)
|
||||
}
|
||||
|
||||
for _, name := range example {
|
||||
if !slices.Contains(registry, name) {
|
||||
t.Errorf("%s is in .env.example but not in env_registry.json", name)
|
||||
}
|
||||
}
|
||||
for _, name := range registry {
|
||||
if !slices.Contains(example, name) {
|
||||
t.Errorf("%s is in env_registry.json but not in .env.example", name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestEnvRegistryEntriesAreWellFormed(t *testing.T) {
|
||||
kinds := []string{"secret", "generated", "text", "url", "bool", "duration", "number", "enum"}
|
||||
for _, v := range newEnvManager(t).Vars() {
|
||||
if !slices.Contains(kinds, v.Kind) {
|
||||
t.Errorf("%s has unknown kind %q", v.Name, v.Kind)
|
||||
}
|
||||
if v.Group == "" || v.Purpose == "" {
|
||||
t.Errorf("%s is missing its group or purpose", v.Name)
|
||||
}
|
||||
if v.Editable && len(v.Services) == 0 {
|
||||
t.Errorf("%s is editable but names no service to recreate", v.Name)
|
||||
}
|
||||
if !v.Editable && v.LockedReason == "" {
|
||||
t.Errorf("%s is locked without a reason", v.Name)
|
||||
}
|
||||
if v.Kind == "enum" && len(v.Options) == 0 {
|
||||
t.Errorf("%s is an enum with no options", v.Name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestEnvValidate(t *testing.T) {
|
||||
m := newEnvManager(t)
|
||||
cases := []struct {
|
||||
name, value string
|
||||
ok bool
|
||||
}{
|
||||
{"CLAUDE_API_KEY", "sk-ant-abc123", true},
|
||||
{"CLAUDE_API_KEY", "", true},
|
||||
// The injection case: a newline would start a second variable.
|
||||
{"CLAUDE_API_KEY", "x\nPOSTGRES_PASSWORD=owned", false},
|
||||
{"CLAUDE_API_KEY", "x\rY", false},
|
||||
{"CLAUDE_API_KEY", "it's", false},
|
||||
{"CLAUDE_API_KEY", strings.Repeat("a", envValueMaxLen+1), false},
|
||||
{"POSTGRES_PASSWORD", "anything", false},
|
||||
{"NOT_A_VARIABLE", "anything", false},
|
||||
{"EMAIL_BACKEND", "graph", true},
|
||||
{"EMAIL_BACKEND", "pop3", false},
|
||||
{"EMAIL_SYNC_INTERVAL", "45m", true},
|
||||
{"EMAIL_SYNC_INTERVAL", "soon", false},
|
||||
{"EMAIL_SYNC_INTERVAL", "-5m", false},
|
||||
{"EMAIL_SYNC_ENABLED", "true", true},
|
||||
{"EMAIL_SYNC_ENABLED", "yes", false},
|
||||
{"IMAP_PORT", "993", true},
|
||||
{"IMAP_PORT", "imaps", false},
|
||||
{"SPOTIFY_REDIRECT_URI", "https://example.com/api/spotify/callback", true},
|
||||
{"SPOTIFY_REDIRECT_URI", "example.com/callback", false},
|
||||
{"SPOTIFY_REDIRECT_URI", "javascript:alert(1)", false},
|
||||
}
|
||||
for _, c := range cases {
|
||||
err := m.Validate(c.name, c.value)
|
||||
if (err == nil) != c.ok {
|
||||
t.Errorf("Validate(%s, %q) error = %v, want ok = %v", c.name, c.value, err, c.ok)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestEnvSubmitWritesRequest(t *testing.T) {
|
||||
m := newEnvManager(t)
|
||||
generated, services, err := m.Submit(
|
||||
map[string]string{"TFL_APP_KEY": " tfl-key ", "STEAM_ID": ""},
|
||||
[]string{"ICECAST_RELAY_PASSWORD"},
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatalf("Submit: %v", err)
|
||||
}
|
||||
if len(generated["ICECAST_RELAY_PASSWORD"]) != 64 {
|
||||
t.Fatalf("generated value = %q, want 64 hex characters", generated["ICECAST_RELAY_PASSWORD"])
|
||||
}
|
||||
if want := []string{"backend", "icecast2", "python"}; !slices.Equal(services, want) {
|
||||
t.Fatalf("services = %v, want %v", services, want)
|
||||
}
|
||||
|
||||
request := readRequestFile(t, m)
|
||||
want := map[string]string{
|
||||
"TFL_APP_KEY": "tfl-key", // surrounding whitespace from a paste is dropped
|
||||
"STEAM_ID": "",
|
||||
"ICECAST_RELAY_PASSWORD": generated["ICECAST_RELAY_PASSWORD"],
|
||||
}
|
||||
if len(request.Set) != len(want) {
|
||||
t.Fatalf("request.Set = %v, want %v", request.Set, want)
|
||||
}
|
||||
for name, value := range want {
|
||||
if request.Set[name] != value {
|
||||
t.Errorf("request.Set[%s] = %q, want %q", name, request.Set[name], value)
|
||||
}
|
||||
}
|
||||
|
||||
info, err := os.Stat(filepath.Join(m.dir, envRequestFile))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if info.Mode().Perm() != 0600 {
|
||||
t.Errorf("request mode = %v, want 0600: it holds secrets in the clear", info.Mode().Perm())
|
||||
}
|
||||
}
|
||||
|
||||
func TestEnvSubmitRejectsWholeBatch(t *testing.T) {
|
||||
m := newEnvManager(t)
|
||||
cases := []struct {
|
||||
name string
|
||||
set map[string]string
|
||||
generate []string
|
||||
}{
|
||||
{"one bad value", map[string]string{"STEAM_ID": "1", "EMAIL_BACKEND": "pop3"}, nil},
|
||||
{"a locked variable", map[string]string{"STEAM_ID": "1", "DOMAIN": "evil.example"}, nil},
|
||||
{"generating a pasted secret", nil, []string{"CLAUDE_API_KEY"}},
|
||||
{"generating a locked secret", nil, []string{"POSTGRES_PASSWORD"}},
|
||||
{"nothing at all", nil, nil},
|
||||
}
|
||||
for _, c := range cases {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
if _, _, err := m.Submit(c.set, c.generate); err == nil {
|
||||
t.Fatal("Submit succeeded, want an error")
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(m.dir, envRequestFile)); !errors.Is(err, os.ErrNotExist) {
|
||||
t.Fatal("a rejected batch left a request file behind")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestEnvSubmitMergesUnclaimedRequest(t *testing.T) {
|
||||
m := newEnvManager(t)
|
||||
if _, _, err := m.Submit(map[string]string{"STEAM_ID": "1", "TFL_APP_KEY": "old"}, nil); err != nil {
|
||||
t.Fatalf("first Submit: %v", err)
|
||||
}
|
||||
if _, _, err := m.Submit(map[string]string{"TFL_APP_KEY": "new"}, nil); err != nil {
|
||||
t.Fatalf("second Submit: %v", err)
|
||||
}
|
||||
request := readRequestFile(t, m)
|
||||
if request.Set["STEAM_ID"] != "1" || request.Set["TFL_APP_KEY"] != "new" {
|
||||
t.Fatalf("merged request = %v, want the earlier STEAM_ID kept and TFL_APP_KEY replaced", request.Set)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEnvSubmitWithoutMount(t *testing.T) {
|
||||
m, err := NewEnvManager(filepath.Join(t.TempDir(), "absent"))
|
||||
if err != nil {
|
||||
t.Fatalf("NewEnvManager: %v", err)
|
||||
}
|
||||
if _, _, err := m.Submit(map[string]string{"STEAM_ID": "1"}, nil); err == nil {
|
||||
t.Fatal("Submit succeeded with no shared directory")
|
||||
}
|
||||
if got := m.Status().State; got != "idle" {
|
||||
t.Fatalf("Status().State = %q, want idle", got)
|
||||
}
|
||||
}
|
||||
|
||||
func writeStatusFile(t *testing.T, m *EnvManager, state string, at time.Time) {
|
||||
t.Helper()
|
||||
data, _ := json.Marshal(EnvApplyStatus{State: state, ID: "abc", At: &at})
|
||||
if err := os.WriteFile(filepath.Join(m.dir, envStatusFile), data, 0644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEnvStatus(t *testing.T) {
|
||||
m := newEnvManager(t)
|
||||
if got := m.Status(); got.State != "idle" || !got.Watcher {
|
||||
t.Fatalf("fresh status = %+v, want idle with watcher assumed", got)
|
||||
}
|
||||
|
||||
writeStatusFile(t, m, "applied", time.Now())
|
||||
if got := m.Status(); got.State != "applied" || got.ID != "abc" {
|
||||
t.Fatalf("status = %+v, want the host's applied report", got)
|
||||
}
|
||||
|
||||
// An unclaimed request outranks the report of an older change.
|
||||
if _, _, err := m.Submit(map[string]string{"CLAUDE_API_KEY": "sk-secret"}, nil); err != nil {
|
||||
t.Fatalf("Submit: %v", err)
|
||||
}
|
||||
got := m.Status()
|
||||
if got.State != "pending" || !slices.Equal(got.Pending, []string{"CLAUDE_API_KEY"}) || !got.Watcher {
|
||||
t.Fatalf("status = %+v, want pending CLAUDE_API_KEY", got)
|
||||
}
|
||||
if encoded, _ := json.Marshal(got); strings.Contains(string(encoded), "sk-secret") {
|
||||
t.Fatal("the status leaks a pending value")
|
||||
}
|
||||
|
||||
// Backdate the request past the grace period: nothing is watching.
|
||||
request := readRequestFile(t, m)
|
||||
request.RequestedAt = time.Now().Add(-2 * envWatcherGrace)
|
||||
if err := m.writeRequest(&request); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if m.Status().Watcher {
|
||||
t.Fatal("a long-unclaimed request still reports a watcher")
|
||||
}
|
||||
|
||||
if err := m.Cancel(); err != nil {
|
||||
t.Fatalf("Cancel: %v", err)
|
||||
}
|
||||
if got := m.Status().State; got != "applied" {
|
||||
t.Fatalf("after Cancel state = %q, want the earlier applied report", got)
|
||||
}
|
||||
if err := m.Cancel(); err != nil {
|
||||
t.Fatalf("Cancel with nothing pending: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEnvSubmitRefusedWhileApplying(t *testing.T) {
|
||||
m := newEnvManager(t)
|
||||
writeStatusFile(t, m, "applying", time.Now())
|
||||
if _, _, err := m.Submit(map[string]string{"STEAM_ID": "1"}, nil); !errors.Is(err, ErrEnvApplying) {
|
||||
t.Fatalf("Submit error = %v, want ErrEnvApplying", err)
|
||||
}
|
||||
|
||||
// A host script that died mid-run must not block the panel for ever.
|
||||
writeStatusFile(t, m, "applying", time.Now().Add(-2*envApplyingStale))
|
||||
if _, _, err := m.Submit(map[string]string{"STEAM_ID": "1"}, nil); err != nil {
|
||||
t.Fatalf("Submit after a stale applying status: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
[
|
||||
{"name": "CLAUDE_API_KEY", "group": "API keys", "purpose": "Email pipeline, rowing photo reader, job posting reader", "kind": "secret", "editable": true, "services": ["backend", "python"], "docsUrl": "https://console.anthropic.com/settings/keys"},
|
||||
{"name": "STEAM_API_KEY", "group": "API keys", "purpose": "Steam status widget", "kind": "secret", "editable": true, "services": ["backend"], "docsUrl": "https://steamcommunity.com/dev/apikey"},
|
||||
{"name": "STEAM_ID", "group": "API keys", "purpose": "Steam account the widget reports on (64-bit ID)", "kind": "text", "editable": true, "services": ["backend"]},
|
||||
{"name": "TFL_APP_KEY", "group": "API keys", "purpose": "TfL Unified API, used by the hotel finder", "kind": "secret", "editable": true, "services": ["python"], "docsUrl": "https://api-portal.tfl.gov.uk/profile"},
|
||||
|
||||
{"name": "SPOTIFY_CLIENT_ID", "group": "Spotify", "purpose": "Spotify listening widget", "kind": "text", "editable": true, "services": ["backend"], "docsUrl": "https://developer.spotify.com/dashboard"},
|
||||
{"name": "SPOTIFY_CLIENT_SECRET", "group": "Spotify", "purpose": "Spotify listening widget", "kind": "secret", "editable": true, "services": ["backend"], "docsUrl": "https://developer.spotify.com/dashboard"},
|
||||
{"name": "SPOTIFY_REDIRECT_URI", "group": "Spotify", "purpose": "Must match the URI registered in the Spotify dashboard exactly", "kind": "url", "editable": true, "services": ["backend"]},
|
||||
{"name": "SPOTIFY_AUTH_STATE", "group": "Spotify", "purpose": "Former fixed OAuth state", "kind": "secret", "editable": false, "lockedReason": "No longer read: the OAuth state is a per-request nonce."},
|
||||
|
||||
{"name": "EMAIL_BACKEND", "group": "Email ingest", "purpose": "Mail source for the email pipeline", "kind": "enum", "options": ["graph", "imap"], "editable": true, "services": ["backend"]},
|
||||
{"name": "EMAIL_SYNC_ENABLED", "group": "Email ingest", "purpose": "Run the periodic email sync", "kind": "bool", "editable": true, "services": ["backend"]},
|
||||
{"name": "EMAIL_SYNC_INTERVAL", "group": "Email ingest", "purpose": "Time between syncs, as a Go duration such as 30m (default 30m)", "kind": "duration", "editable": true, "services": ["backend"]},
|
||||
{"name": "MSGRAPH_CLIENT_ID", "group": "Email ingest", "purpose": "Microsoft Graph app registration", "kind": "text", "editable": true, "services": ["backend"], "docsUrl": "https://entra.microsoft.com/#view/Microsoft_AAD_RegisteredApps/ApplicationsListBlade"},
|
||||
{"name": "MSGRAPH_CLIENT_SECRET", "group": "Email ingest", "purpose": "Microsoft Graph app registration", "kind": "secret", "editable": true, "services": ["backend"], "docsUrl": "https://entra.microsoft.com/#view/Microsoft_AAD_RegisteredApps/ApplicationsListBlade"},
|
||||
{"name": "MSGRAPH_TENANT_ID", "group": "Email ingest", "purpose": "\"consumers\" for a personal outlook.com account", "kind": "text", "editable": true, "services": ["backend"]},
|
||||
{"name": "MSGRAPH_REDIRECT_URI", "group": "Email ingest", "purpose": "OAuth callback, behind the site's HTTPS origin", "kind": "url", "editable": true, "services": ["backend"]},
|
||||
{"name": "IMAP_HOST", "group": "Email ingest", "purpose": "IMAP fallback server", "kind": "text", "editable": true, "services": ["backend"]},
|
||||
{"name": "IMAP_PORT", "group": "Email ingest", "purpose": "IMAP fallback port (993)", "kind": "number", "editable": true, "services": ["backend"]},
|
||||
{"name": "IMAP_EMAIL", "group": "Email ingest", "purpose": "IMAP fallback account", "kind": "text", "editable": true, "services": ["backend"]},
|
||||
{"name": "IMAP_PASSWORD", "group": "Email ingest", "purpose": "App-specific password, not the account password", "kind": "secret", "editable": true, "services": ["backend"]},
|
||||
|
||||
{"name": "ICECAST_SOURCE_PASSWORD", "group": "Radio", "purpose": "Liquidsoap to Icecast, and live broadcasters to the harbor port", "kind": "generated", "editable": true, "services": ["icecast2"], "warning": "Live broadcasting clients must be given the new password."},
|
||||
{"name": "ICECAST_RELAY_PASSWORD", "group": "Radio", "purpose": "Icecast relay clients", "kind": "generated", "editable": true, "services": ["icecast2"]},
|
||||
{"name": "ICECAST_ADMIN_USER", "group": "Radio", "purpose": "Icecast web admin login", "kind": "text", "editable": true, "services": ["icecast2"]},
|
||||
{"name": "ICECAST_ADMIN_PASSWORD", "group": "Radio", "purpose": "Icecast web admin login", "kind": "generated", "editable": true, "services": ["icecast2"]},
|
||||
|
||||
{"name": "BACKEND_SECRET", "group": "Backend", "purpose": "Signs the JWTs in the auth cookies", "kind": "generated", "editable": true, "services": ["backend"], "warning": "Rotating this logs everyone out, including you."},
|
||||
{"name": "SILVERBULLET_GIT_INTERVAL", "group": "Backend", "purpose": "Seconds between notes commit/push cycles (default 300)", "kind": "number", "editable": true, "services": ["silverbullet-git"]},
|
||||
|
||||
{"name": "DOMAIN", "group": "Infrastructure", "purpose": "Apex domain: TLS certificate, cookie domain, nginx server name", "kind": "text", "editable": false, "lockedReason": "Changing the domain needs a new certificate and a full restart."},
|
||||
{"name": "EMAIL", "group": "Infrastructure", "purpose": "Let's Encrypt account address", "kind": "text", "editable": false, "lockedReason": "Only read by certbot when it registers the account."},
|
||||
{"name": "OBSIDIAN_DIR", "group": "Infrastructure", "purpose": "Host path of the notes vault", "kind": "text", "editable": false, "lockedReason": "A bind-mount path: a wrong value stops the stack from starting."},
|
||||
{"name": "SEED_DB", "group": "Infrastructure", "purpose": "Development-only test data switch", "kind": "bool", "editable": false, "lockedReason": "Would inject test data into the live site."},
|
||||
{"name": "BACKEND_HOST", "group": "Infrastructure", "purpose": "Backend container name and nginx upstream", "kind": "text", "editable": false, "lockedReason": "Renames a container and repoints nginx."},
|
||||
{"name": "BACKEND_PORT", "group": "Infrastructure", "purpose": "Backend listen port", "kind": "text", "editable": false, "lockedReason": "Renames a container or repoints nginx."},
|
||||
{"name": "BACKEND_ENDPOINT", "group": "Infrastructure", "purpose": "URL prefix nginx mounts the API at", "kind": "text", "editable": false, "lockedReason": "The Vue app assumes /api."},
|
||||
{"name": "PYTHON_HOST", "group": "Infrastructure", "purpose": "Python container name and nginx upstream", "kind": "text", "editable": false, "lockedReason": "Renames a container and repoints nginx."},
|
||||
{"name": "PYTHON_PORT", "group": "Infrastructure", "purpose": "Python listen port", "kind": "text", "editable": false, "lockedReason": "Renames a container or repoints nginx."},
|
||||
{"name": "ICECAST_HOST", "group": "Infrastructure", "purpose": "Icecast container name and nginx upstream", "kind": "text", "editable": false, "lockedReason": "Renames a container and repoints nginx."},
|
||||
{"name": "ICECAST_PORT", "group": "Infrastructure", "purpose": "Icecast listen port", "kind": "text", "editable": false, "lockedReason": "Renames a container or repoints nginx."},
|
||||
{"name": "ICECAST_MOUNT", "group": "Infrastructure", "purpose": "Listener-facing stream mount", "kind": "text", "editable": false, "lockedReason": "The player and nginx both assume this mount."},
|
||||
{"name": "LIQUIDSOAP_HARBOR_MOUNT", "group": "Infrastructure", "purpose": "Live broadcast mount", "kind": "text", "editable": false, "lockedReason": "Broadcasting clients are configured against it."},
|
||||
{"name": "LIQUIDSOAP_HARBOR_PORT", "group": "Infrastructure", "purpose": "Live broadcast port, published to the host", "kind": "text", "editable": false, "lockedReason": "A published port: changing it needs the router and clients updated."},
|
||||
{"name": "SILVERBULLET_HOST", "group": "Infrastructure", "purpose": "Notes editor container name", "kind": "text", "editable": false, "lockedReason": "Renames a container and repoints nginx."},
|
||||
{"name": "SILVERBULLET_PORT", "group": "Infrastructure", "purpose": "Notes editor port", "kind": "text", "editable": false, "lockedReason": "Renames a container or repoints nginx."},
|
||||
{"name": "SILVERBULLET_PUBLIC_HOST", "group": "Infrastructure", "purpose": "Public notes container name", "kind": "text", "editable": false, "lockedReason": "Renames a container and repoints nginx."},
|
||||
{"name": "SILVERBULLET_PUBLIC_PORT", "group": "Infrastructure", "purpose": "Public notes port", "kind": "text", "editable": false, "lockedReason": "Renames a container or repoints nginx."},
|
||||
|
||||
{"name": "POSTGRES_HOST", "group": "Database", "purpose": "Database container name", "kind": "text", "editable": false, "lockedReason": "Renames the database container."},
|
||||
{"name": "POSTGRES_PORT", "group": "Database", "purpose": "Database port", "kind": "text", "editable": false, "lockedReason": "Every client of the database assumes it."},
|
||||
{"name": "POSTGRES_USER", "group": "Database", "purpose": "Database role", "kind": "text", "editable": false, "lockedReason": "Only applied when the volume is first initialised; changing it here locks the backend out."},
|
||||
{"name": "POSTGRES_PASSWORD", "group": "Database", "purpose": "Database password", "kind": "secret", "editable": false, "lockedReason": "Only applied when the volume is first initialised; changing it here locks the backend out."},
|
||||
{"name": "POSTGRES_DB", "group": "Database", "purpose": "Backend database name", "kind": "text", "editable": false, "lockedReason": "Only applied when the volume is first initialised."},
|
||||
{"name": "POSTGRES_GITEA_DB", "group": "Database", "purpose": "Gitea database name", "kind": "text", "editable": false, "lockedReason": "Created by hand on a fresh volume."},
|
||||
|
||||
{"name": "GITEA_HOST", "group": "Gitea", "purpose": "Gitea container name and nginx upstream", "kind": "text", "editable": false, "lockedReason": "Renames a container and repoints nginx."},
|
||||
{"name": "GITEA_PORT", "group": "Gitea", "purpose": "Gitea HTTP port", "kind": "text", "editable": false, "lockedReason": "Renames a container or repoints nginx."},
|
||||
{"name": "GITEA_INTERNAL_TOKEN", "group": "Gitea", "purpose": "Gitea internal API token", "kind": "secret", "editable": false, "lockedReason": "Rotating Gitea's own secrets can invalidate its sessions and LFS links."},
|
||||
{"name": "GITEA_LFS_JWT_SECRET", "group": "Gitea", "purpose": "Gitea LFS token signing", "kind": "secret", "editable": false, "lockedReason": "Rotating Gitea's own secrets can invalidate its sessions and LFS links."},
|
||||
{"name": "GITEA_OAUTH2_JWT_SECRET", "group": "Gitea", "purpose": "Gitea OAuth2 token signing", "kind": "secret", "editable": false, "lockedReason": "Rotating Gitea's own secrets can invalidate its sessions and LFS links."},
|
||||
{"name": "GITEA_RUNNER_HOST", "group": "Gitea", "purpose": "Gitea URL the Actions runner registers against", "kind": "text", "editable": false, "lockedReason": "Read by gitea-runner/run.sh on the host, not by a container."},
|
||||
{"name": "GITEA_RUNNER_NAME", "group": "Gitea", "purpose": "Actions runner name", "kind": "text", "editable": false, "lockedReason": "Read by gitea-runner/run.sh on the host, not by a container."},
|
||||
{"name": "GITEA_RUNNER_REGISTRATION_TOKEN", "group": "Gitea", "purpose": "Single-use runner registration token", "kind": "secret", "editable": false, "lockedReason": "Single-use, and ignored once the runner is registered."}
|
||||
]
|
||||
Reference in New Issue
Block a user