feat(system): bootstrap values are read-only and the admin token rotates into the config (#2026)
This commit is contained in:
4 files changed
+227
No files matched your search
@@ -4,9 +4,11 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strings"
|
||||
|
||||
"filippo.io/age"
|
||||
"github.com/BurntSushi/toml"
|
||||
@@ -37,6 +39,73 @@ type DatabaseConfig struct {
|
||||
|
||||
var adminHash = regexp.MustCompile(`^[0-9a-f]{64}$`)
|
||||
|
||||
var adminLine = regexp.MustCompile(`(?m)^\s*admin_token_sha256\s*=.*$`)
|
||||
|
||||
// WriteAdminHash replaces the admin token hash in the config at path, keeping
|
||||
// every other line. The hash is the only value written: the old token and the
|
||||
// old hash are never read back or logged.
|
||||
func WriteAdminHash(path, hash string) error {
|
||||
if !adminHash.MatchString(hash) {
|
||||
return errors.New("an admin token hash is a hex SHA-256")
|
||||
}
|
||||
raw, err := os.ReadFile(path) //nolint:gosec // the path is the config the binary was started with.
|
||||
if err != nil {
|
||||
return fmt.Errorf("read config %s: %w", path, err)
|
||||
}
|
||||
line := `admin_token_sha256 = "` + hash + `"`
|
||||
next := string(raw)
|
||||
if adminLine.MatchString(next) {
|
||||
next = adminLine.ReplaceAllString(next, line)
|
||||
} else {
|
||||
next = strings.TrimRight(next, "\n") + "\n" + line + "\n"
|
||||
}
|
||||
if !strings.HasSuffix(next, "\n") {
|
||||
next += "\n"
|
||||
}
|
||||
return writeConfig(path, []byte(next))
|
||||
}
|
||||
|
||||
// writeConfig replaces path atomically, so a crash leaves either the old file
|
||||
// or the new one.
|
||||
func writeConfig(path string, data []byte) error {
|
||||
dir := filepath.Dir(path)
|
||||
file, err := os.CreateTemp(dir, ".config-*")
|
||||
if err != nil {
|
||||
return fmt.Errorf("write config %s: %w", path, err)
|
||||
}
|
||||
name := file.Name()
|
||||
defer func() { _ = os.Remove(name) }()
|
||||
if err := file.Chmod(0o600); err != nil {
|
||||
_ = file.Close()
|
||||
return fmt.Errorf("write config %s: %w", path, err)
|
||||
}
|
||||
if _, err := file.Write(data); err != nil {
|
||||
_ = file.Close()
|
||||
return fmt.Errorf("write config %s: %w", path, err)
|
||||
}
|
||||
if err := file.Sync(); err != nil {
|
||||
_ = file.Close()
|
||||
return fmt.Errorf("write config %s: %w", path, err)
|
||||
}
|
||||
if err := file.Close(); err != nil {
|
||||
return fmt.Errorf("write config %s: %w", path, err)
|
||||
}
|
||||
if err := os.Rename(name, path); err != nil {
|
||||
return fmt.Errorf("write config %s: %w", path, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// DatabaseHost is the host a database URL names, without credentials or the
|
||||
// database name. It is what the dashboard shows.
|
||||
func DatabaseHost(raw string) string {
|
||||
u, err := url.Parse(raw)
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
return u.Host
|
||||
}
|
||||
|
||||
// DefaultConfigPath is ${XDG_CONFIG_HOME:-~/.config}/archie/config.toml.
|
||||
func DefaultConfigPath() string {
|
||||
dir, err := os.UserConfigDir()
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
package archie
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// TestWriteAdminHashReplacesOnlyTheHash guards token rotation: the config keeps
|
||||
// every other value, the old hash is gone, and the file is not left readable.
|
||||
func TestWriteAdminHashReplacesOnlyTheHash(t *testing.T) {
|
||||
const oldHash = "1111111111111111111111111111111111111111111111111111111111111111"
|
||||
const newHash = "2222222222222222222222222222222222222222222222222222222222222222"
|
||||
path := filepath.Join(t.TempDir(), "config.toml")
|
||||
before := "listen = \"127.0.0.1:8080\"\nadmin_token_sha256 = \"" + oldHash + "\"\n"
|
||||
if err := os.WriteFile(path, []byte(before), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if err := WriteAdminHash(path, newHash); err != nil {
|
||||
t.Fatalf("rotate: %v", err)
|
||||
}
|
||||
|
||||
got, err := os.ReadFile(path) //nolint:gosec // a test fixture in t.TempDir.
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
text := string(got)
|
||||
switch {
|
||||
case strings.Contains(text, oldHash):
|
||||
t.Fatal("the old hash is still in the config")
|
||||
case !strings.Contains(text, newHash):
|
||||
t.Fatal("the new hash was not written")
|
||||
case !strings.Contains(text, `listen = "127.0.0.1:8080"`):
|
||||
t.Fatal("rotation changed another setting")
|
||||
}
|
||||
info, err := os.Stat(path) //nolint:gosec // a test fixture in t.TempDir.
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if info.Mode().Perm() != 0o600 {
|
||||
t.Fatalf("config mode is %o, want 600", info.Mode().Perm())
|
||||
}
|
||||
}
|
||||
|
||||
// TestWriteAdminHashAddsAMissingLine guards a config written before the hash
|
||||
// was set.
|
||||
func TestWriteAdminHashAddsAMissingLine(t *testing.T) {
|
||||
const hash = "3333333333333333333333333333333333333333333333333333333333333333"
|
||||
path := filepath.Join(t.TempDir(), "config.toml")
|
||||
if err := os.WriteFile(path, []byte("listen = \"127.0.0.1:8080\"\n"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := WriteAdminHash(path, hash); err != nil {
|
||||
t.Fatalf("rotate: %v", err)
|
||||
}
|
||||
got, err := os.ReadFile(path) //nolint:gosec // a test fixture in t.TempDir.
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !strings.Contains(string(got), hash) {
|
||||
t.Fatal("the hash was not added")
|
||||
}
|
||||
}
|
||||
@@ -33,6 +33,7 @@ import (
|
||||
"github.com/samcharles93/archie-core/modules/judgement"
|
||||
"github.com/samcharles93/archie-core/modules/memory"
|
||||
"github.com/samcharles93/archie-core/modules/runs"
|
||||
"github.com/samcharles93/archie-core/modules/system"
|
||||
"github.com/samcharles93/archie-core/ui"
|
||||
)
|
||||
|
||||
@@ -78,6 +79,14 @@ func Run(ctx context.Context, configPath string) error {
|
||||
}
|
||||
checks.Register("connectors", conns.Ready)
|
||||
conns.Routes(mux, guard)
|
||||
// A model's key is a credential name resolved through the sealed store.
|
||||
settings.UseCredentials(conns)
|
||||
|
||||
system.New(system.Bootstrap{
|
||||
Listen: cfg.Listen, Database: DatabaseHost(cfg.Database.URL), Schemas: len(schemas),
|
||||
AdminPrefix: cfg.AdminTokenSHA256[:8], AdminSet: cfg.AdminTokenSHA256 != "",
|
||||
Sealing: cfg.AgeIdentity != "",
|
||||
}, func(hash string) error { return WriteAdminHash(configPath, hash) }, log.With("module", "system")).Routes(mux, guard)
|
||||
|
||||
live := hub.New()
|
||||
// Messages go to the composer and to every accepted connector that delivers
|
||||
@@ -99,6 +108,7 @@ func Run(ctx context.Context, configPath string) error {
|
||||
hear := events.NewModule(db, log.With("module", "events"), orgID, conns, engine, allow, tell)
|
||||
hear.Routes(mux, guard)
|
||||
judge := newJudgement(db, log, conns, classes, policies, settings, hear)
|
||||
judge.Routes(mux, guard)
|
||||
if err := useWorkflows(ctx, engine, runs.Deps{Settings: settings, Toolbox: conns, Judge: judge, Approver: allow, Notifier: tell, Memory: memory.NewModule(db, orgID)}); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
// Package system serves the bootstrap values the binary reads before the
|
||||
// database is reachable, read-only, and the one change that must survive a
|
||||
// restart: the admin token.
|
||||
package system
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"sync"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/platform/httpjson"
|
||||
)
|
||||
|
||||
// Bootstrap is what the binary loaded from config.toml, reduced to values safe
|
||||
// to show: no connection URL and no secret.
|
||||
type Bootstrap struct {
|
||||
Listen string `json:"listen"`
|
||||
Database string `json:"database_host"`
|
||||
Schemas int `json:"schemas"`
|
||||
AdminPrefix string `json:"admin_token_hash_prefix"`
|
||||
AdminSet bool `json:"admin_token_set"`
|
||||
Sealing bool `json:"sealing_identity_set"`
|
||||
}
|
||||
|
||||
// Module serves the bootstrap view and rotates the admin token.
|
||||
type Module struct {
|
||||
mu sync.RWMutex
|
||||
bootstrap Bootstrap
|
||||
rotate func(hash string) error
|
||||
log *slog.Logger
|
||||
}
|
||||
|
||||
// New returns the system module. rotate writes a new admin token hash to the
|
||||
// config the binary loaded.
|
||||
func New(b Bootstrap, rotate func(hash string) error, log *slog.Logger) *Module {
|
||||
return &Module{bootstrap: b, rotate: rotate, log: log}
|
||||
}
|
||||
|
||||
// Routes adds the system API to mux behind guard.
|
||||
func (m *Module) Routes(mux *http.ServeMux, guard func(http.Handler) http.Handler) {
|
||||
mux.Handle("GET /api/system/bootstrap", guard(http.HandlerFunc(m.getBootstrap)))
|
||||
mux.Handle("POST /api/admin/token", guard(http.HandlerFunc(m.rotateAdminToken)))
|
||||
}
|
||||
|
||||
func (m *Module) getBootstrap(w http.ResponseWriter, _ *http.Request) {
|
||||
m.mu.RLock()
|
||||
defer m.mu.RUnlock()
|
||||
httpjson.Write(w, http.StatusOK, m.bootstrap)
|
||||
}
|
||||
|
||||
// rotateAdminToken generates a new token, writes only its hash to the config,
|
||||
// and returns the token once. The old token and the old hash are never read
|
||||
// back or logged.
|
||||
func (m *Module) rotateAdminToken(w http.ResponseWriter, r *http.Request) {
|
||||
token, err := newToken()
|
||||
if err != nil {
|
||||
m.log.ErrorContext(r.Context(), "generate admin token", "error", err)
|
||||
httpjson.Error(w, http.StatusInternalServerError, "couldn't generate a token")
|
||||
return
|
||||
}
|
||||
hash := httpjson.TokenHash(token)
|
||||
if err := m.rotate(hash); err != nil {
|
||||
m.log.ErrorContext(r.Context(), "write admin token hash", "error", err)
|
||||
httpjson.Error(w, http.StatusInternalServerError, "couldn't write the new token hash to the config")
|
||||
return
|
||||
}
|
||||
m.mu.Lock()
|
||||
m.bootstrap.AdminPrefix, m.bootstrap.AdminSet = hash[:8], true
|
||||
m.mu.Unlock()
|
||||
m.log.InfoContext(r.Context(), "admin token rotated", "audit", true, "action", "admin.token.rotate")
|
||||
httpjson.Write(w, http.StatusOK, map[string]string{"token": token})
|
||||
}
|
||||
|
||||
func newToken() (string, error) {
|
||||
b := make([]byte, 32)
|
||||
if _, err := rand.Read(b); err != nil {
|
||||
return "", fmt.Errorf("generate token: %w", err)
|
||||
}
|
||||
return hex.EncodeToString(b), nil
|
||||
}
|
||||
Reference in new issue
Block a user