Files
archie/modules/system/system.go
T

84 lines
2.8 KiB
Go

// 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
}