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:
1 parent
f52ae33cf0
commit
46f1f82481
11 files changed
+611
-1
No files matched your search
@@ -0,0 +1,108 @@
|
||||
package agentapi
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"time"
|
||||
)
|
||||
|
||||
// StorageInfo describes a stored key; IsTerminal is false for keys that only
|
||||
// exist as a prefix of others.
|
||||
type StorageInfo struct {
|
||||
Key string `json:"key"`
|
||||
Modified time.Time `json:"modified"`
|
||||
Size int64 `json:"size"`
|
||||
IsTerminal bool `json:"is_terminal"`
|
||||
}
|
||||
|
||||
// ErrLocked means another instance holds a storage lock.
|
||||
var ErrLocked = errors.New("agentapi: locked")
|
||||
|
||||
func (c *Client) raw(ctx context.Context, method, path string, body []byte) ([]byte, error) {
|
||||
var rd io.Reader
|
||||
if body != nil {
|
||||
rd = bytes.NewReader(body)
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx, method, c.base+"/agent/v1"+path, rd)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
req.Header.Set("Authorization", "Bearer "+c.token)
|
||||
req.Header.Set(VersionHeader, strconv.Itoa(Version))
|
||||
req.Header.Set(InstanceHeader, c.instance.String())
|
||||
req.Header.Set(ReleaseHeader, c.release)
|
||||
resp, err := c.hc.Do(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
out, err := io.ReadAll(io.LimitReader(resp.Body, 2<<20))
|
||||
switch {
|
||||
case resp.StatusCode == http.StatusNotFound:
|
||||
return nil, ErrNotFound
|
||||
case resp.StatusCode == http.StatusConflict:
|
||||
return nil, ErrLocked
|
||||
case resp.StatusCode == http.StatusUnauthorized:
|
||||
return nil, ErrUnauthorized
|
||||
case resp.StatusCode >= 300:
|
||||
return nil, fmt.Errorf("agentapi: %s %s: %d", method, path, resp.StatusCode)
|
||||
}
|
||||
return out, err
|
||||
}
|
||||
|
||||
func keyQuery(name, value string) string { return "?" + url.Values{name: {value}}.Encode() }
|
||||
|
||||
// StorageGet returns the value of key or ErrNotFound.
|
||||
func (c *Client) StorageGet(ctx context.Context, key string) ([]byte, error) {
|
||||
return c.raw(ctx, http.MethodGet, "/storage"+keyQuery("key", key), nil)
|
||||
}
|
||||
|
||||
// StoragePut stores value under key.
|
||||
func (c *Client) StoragePut(ctx context.Context, key string, value []byte) error {
|
||||
if value == nil {
|
||||
value = []byte{}
|
||||
}
|
||||
_, err := c.raw(ctx, http.MethodPut, "/storage"+keyQuery("key", key), value)
|
||||
return err
|
||||
}
|
||||
|
||||
// StorageDelete removes key and everything below it.
|
||||
func (c *Client) StorageDelete(ctx context.Context, key string) error {
|
||||
_, err := c.raw(ctx, http.MethodDelete, "/storage"+keyQuery("key", key), nil)
|
||||
return err
|
||||
}
|
||||
|
||||
// StorageStat describes key.
|
||||
func (c *Client) StorageStat(ctx context.Context, key string) (StorageInfo, error) {
|
||||
var info StorageInfo
|
||||
err := c.do(ctx, http.MethodGet, "/storage/stat"+keyQuery("key", key), nil, &info)
|
||||
return info, err
|
||||
}
|
||||
|
||||
// StorageList lists keys below prefix.
|
||||
func (c *Client) StorageList(ctx context.Context, prefix string, recursive bool) ([]string, error) {
|
||||
var out struct {
|
||||
Keys []string `json:"keys"`
|
||||
}
|
||||
q := url.Values{"prefix": {prefix}, "recursive": {strconv.FormatBool(recursive)}}
|
||||
err := c.do(ctx, http.MethodGet, "/storage/list?"+q.Encode(), nil, &out)
|
||||
return out.Keys, err
|
||||
}
|
||||
|
||||
// StorageLock tries to take the lock name once.
|
||||
func (c *Client) StorageLock(ctx context.Context, name string) error {
|
||||
_, err := c.raw(ctx, http.MethodPost, "/storage/lock"+keyQuery("name", name), nil)
|
||||
return err
|
||||
}
|
||||
|
||||
// StorageUnlock releases the lock name.
|
||||
func (c *Client) StorageUnlock(ctx context.Context, name string) error {
|
||||
_, err := c.raw(ctx, http.MethodDelete, "/storage/lock"+keyQuery("name", name), nil)
|
||||
return err
|
||||
}
|
||||
@@ -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)
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -101,6 +101,7 @@
|
||||
"error.invitation_email_mismatch": "Diese Einladung ging an eine andere E-Mail-Adresse als die, mit der du angemeldet bist.",
|
||||
"error.invitation_invalid": "Diese Einladung ist ungültig, abgelaufen oder wurde bereits verwendet.",
|
||||
"error.keyword_needs_get": "Keyword-Checks brauchen GET-Anfragen.",
|
||||
"error.locked": "Die Ressource ist von einem anderen Prozess gesperrt.",
|
||||
"error.mfa_expired": "Anmeldung abgelaufen, bitte erneut anmelden.",
|
||||
"error.no_domain": "Lege zuerst eine eigene Domain fest.",
|
||||
"error.no_password": "Konto ohne Passwort.",
|
||||
|
||||
@@ -101,6 +101,7 @@
|
||||
"error.invitation_email_mismatch": "This invitation was sent to a different email address than the one you are signed in with.",
|
||||
"error.invitation_invalid": "This invitation is invalid, expired or was already used.",
|
||||
"error.keyword_needs_get": "Keyword checks need GET requests.",
|
||||
"error.locked": "The resource is locked by another process.",
|
||||
"error.mfa_expired": "Sign-in expired, please start again.",
|
||||
"error.no_domain": "Set a custom domain first.",
|
||||
"error.no_password": "This account has no password.",
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
-- +goose Up
|
||||
-- Key-value storage for status page servers, which have no database of
|
||||
-- their own: TLS certificates and ACME account keys. Values are sealed by
|
||||
-- the application. Owner separates platform servers from each
|
||||
-- organization's servers so none can read another's private keys.
|
||||
CREATE TABLE agent_storage (
|
||||
owner text NOT NULL,
|
||||
key text NOT NULL CHECK (length(key) BETWEEN 1 AND 1000),
|
||||
value bytea NOT NULL,
|
||||
modified timestamptz NOT NULL DEFAULT now(),
|
||||
PRIMARY KEY (owner, key)
|
||||
);
|
||||
|
||||
-- Only reached through agent handlers in the system scope.
|
||||
ALTER TABLE agent_storage ENABLE ROW LEVEL SECURITY;
|
||||
ALTER TABLE agent_storage FORCE ROW LEVEL SECURITY;
|
||||
CREATE POLICY agent_storage_system ON agent_storage FOR ALL
|
||||
USING (app_scope_system()) WITH CHECK (app_scope_system());
|
||||
|
||||
-- +goose Down
|
||||
DROP TABLE agent_storage;
|
||||
@@ -0,0 +1,104 @@
|
||||
// Code generated by sqlc. DO NOT EDIT.
|
||||
// versions:
|
||||
// sqlc v1.31.1
|
||||
// source: agent_storage.sql
|
||||
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
)
|
||||
|
||||
const storageDelete = `-- name: StorageDelete :execrows
|
||||
DELETE FROM agent_storage
|
||||
WHERE owner = $1 AND (key = $2 OR starts_with(key, $2::text || '/'))
|
||||
`
|
||||
|
||||
type StorageDeleteParams struct {
|
||||
Owner string
|
||||
Key string
|
||||
}
|
||||
|
||||
// Deletes key and, as certmagic expects, everything below it.
|
||||
func (q *Queries) StorageDelete(ctx context.Context, arg StorageDeleteParams) (int64, error) {
|
||||
result, err := q.db.Exec(ctx, storageDelete, arg.Owner, arg.Key)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return result.RowsAffected(), nil
|
||||
}
|
||||
|
||||
const storageGet = `-- name: StorageGet :one
|
||||
SELECT value, modified FROM agent_storage WHERE owner = $1 AND key = $2
|
||||
`
|
||||
|
||||
type StorageGetParams struct {
|
||||
Owner string
|
||||
Key string
|
||||
}
|
||||
|
||||
type StorageGetRow struct {
|
||||
Value []byte
|
||||
Modified time.Time
|
||||
}
|
||||
|
||||
func (q *Queries) StorageGet(ctx context.Context, arg StorageGetParams) (StorageGetRow, error) {
|
||||
row := q.db.QueryRow(ctx, storageGet, arg.Owner, arg.Key)
|
||||
var i StorageGetRow
|
||||
err := row.Scan(&i.Value, &i.Modified)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const storageList = `-- name: StorageList :many
|
||||
SELECT key, length(value)::bigint AS size, modified FROM agent_storage
|
||||
WHERE owner = $1 AND ($2::text = '' OR starts_with(key, $2::text || '/'))
|
||||
ORDER BY key
|
||||
`
|
||||
|
||||
type StorageListParams struct {
|
||||
Owner string
|
||||
Prefix string
|
||||
}
|
||||
|
||||
type StorageListRow struct {
|
||||
Key string
|
||||
Size int64
|
||||
Modified time.Time
|
||||
}
|
||||
|
||||
func (q *Queries) StorageList(ctx context.Context, arg StorageListParams) ([]StorageListRow, error) {
|
||||
rows, err := q.db.Query(ctx, storageList, arg.Owner, arg.Prefix)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
items := []StorageListRow{}
|
||||
for rows.Next() {
|
||||
var i StorageListRow
|
||||
if err := rows.Scan(&i.Key, &i.Size, &i.Modified); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const storagePut = `-- name: StoragePut :exec
|
||||
INSERT INTO agent_storage (owner, key, value) VALUES ($1, $2, $3)
|
||||
ON CONFLICT (owner, key) DO UPDATE SET value = EXCLUDED.value, modified = now()
|
||||
`
|
||||
|
||||
type StoragePutParams struct {
|
||||
Owner string
|
||||
Key string
|
||||
Value []byte
|
||||
}
|
||||
|
||||
func (q *Queries) StoragePut(ctx context.Context, arg StoragePutParams) error {
|
||||
_, err := q.db.Exec(ctx, storagePut, arg.Owner, arg.Key, arg.Value)
|
||||
return err
|
||||
}
|
||||
@@ -23,6 +23,13 @@ type Agent struct {
|
||||
RegionID *uuid.UUID
|
||||
}
|
||||
|
||||
type AgentStorage struct {
|
||||
Owner string
|
||||
Key string
|
||||
Value []byte
|
||||
Modified time.Time
|
||||
}
|
||||
|
||||
type ApiToken struct {
|
||||
ID uuid.UUID
|
||||
OrgID uuid.UUID
|
||||
|
||||
@@ -147,6 +147,11 @@ type Querier interface {
|
||||
SetUserAdmin(ctx context.Context, arg SetUserAdminParams) (int64, error)
|
||||
SetUserLocale(ctx context.Context, arg SetUserLocaleParams) error
|
||||
StatusPageMonitors(ctx context.Context, pageID uuid.UUID) ([]StatusPageMonitorsRow, error)
|
||||
// Deletes key and, as certmagic expects, everything below it.
|
||||
StorageDelete(ctx context.Context, arg StorageDeleteParams) (int64, error)
|
||||
StorageGet(ctx context.Context, arg StorageGetParams) (StorageGetRow, error)
|
||||
StorageList(ctx context.Context, arg StorageListParams) ([]StorageListRow, error)
|
||||
StoragePut(ctx context.Context, arg StoragePutParams) error
|
||||
TouchAPIToken(ctx context.Context, id uuid.UUID) error
|
||||
TouchAgent(ctx context.Context, arg TouchAgentParams) error
|
||||
TouchIdentity(ctx context.Context, arg TouchIdentityParams) error
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
-- name: StorageGet :one
|
||||
SELECT value, modified FROM agent_storage WHERE owner = $1 AND key = $2;
|
||||
|
||||
-- name: StoragePut :exec
|
||||
INSERT INTO agent_storage (owner, key, value) VALUES ($1, $2, $3)
|
||||
ON CONFLICT (owner, key) DO UPDATE SET value = EXCLUDED.value, modified = now();
|
||||
|
||||
-- name: StorageDelete :execrows
|
||||
-- Deletes key and, as certmagic expects, everything below it.
|
||||
DELETE FROM agent_storage
|
||||
WHERE owner = sqlc.arg(owner) AND (key = sqlc.arg(key) OR starts_with(key, sqlc.arg(key)::text || '/'));
|
||||
|
||||
-- name: StorageList :many
|
||||
SELECT key, length(value)::bigint AS size, modified FROM agent_storage
|
||||
WHERE owner = sqlc.arg(owner) AND (sqlc.arg(prefix)::text = '' OR starts_with(key, sqlc.arg(prefix)::text || '/'))
|
||||
ORDER BY key;
|
||||
Reference in new issue
Block a user