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"` // Latitude and longitude place the region on the map; both are absent // for regions without a location. Latitude *float64 `json:"latitude,omitempty"` Longitude *float64 `json:"longitude,omitempty"` } func newRegionView(r store.Region, org uuid.UUID, instances int64) regionView { return regionView{ID: r.ID, Key: r.Key, Name: r.Name, Own: r.OrgID != nil && *r.OrgID == org, Instances: instances, Latitude: r.Latitude, Longitude: r.Longitude} } 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] = newRegionView(r, org, 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"` regionLocation } 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) } // regionLocation is where a region's checkers stand; null for both // coordinates means no location. type regionLocation struct { Latitude *float64 `json:"latitude"` Longitude *float64 `json:"longitude"` } func (l regionLocation) valid() bool { if l.Latitude == nil || l.Longitude == nil { return l.Latitude == nil && l.Longitude == nil } return *l.Latitude >= -90 && *l.Latitude <= 90 && *l.Longitude >= -180 && *l.Longitude <= 180 } 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 } if !req.valid() { fail(c, http.StatusUnprocessableEntity, "invalid_location") 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, Latitude: req.Latitude, Longitude: req.Longitude}) return err }) if isUniqueViolation(err, "regions_owner_key_key") { fail(c, http.StatusConflict, "region_key_taken") return } if err != nil { internalError(c, err) return } v := newRegionView(row, uuid.Nil, 0) v.Own = org != nil c.JSON(http.StatusCreated, v) } // updateRegion sets or removes a region's location. func (s *Server) updateRegion(c *gin.Context, scope tenant.Scope) { id, err := uuid.Parse(c.Param("id")) if err != nil { fail(c, http.StatusNotFound, "not_found") return } var req regionLocation if !bind(c, &req) { return } if !req.valid() { fail(c, http.StatusUnprocessableEntity, "invalid_location") return } ctx := c.Request.Context() var n int64 err = s.db.Tx(ctx, scope, func(q *store.Queries) error { n, err = q.UpdateRegionLocation(ctx, store.UpdateRegionLocationParams{ID: id, Latitude: req.Latitude, Longitude: req.Longitude}) 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) 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()) } // updateOrgRegion, like deleteOrgRegion, reaches the org's own regions only. func (s *Server) updateOrgRegion(c *gin.Context) { s.updateRegion(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"` // AllowPrivate tells whether an organization's checker may check // private addresses; platform checkers follow the platform setting. AllowPrivate *bool `json:"allow_private,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), } if a.Kind == "checker" && a.OrgID != nil { out[i].AllowPrivate = &a.AllowPrivate } } 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"` // AllowPrivate lets an organization's checker check private // addresses; it defaults to true. AllowPrivate *bool `json:"allow_private"` } // 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) if req.AllowPrivate != nil && org != nil { params.AllowPrivate = *req.AllowPrivate } 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], AllowPrivate: true, } } 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) { if s.platformRegion(c) { s.deleteRegion(c, tenant.System()) } } func (s *Server) adminUpdateRegion(c *gin.Context) { if s.platformRegion(c) { s.updateRegion(c, tenant.System()) } } // platformRegion reports whether the region in the path is a platform one, // answering the request otherwise: the system scope could reach org // regions, but only platform ones are meant. func (s *Server) platformRegion(c *gin.Context) bool { id, err := uuid.Parse(c.Param("id")) if err != nil { fail(c, http.StatusNotFound, "not_found") return false } 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 false } if err != nil { internalError(c, err) return false } return true } 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" }