feat(api): organization-owned regions, checkers and status page servers
Organizations create regions and agents for themselves under Regions & checkers; an org checker only receives its org's monitors. Platform admins manage shared regions and agents in the admin panel or with the CLI, which gains 'api admin grant|revoke'. The first user of a self-hosted installation becomes a platform admin. Region lists show the org's own regions first. Closes #52 Refs #29 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
607798d742
commit
22f0740056
19 files changed
+1932
-301
No files matched your search
@@ -0,0 +1,344 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/auth"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/store"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/tenant"
|
||||
)
|
||||
|
||||
var regionKeyRE = regexp.MustCompile(`^[a-z0-9][a-z0-9-]{0,39}$`)
|
||||
|
||||
type regionView struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
Key string `json:"key"`
|
||||
Name string `json:"name"`
|
||||
// Own is set for regions of the requesting org, false for platform
|
||||
// regions.
|
||||
Own bool `json:"own"`
|
||||
Instances int64 `json:"instances"`
|
||||
}
|
||||
|
||||
func (s *Server) viewRegions(ctx context.Context, rows []store.Region, org uuid.UUID) ([]regionView, error) {
|
||||
out := make([]regionView, len(rows))
|
||||
for i, r := range rows {
|
||||
n, err := s.sched.Instances(ctx, r.ID.String())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out[i] = regionView{ID: r.ID, Key: r.Key, Name: r.Name, Own: r.OrgID != nil && *r.OrgID == org, Instances: n}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// listOrgRegions returns the org's own regions first, then platform ones.
|
||||
func (s *Server) listOrgRegions(c *gin.Context) {
|
||||
p := current(c)
|
||||
ctx := c.Request.Context()
|
||||
var rows []store.Region
|
||||
err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
|
||||
var err error
|
||||
rows, err = q.ListVisibleRegions(ctx)
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
out, err := s.viewRegions(ctx, rows, p.Org.ID)
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"regions": out})
|
||||
}
|
||||
|
||||
type regionRequest struct {
|
||||
Key string `json:"key" binding:"required,max=40"`
|
||||
Name string `json:"name" binding:"max=100"`
|
||||
}
|
||||
|
||||
func (r *regionRequest) normalize() bool {
|
||||
r.Key = strings.ToLower(strings.TrimSpace(r.Key))
|
||||
r.Name = strings.TrimSpace(r.Name)
|
||||
if r.Name == "" {
|
||||
r.Name = r.Key
|
||||
}
|
||||
return regionKeyRE.MatchString(r.Key)
|
||||
}
|
||||
|
||||
func (s *Server) createRegion(c *gin.Context, scope tenant.Scope, org *uuid.UUID) {
|
||||
var req regionRequest
|
||||
if !bind(c, &req) {
|
||||
return
|
||||
}
|
||||
if !req.normalize() {
|
||||
fail(c, http.StatusUnprocessableEntity, "invalid_region_key")
|
||||
return
|
||||
}
|
||||
ctx := c.Request.Context()
|
||||
var row store.Region
|
||||
err := s.db.Tx(ctx, scope, func(q *store.Queries) error {
|
||||
var err error
|
||||
row, err = q.CreateRegion(ctx, store.CreateRegionParams{OrgID: org, Key: req.Key, Name: req.Name})
|
||||
return err
|
||||
})
|
||||
if isUniqueViolation(err, "regions_owner_key_key") {
|
||||
fail(c, http.StatusConflict, "region_key_taken")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusCreated, regionView{ID: row.ID, Key: row.Key, Name: row.Name, Own: org != nil})
|
||||
}
|
||||
|
||||
func (s *Server) deleteRegion(c *gin.Context, scope tenant.Scope) {
|
||||
id, err := uuid.Parse(c.Param("id"))
|
||||
if err != nil {
|
||||
fail(c, http.StatusNotFound, "not_found")
|
||||
return
|
||||
}
|
||||
ctx := c.Request.Context()
|
||||
var n int64
|
||||
err = s.db.Tx(ctx, scope, func(q *store.Queries) error {
|
||||
n, err = q.DeleteRegion(ctx, id)
|
||||
return err
|
||||
})
|
||||
if isForeignKeyViolation(err) {
|
||||
fail(c, http.StatusConflict, "region_in_use")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
if n == 0 {
|
||||
fail(c, http.StatusNotFound, "not_found")
|
||||
return
|
||||
}
|
||||
c.Status(http.StatusNoContent)
|
||||
}
|
||||
|
||||
func (s *Server) createOrgRegion(c *gin.Context) {
|
||||
p := current(c)
|
||||
s.createRegion(c, p.scope(), &p.Org.ID)
|
||||
}
|
||||
|
||||
// deleteOrgRegion can only reach the org's own regions: row-level security
|
||||
// hides platform regions from writes in an org scope.
|
||||
func (s *Server) deleteOrgRegion(c *gin.Context) { s.deleteRegion(c, current(c).scope()) }
|
||||
|
||||
type agentView struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
Kind string `json:"kind"`
|
||||
Name string `json:"name"`
|
||||
RegionID *uuid.UUID `json:"region_id,omitempty"`
|
||||
RegionKey string `json:"region_key,omitempty"`
|
||||
RegionName string `json:"region_name,omitempty"`
|
||||
Prefix string `json:"prefix"`
|
||||
LastSeenAt *time.Time `json:"last_seen_at"`
|
||||
Release string `json:"release,omitempty"`
|
||||
}
|
||||
|
||||
func (s *Server) listAgents(c *gin.Context, scope tenant.Scope, org *uuid.UUID) {
|
||||
ctx := c.Request.Context()
|
||||
var rows []store.ListAgentsRow
|
||||
err := s.db.Tx(ctx, scope, func(q *store.Queries) error {
|
||||
var err error
|
||||
rows, err = q.ListAgents(ctx, org)
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
out := make([]agentView, len(rows))
|
||||
for i, a := range rows {
|
||||
out[i] = agentView{
|
||||
ID: a.ID, Kind: a.Kind, Name: a.Name, RegionID: a.RegionID, RegionKey: deref(a.RegionKey),
|
||||
RegionName: deref(a.RegionName), Prefix: a.Prefix, LastSeenAt: a.LastSeenAt, Release: deref(a.Release),
|
||||
}
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"agents": out})
|
||||
}
|
||||
|
||||
type agentRequest struct {
|
||||
Kind string `json:"kind" binding:"required,oneof=checker statuspage"`
|
||||
Name string `json:"name" binding:"required,max=100"`
|
||||
RegionID *uuid.UUID `json:"region_id"`
|
||||
}
|
||||
|
||||
// createAgent creates an agent and returns its token, which is shown once.
|
||||
func (s *Server) createAgent(c *gin.Context, scope tenant.Scope, org *uuid.UUID) {
|
||||
var req agentRequest
|
||||
if !bind(c, &req) {
|
||||
return
|
||||
}
|
||||
req.Name = strings.TrimSpace(req.Name)
|
||||
if req.Name == "" || (req.Kind == "checker") != (req.RegionID != nil) {
|
||||
fail(c, http.StatusUnprocessableEntity, "invalid_input")
|
||||
return
|
||||
}
|
||||
tok, params := NewAgentToken(org, req.Kind, req.Name, req.RegionID)
|
||||
ctx := c.Request.Context()
|
||||
var row store.Agent
|
||||
err := s.db.Tx(ctx, scope, func(q *store.Queries) error {
|
||||
var err error
|
||||
row, err = q.CreateAgent(ctx, params)
|
||||
return err
|
||||
})
|
||||
// The trigger rejects regions of another owner, and the foreign key
|
||||
// unknown regions; both look the same to the caller.
|
||||
if isCheckViolation(err) || isForeignKeyViolation(err) {
|
||||
fail(c, http.StatusUnprocessableEntity, "invalid_region")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusCreated, gin.H{"id": row.ID, "token": tok})
|
||||
}
|
||||
|
||||
// NewAgentToken returns a fresh agent token and the row storing its hash.
|
||||
func NewAgentToken(org *uuid.UUID, kind, name string, region *uuid.UUID) (string, store.CreateAgentParams) {
|
||||
tok := AgentTokenPrefix + auth.RandomToken()
|
||||
return tok, store.CreateAgentParams{
|
||||
OrgID: org, Kind: kind, Name: name, RegionID: region,
|
||||
TokenHash: HashToken(tok), Prefix: tok[:len(AgentTokenPrefix)+6],
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) deleteAgent(c *gin.Context, scope tenant.Scope, org *uuid.UUID) {
|
||||
id, err := uuid.Parse(c.Param("id"))
|
||||
if err != nil {
|
||||
fail(c, http.StatusNotFound, "not_found")
|
||||
return
|
||||
}
|
||||
ctx := c.Request.Context()
|
||||
var n int64
|
||||
err = s.db.Tx(ctx, scope, func(q *store.Queries) error {
|
||||
n, err = q.DeleteAgent(ctx, store.DeleteAgentParams{ID: id, OrgID: org})
|
||||
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) listOrgAgents(c *gin.Context) {
|
||||
p := current(c)
|
||||
s.listAgents(c, p.scope(), &p.Org.ID)
|
||||
}
|
||||
|
||||
func (s *Server) createOrgAgent(c *gin.Context) {
|
||||
p := current(c)
|
||||
s.createAgent(c, p.scope(), &p.Org.ID)
|
||||
}
|
||||
|
||||
func (s *Server) deleteOrgAgent(c *gin.Context) {
|
||||
p := current(c)
|
||||
s.deleteAgent(c, p.scope(), &p.Org.ID)
|
||||
}
|
||||
|
||||
// requireAdmin admits signed-in platform admins. Admin actions affect every
|
||||
// organization and run in the system scope.
|
||||
func (s *Server) requireAdmin() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
sess := auth.Current(c)
|
||||
if sess == nil {
|
||||
fail(c, http.StatusUnauthorized, "unauthenticated")
|
||||
return
|
||||
}
|
||||
ctx := c.Request.Context()
|
||||
var u store.User
|
||||
err := s.db.Tx(ctx, tenant.Global(), func(q *store.Queries) error {
|
||||
var err error
|
||||
u, err = q.GetUser(ctx, sess.UserID)
|
||||
return err
|
||||
})
|
||||
if errors.Is(err, pgx.ErrNoRows) || (err == nil && !u.IsAdmin) {
|
||||
fail(c, http.StatusForbidden, "forbidden")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) adminListRegions(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
var rows []store.Region
|
||||
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
|
||||
var err error
|
||||
rows, err = q.ListPlatformRegions(ctx)
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
out, err := s.viewRegions(ctx, rows, uuid.Nil)
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"regions": out})
|
||||
}
|
||||
|
||||
func (s *Server) adminCreateRegion(c *gin.Context) { s.createRegion(c, tenant.System(), nil) }
|
||||
|
||||
func (s *Server) adminDeleteRegion(c *gin.Context) {
|
||||
// The system scope could reach org regions; only platform ones are meant.
|
||||
id, err := uuid.Parse(c.Param("id"))
|
||||
if err != nil {
|
||||
fail(c, http.StatusNotFound, "not_found")
|
||||
return
|
||||
}
|
||||
ctx := c.Request.Context()
|
||||
var r store.Region
|
||||
err = s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
|
||||
r, err = q.GetRegion(ctx, id)
|
||||
return err
|
||||
})
|
||||
if errors.Is(err, pgx.ErrNoRows) || (err == nil && r.OrgID != nil) {
|
||||
fail(c, http.StatusNotFound, "not_found")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
s.deleteRegion(c, tenant.System())
|
||||
}
|
||||
|
||||
func (s *Server) adminListAgents(c *gin.Context) { s.listAgents(c, tenant.System(), nil) }
|
||||
func (s *Server) adminCreateAgent(c *gin.Context) { s.createAgent(c, tenant.System(), nil) }
|
||||
func (s *Server) adminDeleteAgent(c *gin.Context) { s.deleteAgent(c, tenant.System(), nil) }
|
||||
|
||||
func isForeignKeyViolation(err error) bool {
|
||||
var pgErr *pgconn.PgError
|
||||
return errors.As(err, &pgErr) && pgErr.Code == "23503"
|
||||
}
|
||||
Reference in new issue
Block a user