feat(api): give status page servers sealed key-value storage

Certificates and ACME keys are stored encrypted in the database,
namespaced per owner so an organization's servers cannot read platform
or other organizations' keys. Locks live in Redis and expire.

Refs #22

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
This commit is contained in:
Sebastian UnterschützandClaude Opus 5.5 committed 2026-11-22 08:54:08 +01:00
1 parent f52ae33cf0
commit 46f1f82481
11 files changed
+611 -1

No files matched your search

+9 -1
View File
@@ -32,7 +32,15 @@ const (
func (s *Server) mountAgentAPI(r gin.IRouter) {
g := r.Group("/agent/v1", s.agentAuth())
g.GET("/hello", s.agentHello)
g.GET("/pages", requireAgentKind("statuspage"), s.agentPage)
sp := g.Group("", requireAgentKind("statuspage"))
sp.GET("/pages", s.agentPage)
sp.GET("/storage", s.storageGet)
sp.PUT("/storage", s.storagePut)
sp.DELETE("/storage", s.storageDelete)
sp.GET("/storage/stat", s.storageStat)
sp.GET("/storage/list", s.storageList)
sp.POST("/storage/lock", s.storageLock)
sp.DELETE("/storage/lock", s.storageUnlock)
checker := g.Group("", requireAgentKind("checker"))
checker.POST("/jobs", s.agentJobs)
checker.POST("/results", s.agentResults)
+221
View File
@@ -0,0 +1,221 @@
package api
import (
"errors"
"io"
"net/http"
"slices"
"strings"
"time"
"github.com/gin-gonic/gin"
"github.com/jackc/pgx/v5"
"git.zb-server.de/ZB-Server/uptimesebi/internal/agentapi"
"git.zb-server.de/ZB-Server/uptimesebi/internal/store"
"git.zb-server.de/ZB-Server/uptimesebi/internal/tenant"
)
const (
maxStorageValue = 1 << 20
storageLockTTL = 2 * time.Minute
)
// storageOwner namespaces storage per agent owner: an organization's status
// page servers never see platform keys or another organization's.
func storageOwner(c *gin.Context) string {
if org := agentOf(c).OrgID; org != nil {
return "org:" + org.String()
}
return "platform"
}
func storageAAD(owner, key string) []byte { return []byte(owner + "\x00" + key) }
func storageKey(c *gin.Context, param string) (string, bool) {
k := c.Query(param)
if k == "" || len(k) > 1000 || strings.Contains(k, "\x00") {
fail(c, http.StatusBadRequest, "invalid_input")
return "", false
}
return k, true
}
func (s *Server) storageGet(c *gin.Context) {
key, ok := storageKey(c, "key")
if !ok {
return
}
ctx := c.Request.Context()
owner := storageOwner(c)
var row store.StorageGetRow
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
var err error
row, err = q.StorageGet(ctx, store.StorageGetParams{Owner: owner, Key: key})
return err
})
if errors.Is(err, pgx.ErrNoRows) {
fail(c, http.StatusNotFound, "not_found")
return
}
if err != nil {
internalError(c, err)
return
}
value, err := s.keys.Open(row.Value, storageAAD(owner, key))
if err != nil {
internalError(c, err)
return
}
c.Data(http.StatusOK, "application/octet-stream", value)
}
func (s *Server) storagePut(c *gin.Context) {
key, ok := storageKey(c, "key")
if !ok {
return
}
value, err := io.ReadAll(io.LimitReader(c.Request.Body, maxStorageValue+1))
if err != nil || len(value) > maxStorageValue {
fail(c, http.StatusRequestEntityTooLarge, "invalid_input")
return
}
ctx := c.Request.Context()
owner := storageOwner(c)
err = s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
return q.StoragePut(ctx, store.StoragePutParams{Owner: owner, Key: key, Value: s.keys.Seal(value, storageAAD(owner, key))})
})
if err != nil {
internalError(c, err)
return
}
c.Status(http.StatusNoContent)
}
func (s *Server) storageDelete(c *gin.Context) {
key, ok := storageKey(c, "key")
if !ok {
return
}
ctx := c.Request.Context()
var n int64
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
var err error
n, err = q.StorageDelete(ctx, store.StorageDeleteParams{Owner: storageOwner(c), Key: key})
return err
})
if err != nil {
internalError(c, err)
return
}
if n == 0 {
fail(c, http.StatusNotFound, "not_found")
return
}
c.Status(http.StatusNoContent)
}
func (s *Server) storageEntries(c *gin.Context, prefix string) ([]store.StorageListRow, error) {
ctx := c.Request.Context()
var rows []store.StorageListRow
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
var err error
rows, err = q.StorageList(ctx, store.StorageListParams{Owner: storageOwner(c), Prefix: prefix})
return err
})
return rows, err
}
func (s *Server) storageStat(c *gin.Context) {
key, ok := storageKey(c, "key")
if !ok {
return
}
ctx := c.Request.Context()
var row store.StorageGetRow
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
var err error
row, err = q.StorageGet(ctx, store.StorageGetParams{Owner: storageOwner(c), Key: key})
return err
})
switch {
case err == nil:
c.JSON(http.StatusOK, agentapi.StorageInfo{Key: key, Modified: row.Modified, Size: int64(len(row.Value)), IsTerminal: true})
return
case !errors.Is(err, pgx.ErrNoRows):
internalError(c, err)
return
}
// Not a value, but possibly a directory of values.
below, err := s.storageEntries(c, key)
if err != nil {
internalError(c, err)
return
}
if len(below) == 0 {
fail(c, http.StatusNotFound, "not_found")
return
}
c.JSON(http.StatusOK, agentapi.StorageInfo{Key: key, IsTerminal: false})
}
func (s *Server) storageList(c *gin.Context) {
prefix := strings.TrimSuffix(c.Query("prefix"), "/")
recursive := c.Query("recursive") == "true"
rows, err := s.storageEntries(c, prefix)
if err != nil {
internalError(c, err)
return
}
keys := []string{}
for _, r := range rows {
k := r.Key
if !recursive {
rest := strings.TrimPrefix(k, prefix)
rest = strings.TrimPrefix(rest, "/")
first, _, _ := strings.Cut(rest, "/")
k = first
if prefix != "" {
k = prefix + "/" + first
}
}
if !slices.Contains(keys, k) {
keys = append(keys, k)
}
}
c.JSON(http.StatusOK, gin.H{"keys": keys})
}
func lockKey(c *gin.Context, name string) string {
return "storage-lock:" + storageOwner(c) + ":" + name
}
// storageLock tries once; agents retry until they get the lock.
func (s *Server) storageLock(c *gin.Context) {
name, ok := storageKey(c, "name")
if !ok {
return
}
got, err := s.rdb.SetNX(c.Request.Context(), lockKey(c, name), "1", storageLockTTL).Result()
if err != nil {
internalError(c, err)
return
}
if !got {
fail(c, http.StatusConflict, "locked")
return
}
c.Status(http.StatusNoContent)
}
func (s *Server) storageUnlock(c *gin.Context) {
name, ok := storageKey(c, "name")
if !ok {
return
}
if err := s.rdb.Del(c.Request.Context(), lockKey(c, name)).Err(); err != nil {
internalError(c, err)
return
}
c.Status(http.StatusNoContent)
}
+118
View File
@@ -0,0 +1,118 @@
package api_test
import (
"bytes"
"context"
"errors"
"io/fs"
"log/slog"
"slices"
"testing"
"time"
"github.com/google/uuid"
"git.zb-server.de/ZB-Server/uptimesebi/internal/i18n"
"git.zb-server.de/ZB-Server/uptimesebi/internal/statuspage"
)
func TestCertStorage(t *testing.T) {
e := newEnv(t)
ctx := context.Background()
platform := statuspage.NewCertStorage(e.statuspageClient(t, nil))
base := "certificates/" + uuid.NewString()[:8]
key := base + "/example.com/example.com.key"
if err := platform.Store(ctx, key, []byte("private key")); err != nil {
t.Fatalf("Store() failed: %v", err)
}
if err := platform.Store(ctx, base+"/example.com/example.com.crt", []byte("cert")); err != nil {
t.Fatal(err)
}
if got, err := platform.Load(ctx, key); err != nil || !bytes.Equal(got, []byte("private key")) {
t.Errorf("Load() = %q, %v", got, err)
}
if _, err := platform.Load(ctx, base+"/missing"); !errors.Is(err, fs.ErrNotExist) {
t.Errorf("Load(missing) error = %v, want fs.ErrNotExist", err)
}
if !platform.Exists(ctx, key) || platform.Exists(ctx, base+"/missing") {
t.Error("Exists() wrong")
}
if info, err := platform.Stat(ctx, base+"/example.com"); err != nil || info.IsTerminal {
t.Errorf("Stat(directory) = %+v, %v; want non-terminal", info, err)
}
if info, err := platform.Stat(ctx, key); err != nil || !info.IsTerminal || info.Size == 0 {
t.Errorf("Stat(key) = %+v, %v", info, err)
}
if got, err := platform.List(ctx, base, false); err != nil || !slices.Equal(got, []string{base + "/example.com"}) {
t.Errorf("List(non-recursive) = %v, %v", got, err)
}
if got, err := platform.List(ctx, base, true); err != nil || len(got) != 2 {
t.Errorf("List(recursive) = %v, %v", got, err)
}
var stored []byte
_ = e.dbPool.QueryRow(ctx, `SELECT value FROM agent_storage WHERE key = $1`, key).Scan(&stored)
if bytes.Contains(stored, []byte("private key")) {
t.Error("value stored in plain text")
}
other := e.browser(t)
other.signup("x@"+uniq("cs")+".test", uniq("cs-"))
org := uuid.MustParse(other.orgID())
orgStore := statuspage.NewCertStorage(e.statuspageClient(t, &org))
if _, err := orgStore.Load(ctx, key); !errors.Is(err, fs.ErrNotExist) {
t.Errorf("org server loaded a platform key: %v", err)
}
if err := platform.Lock(ctx, "issue-example.com"); err != nil {
t.Fatal(err)
}
locked, cancel := context.WithTimeout(ctx, 500*time.Millisecond)
defer cancel()
if err := platform.Lock(locked, "issue-example.com"); !errors.Is(err, context.DeadlineExceeded) {
t.Errorf("second Lock() = %v, want to wait until the deadline", err)
}
if err := orgStore.Lock(ctx, "issue-example.com"); err != nil {
t.Errorf("org Lock() on its own namespace failed: %v", err)
}
_ = platform.Unlock(ctx, "issue-example.com")
if err := platform.Lock(ctx, "issue-example.com"); err != nil {
t.Errorf("Lock() after Unlock() failed: %v", err)
}
if err := platform.Delete(ctx, base+"/example.com"); err != nil {
t.Fatal(err)
}
if _, err := platform.List(ctx, base, true); !errors.Is(err, fs.ErrNotExist) {
t.Errorf("List() after deleting the directory = %v, want fs.ErrNotExist", err)
}
}
func TestAllowCertificate(t *testing.T) {
e := newEnv(t)
owner := e.browser(t)
owner.signup("o@"+uniq("ac")+".test", uniq("ac-"))
_, body := owner.do("POST", "/api/v1/org/statuspages", map[string]any{"slug": uniq("ac-"), "title": "T", "published": true})
pageID := body["id"].(string)
domain := uniq("s") + ".example.test"
_, body = owner.do("PUT", "/api/v1/org/statuspages/"+pageID+"/domain", map[string]any{"domain": domain})
record := body["domain_record"].(map[string]any)
cat, _ := i18n.Load()
srv := statuspage.New(e.statuspageClient(t, nil), cat, slog.New(slog.DiscardHandler), []string{"status.test"})
ctx := context.Background()
if err := srv.AllowCertificate(ctx, "status.test"); err != nil {
t.Errorf("AllowCertificate(default host) = %v", err)
}
if err := srv.AllowCertificate(ctx, domain); err == nil {
t.Error("AllowCertificate(unverified domain) = nil, want refusal")
}
if err := srv.AllowCertificate(ctx, "random.example.test"); err == nil {
t.Error("AllowCertificate(unknown name) = nil, want refusal")
}
verifyDomain(t, owner, pageID, record)
if err := srv.AllowCertificate(ctx, domain); err != nil {
t.Errorf("AllowCertificate(verified domain) = %v", err)
}
}