feat: per-organization limits set by platform admins
Admins set default limits for monitors (all types), status pages and regions per monitor, whether an organization's own checker regions count towards the region limit, and how many organizations an account may own, and override them per organization or account. Defaults are not copied: changing one applies at once to everyone without an override. 0 means unlimited; self-hosted defaults are unlimited, the cloud allows three organizations per account. Creations count under a per-organization advisory lock, so concurrent requests cannot overshoot. A lowered limit keeps everything that exists: monitors already beyond the region limit stay editable but may not grow. Organizations see their usage in their settings and GET /org/limits; the admin panel lists organizations with owner, usage and limits next to their suspend and delete actions. Empty numeric form fields marked data-nullable are sent as null. Refs #111 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
90e74d091a
commit
e4ce619fbe
26 files changed
+2386
-82
No files matched your search
@@ -72,6 +72,9 @@ var endpoints = []endpoint{
|
||||
{method: "GET", path: "/api/v1/org/checkers/:id", tag: "Monitors", summary: "What a checker instance is doing",
|
||||
description: "Platform checkers serve every organization; other organizations' work appears only as a count.",
|
||||
resp: checkerActivity{}},
|
||||
{method: "GET", path: "/api/v1/org/limits", tag: "Organization", summary: "Limits in effect for the organization and its usage",
|
||||
description: "0 means unlimited. Creating beyond a limit gives 422 monitor_limit, status_page_limit, region_limit or platform_region_limit.",
|
||||
resp: usageView{}},
|
||||
{method: "GET", path: "/api/v1/org/check-types", tag: "Monitors", summary: "Monitor types this installation offers",
|
||||
resp: obj{"types": []string{}}},
|
||||
{method: "PUT", path: "/api/v1/org/check-types", tag: "Monitors", summary: "Choose the monitor types offered to members",
|
||||
@@ -241,6 +244,16 @@ var endpoints = []endpoint{
|
||||
{method: "PUT", path: "/api/v1/admin/checker-network", tag: "Platform", summary: "Let platform checkers check private addresses or not",
|
||||
description: "Unset, they may on self-hosted installations and may not in the cloud edition. Applies from each checker's next poll.",
|
||||
perm: "platform admin", req: checkerNetwork{}, status: http.StatusNoContent},
|
||||
{method: "GET", path: "/api/v1/admin/limits", tag: "Platform", summary: "Default limits of organizations and accounts", perm: "platform admin", resp: Limits{}},
|
||||
{method: "PUT", path: "/api/v1/admin/limits", tag: "Platform", summary: "Set the default limits",
|
||||
description: "0 means unlimited. Defaults apply at once to every organization and account without an override of its own. Lowering a limit below current usage keeps everything; only new monitors, status pages, regions or organizations are refused.",
|
||||
perm: "platform admin", req: limitsRequest{}, status: http.StatusNoContent},
|
||||
{method: "GET", path: "/api/v1/admin/orgs", tag: "Platform", summary: "Organizations with usage, limits and owner",
|
||||
description: "Newest first, at most 500. `q` searches name, slug and owner email.", perm: "platform admin", resp: obj{"orgs": []adminOrg{}}},
|
||||
{method: "PUT", path: "/api/v1/admin/orgs/:id/limits", tag: "Platform", summary: "Override an organization's limits",
|
||||
description: "null follows the platform default, 0 means unlimited.", perm: "platform admin", req: orgLimitsView{}, status: http.StatusNoContent},
|
||||
{method: "PUT", path: "/api/v1/admin/users/:id/limits", tag: "Platform", summary: "Override how many organizations an account may own",
|
||||
description: "null follows the platform default, 0 means unlimited.", perm: "platform admin", req: userLimitsRequest{}, status: http.StatusNoContent},
|
||||
{method: "GET", path: "/api/v1/admin/status-pages", tag: "Platform", summary: "Public and suspended status pages with organization and owner",
|
||||
description: "Newest first, at most 500. `q` searches title, slug, domain, organization and owner email.",
|
||||
perm: "platform admin", resp: obj{"status_pages": []moderatedPage{}}},
|
||||
|
||||
@@ -93,6 +93,9 @@ var auditActions = map[string]string{
|
||||
"PUT /api/v1/org/legal/:kind": "org.legal_update",
|
||||
"PUT /api/v1/admin/check-types": "platform.check_types_update",
|
||||
"PUT /api/v1/admin/checker-network": "platform.checker_network_update",
|
||||
"PUT /api/v1/admin/limits": "platform.limits_update",
|
||||
"PUT /api/v1/admin/orgs/:id/limits": "platform.org_limits_update",
|
||||
"PUT /api/v1/admin/users/:id/limits": "platform.user_limits_update",
|
||||
"PUT /api/v1/admin/status-pages/:id/suspension": "platform.status_page_suspension",
|
||||
"DELETE /api/v1/admin/status-pages/:id": "platform.status_page_delete",
|
||||
"PUT /api/v1/admin/orgs/:id/suspension": "platform.org_suspension",
|
||||
|
||||
@@ -0,0 +1,411 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/store"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/tenant"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/web"
|
||||
)
|
||||
|
||||
// Platform admins limit what organizations and accounts may create. The
|
||||
// platform defaults apply to every organization without an override of its
|
||||
// own, also after they change. 0 means unlimited.
|
||||
|
||||
const settingLimits = "limits"
|
||||
|
||||
// Limits are the limits in effect for an organization, or the platform
|
||||
// defaults.
|
||||
type Limits struct {
|
||||
Monitors int `json:"monitors"`
|
||||
StatusPages int `json:"status_pages"`
|
||||
RegionsPerMonitor int `json:"regions_per_monitor"`
|
||||
// OwnRegionsCount makes the organization's own checker regions count
|
||||
// towards RegionsPerMonitor; otherwise only platform regions do.
|
||||
OwnRegionsCount bool `json:"own_regions_count"`
|
||||
// OrgsPerAccount limits the organizations an account owns.
|
||||
OrgsPerAccount int `json:"orgs_per_account"`
|
||||
}
|
||||
|
||||
func (s *Server) defaultLimits() Limits {
|
||||
if s.cloud() {
|
||||
return Limits{OrgsPerAccount: 3}
|
||||
}
|
||||
return Limits{}
|
||||
}
|
||||
|
||||
// platformLimits returns the platform defaults.
|
||||
func (s *Server) platformLimits(ctx context.Context) Limits {
|
||||
l, err := s.limits.get(ctx, s.rdb, func(ctx context.Context) (Limits, error) {
|
||||
l := s.defaultLimits()
|
||||
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
|
||||
raw, err := q.GetPlatformSetting(ctx, settingLimits)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return json.Unmarshal(raw, &l)
|
||||
})
|
||||
return l, err
|
||||
})
|
||||
if err != nil {
|
||||
s.log.WarnContext(ctx, "loading limits failed", "error", err)
|
||||
return s.defaultLimits()
|
||||
}
|
||||
return l
|
||||
}
|
||||
|
||||
// orgLimits applies org's overrides to the platform defaults.
|
||||
func (s *Server) orgLimits(ctx context.Context, org store.Org) Limits {
|
||||
l := s.platformLimits(ctx)
|
||||
override := func(dst *int, v *int32) {
|
||||
if v != nil {
|
||||
*dst = int(*v)
|
||||
}
|
||||
}
|
||||
override(&l.Monitors, org.LimitMonitors)
|
||||
override(&l.StatusPages, org.LimitStatusPages)
|
||||
override(&l.RegionsPerMonitor, org.LimitRegionsPerMonitor)
|
||||
if org.LimitOwnRegionsCount != nil {
|
||||
l.OwnRegionsCount = *org.LimitOwnRegionsCount
|
||||
}
|
||||
return l
|
||||
}
|
||||
|
||||
// limitError reports a reached limit from inside a transaction.
|
||||
type limitError struct {
|
||||
code string
|
||||
max int
|
||||
}
|
||||
|
||||
func (e limitError) Error() string { return fmt.Sprintf("api: %s (%d)", e.code, e.max) }
|
||||
|
||||
// failLimit answers err if it is a limitError and reports whether it was.
|
||||
func failLimit(c *gin.Context, err error) bool {
|
||||
var le limitError
|
||||
if errors.As(err, &le) {
|
||||
fail(c, http.StatusUnprocessableEntity, le.code, "Max", le.max)
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// reserve locks org's usage and fails if count, from countFn, has reached
|
||||
// max.
|
||||
func reserve(ctx context.Context, q *store.Queries, org uuid.UUID, max int, code string, countFn func(context.Context, uuid.UUID) (int64, error)) error {
|
||||
if max == 0 {
|
||||
return nil
|
||||
}
|
||||
if err := q.LockOrgUsage(ctx, org); err != nil {
|
||||
return err
|
||||
}
|
||||
n, err := countFn(ctx, org)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if n >= int64(max) {
|
||||
return limitError{code, max}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// countedRegions counts the regions that count towards the limit.
|
||||
func countedRegions(l Limits, regions []uuid.UUID, platform map[uuid.UUID]bool) int {
|
||||
n := 0
|
||||
for _, r := range regions {
|
||||
if l.OwnRegionsCount || platform[r] {
|
||||
n++
|
||||
}
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
// checkRegions fails if a monitor would use more counted regions than
|
||||
// allowed. A monitor already beyond a lowered limit may keep its regions
|
||||
// but not add any.
|
||||
func checkRegions(l Limits, regions, previous []uuid.UUID, platform map[uuid.UUID]bool) error {
|
||||
n := countedRegions(l, regions, platform)
|
||||
if l.RegionsPerMonitor == 0 || n <= l.RegionsPerMonitor || n <= countedRegions(l, previous, platform) {
|
||||
return nil
|
||||
}
|
||||
if l.OwnRegionsCount {
|
||||
return limitError{"region_limit", l.RegionsPerMonitor}
|
||||
}
|
||||
return limitError{"platform_region_limit", l.RegionsPerMonitor}
|
||||
}
|
||||
|
||||
type usageView struct {
|
||||
Limits Limits `json:"limits"`
|
||||
Usage struct {
|
||||
Monitors int `json:"monitors"`
|
||||
StatusPages int `json:"status_pages"`
|
||||
} `json:"usage"`
|
||||
}
|
||||
|
||||
func (s *Server) orgUsage(ctx context.Context, p *principal) (usageView, error) {
|
||||
v := usageView{Limits: s.orgLimits(ctx, p.Org)}
|
||||
v.Limits.OrgsPerAccount = 0
|
||||
err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
|
||||
m, err := q.CountMonitors(ctx, p.Org.ID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
pg, err := q.CountStatusPages(ctx, p.Org.ID)
|
||||
v.Usage.Monitors, v.Usage.StatusPages = int(m), int(pg)
|
||||
return err
|
||||
})
|
||||
return v, err
|
||||
}
|
||||
|
||||
func (s *Server) getOrgLimits(c *gin.Context) {
|
||||
v, err := s.orgUsage(c.Request.Context(), current(c))
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, v)
|
||||
}
|
||||
|
||||
func (s *Server) adminGetLimits(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, s.platformLimits(c.Request.Context()))
|
||||
}
|
||||
|
||||
type limitsRequest struct {
|
||||
Monitors int `json:"monitors" binding:"min=0,max=1000000"`
|
||||
StatusPages int `json:"status_pages" binding:"min=0,max=1000000"`
|
||||
RegionsPerMonitor int `json:"regions_per_monitor" binding:"min=0,max=1000"`
|
||||
OwnRegionsCount bool `json:"own_regions_count"`
|
||||
OrgsPerAccount int `json:"orgs_per_account" binding:"min=0,max=100000"`
|
||||
}
|
||||
|
||||
func (s *Server) adminSetLimits(c *gin.Context) {
|
||||
var req limitsRequest
|
||||
if !bind(c, &req) {
|
||||
return
|
||||
}
|
||||
ctx := c.Request.Context()
|
||||
raw, _ := json.Marshal(Limits(req))
|
||||
auditDetail(c, "limits", Limits(req))
|
||||
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
|
||||
return q.SetPlatformSetting(ctx, store.SetPlatformSettingParams{Key: settingLimits, Value: raw})
|
||||
})
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
if err := s.limits.bump(ctx, s.rdb); err != nil {
|
||||
s.log.ErrorContext(ctx, "announcing limit change failed", "error", err)
|
||||
}
|
||||
c.Status(http.StatusNoContent)
|
||||
}
|
||||
|
||||
// optBool is a JSON boolean that may be null, and also accepts "true",
|
||||
// "false" and "" from forms.
|
||||
type optBool struct{ v *bool }
|
||||
|
||||
// UnmarshalJSON implements json.Unmarshaler.
|
||||
func (o *optBool) UnmarshalJSON(b []byte) error {
|
||||
switch strings.Trim(string(b), `"`) {
|
||||
case "null", "":
|
||||
o.v = nil
|
||||
case "true":
|
||||
t := true
|
||||
o.v = &t
|
||||
case "false":
|
||||
f := false
|
||||
o.v = &f
|
||||
default:
|
||||
return errors.New("not a boolean")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// MarshalJSON implements json.Marshaler.
|
||||
func (o optBool) MarshalJSON() ([]byte, error) { return json.Marshal(o.v) }
|
||||
|
||||
// orgLimitsRequest overrides limits for one organization; null follows the
|
||||
// platform default.
|
||||
type orgLimitsRequest struct {
|
||||
Monitors *int32 `json:"monitors" binding:"omitempty,min=0,max=1000000"`
|
||||
StatusPages *int32 `json:"status_pages" binding:"omitempty,min=0,max=1000000"`
|
||||
RegionsPerMonitor *int32 `json:"regions_per_monitor" binding:"omitempty,min=0,max=1000"`
|
||||
OwnRegionsCount optBool `json:"own_regions_count"`
|
||||
}
|
||||
|
||||
func (s *Server) adminSetOrgLimits(c *gin.Context) {
|
||||
id, err := uuid.Parse(c.Param("id"))
|
||||
if err != nil {
|
||||
fail(c, http.StatusNotFound, "not_found")
|
||||
return
|
||||
}
|
||||
var req orgLimitsRequest
|
||||
if !bind(c, &req) {
|
||||
return
|
||||
}
|
||||
ctx := c.Request.Context()
|
||||
auditDetail(c, "limits", req)
|
||||
err = s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
|
||||
row, err := q.SetOrgLimits(ctx, store.SetOrgLimitsParams{
|
||||
ID: id, Monitors: req.Monitors, StatusPages: req.StatusPages,
|
||||
RegionsPerMonitor: req.RegionsPerMonitor, OwnRegionsCount: req.OwnRegionsCount.v,
|
||||
})
|
||||
auditDetail(c, "slug", row.Slug)
|
||||
return err
|
||||
})
|
||||
if moderated(c, err) {
|
||||
c.Status(http.StatusNoContent)
|
||||
}
|
||||
}
|
||||
|
||||
type userLimitsRequest struct {
|
||||
// Orgs limits the organizations the account owns; null follows the
|
||||
// platform default.
|
||||
Orgs *int32 `json:"orgs" binding:"omitempty,min=0,max=100000"`
|
||||
}
|
||||
|
||||
func (s *Server) adminSetUserLimits(c *gin.Context) {
|
||||
id, err := uuid.Parse(c.Param("id"))
|
||||
if err != nil {
|
||||
fail(c, http.StatusNotFound, "not_found")
|
||||
return
|
||||
}
|
||||
var req userLimitsRequest
|
||||
if !bind(c, &req) {
|
||||
return
|
||||
}
|
||||
ctx := c.Request.Context()
|
||||
auditDetail(c, "orgs", req.Orgs)
|
||||
err = s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
|
||||
row, err := q.SetUserOrgLimit(ctx, store.SetUserOrgLimitParams{ID: id, Orgs: req.Orgs})
|
||||
auditDetail(c, "email", row.Email)
|
||||
return err
|
||||
})
|
||||
if moderated(c, err) {
|
||||
c.Status(http.StatusNoContent)
|
||||
}
|
||||
}
|
||||
|
||||
// adminOrg is an organization in the admin list.
|
||||
type adminOrg struct {
|
||||
moderatedOrg
|
||||
Created string `json:"created_at"`
|
||||
Overrides orgLimitsView `json:"overrides"`
|
||||
Limits Limits `json:"limits"`
|
||||
Usage struct {
|
||||
Monitors int `json:"monitors"`
|
||||
StatusPages int `json:"status_pages"`
|
||||
} `json:"usage"`
|
||||
Owner *adminOwner `json:"owner"`
|
||||
}
|
||||
|
||||
type orgLimitsView struct {
|
||||
Monitors *int32 `json:"monitors"`
|
||||
StatusPages *int32 `json:"status_pages"`
|
||||
RegionsPerMonitor *int32 `json:"regions_per_monitor"`
|
||||
OwnRegionsCount *bool `json:"own_regions_count"`
|
||||
}
|
||||
|
||||
type adminOwner struct {
|
||||
moderatedUser
|
||||
// OrgLimit overrides the organizations the account may own.
|
||||
OrgLimit *int32 `json:"org_limit"`
|
||||
Orgs int `json:"orgs"`
|
||||
}
|
||||
|
||||
func (s *Server) adminOrgs(ctx context.Context, search string) ([]adminOrg, error) {
|
||||
var rows []store.AdminListOrgsRow
|
||||
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
|
||||
var err error
|
||||
rows, err = q.AdminListOrgs(ctx, store.AdminListOrgsParams{
|
||||
Search: truncate(strings.TrimSpace(search), 200), MaxRows: moderationRows,
|
||||
})
|
||||
return err
|
||||
})
|
||||
defaults := s.platformLimits(ctx)
|
||||
out := make([]adminOrg, len(rows))
|
||||
for i, r := range rows {
|
||||
o := &out[i]
|
||||
o.moderatedOrg = moderatedOrg{r.ID, r.Slug, r.Name, r.SuspendedAt, r.SuspendedReason}
|
||||
o.Created = r.CreatedAt.Format("2006-01-02")
|
||||
o.Overrides = orgLimitsView{r.LimitMonitors, r.LimitStatusPages, r.LimitRegionsPerMonitor, r.LimitOwnRegionsCount}
|
||||
o.Limits = s.orgLimits(ctx, store.Org{LimitMonitors: r.LimitMonitors, LimitStatusPages: r.LimitStatusPages,
|
||||
LimitRegionsPerMonitor: r.LimitRegionsPerMonitor, LimitOwnRegionsCount: r.LimitOwnRegionsCount})
|
||||
o.Limits.OrgsPerAccount = defaults.OrgsPerAccount
|
||||
o.Usage.Monitors, o.Usage.StatusPages = int(r.Monitors), int(r.StatusPages)
|
||||
if r.OwnerID != uuid.Nil {
|
||||
o.Owner = &adminOwner{
|
||||
moderatedUser: moderatedUser{r.OwnerID, r.OwnerEmail, r.OwnerDisabledAt, r.OwnerDisabledReason, r.OwnerIsAdmin},
|
||||
OrgLimit: r.OwnerLimitOrgs, Orgs: int(r.OwnerOrgs),
|
||||
}
|
||||
if r.OwnerLimitOrgs != nil {
|
||||
o.Limits.OrgsPerAccount = int(*r.OwnerLimitOrgs)
|
||||
}
|
||||
}
|
||||
}
|
||||
return out, err
|
||||
}
|
||||
|
||||
func (s *Server) adminListOrgs(c *gin.Context) {
|
||||
orgs, err := s.adminOrgs(c.Request.Context(), c.Query("q"))
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"orgs": orgs})
|
||||
}
|
||||
|
||||
func webLimits(l Limits) web.LimitsView { return web.LimitsView(l) }
|
||||
|
||||
func optInt(v *int32) string {
|
||||
if v == nil {
|
||||
return ""
|
||||
}
|
||||
return strconv.Itoa(int(*v))
|
||||
}
|
||||
|
||||
func (s *Server) orgsView(c *gin.Context) (web.OrgsView, error) {
|
||||
ctx := c.Request.Context()
|
||||
// The admin page searches organizations with oq; q is the status page
|
||||
// search.
|
||||
orgs, err := s.adminOrgs(ctx, c.Query("oq"))
|
||||
v := web.OrgsView{Search: strings.TrimSpace(c.Query("oq")), Limited: len(orgs) == moderationRows, Defaults: webLimits(s.platformLimits(ctx))}
|
||||
state := func(at *time.Time, reason string) string {
|
||||
switch {
|
||||
case at == nil:
|
||||
return ""
|
||||
case reason == "":
|
||||
return "-"
|
||||
}
|
||||
return reason
|
||||
}
|
||||
for _, o := range orgs {
|
||||
row := web.OrgRow{
|
||||
ID: o.ID.String(), Name: o.Name, Slug: o.Slug, Created: o.Created, Suspended: state(o.SuspendedAt, o.Reason),
|
||||
Monitors: o.Usage.Monitors, StatusPages: o.Usage.StatusPages, Limits: webLimits(o.Limits),
|
||||
MonitorsOverride: optInt(o.Overrides.Monitors), StatusPagesOverride: optInt(o.Overrides.StatusPages),
|
||||
RegionsOverride: optInt(o.Overrides.RegionsPerMonitor),
|
||||
}
|
||||
if o.Overrides.OwnRegionsCount != nil {
|
||||
row.OwnRegionsOverride = strconv.FormatBool(*o.Overrides.OwnRegionsCount)
|
||||
}
|
||||
if o.Owner != nil {
|
||||
row.Owner = &web.ModeratedTarget{ID: o.Owner.ID.String(), Name: o.Owner.Email, Suspended: state(o.Owner.SuspendedAt, o.Owner.Reason), Admin: o.Owner.Admin}
|
||||
row.OwnerOrgs, row.OwnerOrgLimit = o.Owner.Orgs, optInt(o.Owner.OrgLimit)
|
||||
}
|
||||
v.Orgs = append(v.Orgs, row)
|
||||
}
|
||||
return v, err
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
package api_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/store"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/tenant"
|
||||
)
|
||||
|
||||
func TestLimits(t *testing.T) {
|
||||
e := newEnv(t)
|
||||
ctx := context.Background()
|
||||
reset := func() {
|
||||
_ = e.asSystem(t, func(tx pgx.Tx) error {
|
||||
_, err := tx.Exec(ctx, `DELETE FROM platform_settings WHERE key = 'limits'`)
|
||||
return err
|
||||
})
|
||||
}
|
||||
reset()
|
||||
t.Cleanup(reset)
|
||||
admin := e.browser(t)
|
||||
admin.signup("admin@"+uniq("lim")+".test", uniq("lim-admin-"))
|
||||
if err := tenant.New(e.dbPool).Tx(ctx, tenant.Global(), func(q *store.Queries) error {
|
||||
return q.MakeAdmin(ctx, admin.userIDSelf())
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
setDefaults := func(l map[string]any) {
|
||||
t.Helper()
|
||||
if st, body := admin.do("PUT", "/api/v1/admin/limits", l); st != http.StatusNoContent {
|
||||
t.Fatalf("set defaults = %d %v", st, body)
|
||||
}
|
||||
}
|
||||
setDefaults(map[string]any{"monitors": 2, "status_pages": 1, "regions_per_monitor": 1, "own_regions_count": false, "orgs_per_account": 3})
|
||||
|
||||
_, p1 := e.platformChecker(t, uniq("eu-"))
|
||||
_, p2 := e.platformChecker(t, uniq("us-"))
|
||||
owner := e.browser(t)
|
||||
orgSlug := uniq("lim-org-")
|
||||
owner.signup("o@"+uniq("lim")+".test", orgSlug)
|
||||
_, own := owner.do("POST", "/api/v1/org/regions", map[string]any{"key": uniq("office-"), "name": "Office"})
|
||||
o1 := own["id"].(string)
|
||||
monitor := func(regions ...string) (int, map[string]any) {
|
||||
return owner.do("POST", "/api/v1/org/monitors", map[string]any{
|
||||
"name": "m", "type": "tcp", "target": "example.com:443", "interval_seconds": 60, "regions": regions,
|
||||
})
|
||||
}
|
||||
|
||||
// Monitors, passive ones included.
|
||||
if st, body := owner.do("POST", "/api/v1/org/monitors", map[string]any{"name": "hb", "type": "heartbeat", "interval_seconds": 3600}); st != http.StatusCreated {
|
||||
t.Fatalf("heartbeat = %d %v", st, body)
|
||||
}
|
||||
if st, body := monitor(p1); st != http.StatusCreated {
|
||||
t.Fatalf("second monitor = %d %v", st, body)
|
||||
}
|
||||
st, body := monitor(p1)
|
||||
expect(t, "third monitor", st, body, http.StatusUnprocessableEntity, "monitor_limit")
|
||||
if !strings.Contains(body["message"].(string), "2") {
|
||||
t.Errorf("message lacks the limit: %v", body["message"])
|
||||
}
|
||||
_, usage := owner.do("GET", "/api/v1/org/limits", nil)
|
||||
if raw := mustJSON(usage); !strings.Contains(raw, `"monitors":2`) || !strings.Contains(raw, `"usage":{"monitors":2,"status_pages":0}`) {
|
||||
t.Errorf("org limits = %s", raw)
|
||||
}
|
||||
|
||||
// An override lifts the monitor limit; own regions do not count.
|
||||
_, orgs := admin.do("GET", "/api/v1/admin/orgs?q="+orgSlug, nil)
|
||||
org := orgs["orgs"].([]any)[0].(map[string]any)
|
||||
orgID := org["id"].(string)
|
||||
setOrg := func(l map[string]any) {
|
||||
t.Helper()
|
||||
if st, body := admin.do("PUT", "/api/v1/admin/orgs/"+orgID+"/limits", l); st != http.StatusNoContent {
|
||||
t.Fatalf("set org limits = %d %v", st, body)
|
||||
}
|
||||
}
|
||||
setOrg(map[string]any{"monitors": 10, "status_pages": nil, "regions_per_monitor": nil, "own_regions_count": nil})
|
||||
st, body = monitor(p1, p2)
|
||||
expect(t, "two platform regions", st, body, http.StatusUnprocessableEntity, "platform_region_limit")
|
||||
st, mixed := monitor(p1, o1)
|
||||
expect(t, "platform and own region", st, mixed, http.StatusCreated, "")
|
||||
|
||||
// Once own regions count, the existing monitor keeps both but may not
|
||||
// grow, and new ones are refused.
|
||||
setOrg(map[string]any{"monitors": 10, "own_regions_count": "true"})
|
||||
st, body = monitor(p1, o1)
|
||||
expect(t, "own region counted", st, body, http.StatusUnprocessableEntity, "region_limit")
|
||||
st, body = owner.do("PUT", "/api/v1/org/monitors/"+mixed["id"].(string), map[string]any{
|
||||
"name": "renamed", "type": "tcp", "target": "example.com:443", "interval_seconds": 60, "regions": []string{p1, o1},
|
||||
})
|
||||
expect(t, "edit a monitor beyond a lowered limit", st, body, http.StatusOK, "")
|
||||
st, body = owner.do("PUT", "/api/v1/org/monitors/"+mixed["id"].(string), map[string]any{
|
||||
"name": "renamed", "type": "tcp", "target": "example.com:443", "interval_seconds": 60, "regions": []string{p1, p2, o1},
|
||||
})
|
||||
expect(t, "grow a monitor beyond the limit", st, body, http.StatusUnprocessableEntity, "region_limit")
|
||||
|
||||
// Status pages; concurrent creations cannot overshoot.
|
||||
var wg sync.WaitGroup
|
||||
var mu sync.Mutex
|
||||
created := 0
|
||||
for range 5 {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
st, _ := owner.do("POST", "/api/v1/org/statuspages", map[string]any{"slug": uniq("p-"), "title": "x"})
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
if st == http.StatusCreated {
|
||||
created++
|
||||
}
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
if created != 1 {
|
||||
t.Errorf("%d status pages created under a limit of 1", created)
|
||||
}
|
||||
|
||||
// Defaults change for every organization without an override, at once.
|
||||
other := e.browser(t)
|
||||
other.signup("x@"+uniq("lim")+".test", uniq("lim-x-"))
|
||||
setDefaults(map[string]any{"monitors": 1})
|
||||
if st, _ := other.do("POST", "/api/v1/org/monitors", map[string]any{"name": "hb", "type": "heartbeat", "interval_seconds": 3600}); st != http.StatusCreated {
|
||||
t.Fatalf("first monitor = %d", st)
|
||||
}
|
||||
st, body = other.do("POST", "/api/v1/org/monitors", map[string]any{"name": "hb2", "type": "heartbeat", "interval_seconds": 3600})
|
||||
expect(t, "default lowered", st, body, http.StatusUnprocessableEntity, "monitor_limit")
|
||||
setDefaults(map[string]any{"monitors": 0})
|
||||
st, body = other.do("POST", "/api/v1/org/monitors", map[string]any{"name": "hb2", "type": "heartbeat", "interval_seconds": 3600})
|
||||
expect(t, "default unlimited", st, body, http.StatusCreated, "")
|
||||
|
||||
// Account limits and the admin list.
|
||||
ownerID := org["owner"].(map[string]any)["id"].(string)
|
||||
if st, body := admin.do("PUT", "/api/v1/admin/users/"+ownerID+"/limits", map[string]any{"orgs": 5}); st != http.StatusNoContent {
|
||||
t.Fatalf("set user limit = %d %v", st, body)
|
||||
}
|
||||
_, orgs = admin.do("GET", "/api/v1/admin/orgs?q="+orgSlug, nil)
|
||||
raw := mustJSON(orgs)
|
||||
for _, want := range []string{`"org_limit":5`, `"orgs":1`, `"monitors":10`, `"own_regions_count":true`, `"usage":{"monitors":3,"status_pages":1}`} {
|
||||
if !strings.Contains(raw, want) {
|
||||
t.Errorf("admin org list lacks %s: %s", want, raw)
|
||||
}
|
||||
}
|
||||
if st, _ := owner.do("GET", "/api/v1/admin/orgs", nil); st != http.StatusForbidden {
|
||||
t.Errorf("non-admin org list = %d", st)
|
||||
}
|
||||
if _, _, html := admin.page("/admin?oq=" + orgSlug); !strings.Contains(html, `id="orgs"`) || !strings.Contains(html, orgSlug) {
|
||||
t.Error("the admin page lacks the organization list")
|
||||
}
|
||||
if _, _, html := owner.page("/settings/org"); !strings.Contains(html, "3 / 10") {
|
||||
t.Error("the organization settings lack the usage")
|
||||
}
|
||||
}
|
||||
@@ -34,6 +34,9 @@ type monitorRequest struct {
|
||||
// Confirmations is how many failures in a row make a region count as
|
||||
// down; 0 keeps the default of 2.
|
||||
Confirmations int `json:"confirmations" binding:"min=0,max=10"`
|
||||
// platform marks the platform regions among those visible, filled by
|
||||
// validateMonitor.
|
||||
platform map[uuid.UUID]bool
|
||||
// GroupID places the monitor in a group; nil keeps it at the top level.
|
||||
GroupID *uuid.UUID `json:"group_id"`
|
||||
// AlertGroupIDs defaults on creation and preserves assignments on update
|
||||
@@ -169,6 +172,10 @@ func (s *Server) validateMonitor(c *gin.Context, req *monitorRequest, t groupTre
|
||||
internalError(c, err)
|
||||
return false
|
||||
}
|
||||
req.platform = map[uuid.UUID]bool{}
|
||||
for _, k := range known {
|
||||
req.platform[k.ID] = k.OrgID == nil
|
||||
}
|
||||
for _, r := range req.Regions {
|
||||
// Row-level security limits known to the org's own and the
|
||||
// platform regions.
|
||||
@@ -270,8 +277,15 @@ func (s *Server) createMonitor(c *gin.Context) {
|
||||
}
|
||||
req.Target = passiveTarget(check.Type(req.Type), req.Target)
|
||||
req.Config = s.sealMonitorConfig(check.Type(req.Type), req.Config, nil)
|
||||
limits := s.orgLimits(ctx, p.Org)
|
||||
if err := checkRegions(limits, req.Regions, nil, req.platform); failLimit(c, err) {
|
||||
return
|
||||
}
|
||||
var m store.Monitor
|
||||
err = s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
|
||||
if err := reserve(ctx, q, p.Org.ID, limits.Monitors, "monitor_limit", q.CountMonitors); err != nil {
|
||||
return err
|
||||
}
|
||||
var err error
|
||||
m, err = q.CreateMonitor(ctx, store.CreateMonitorParams{
|
||||
OrgID: p.Org.ID, Name: req.Name, Type: req.Type, Target: req.Target,
|
||||
@@ -295,6 +309,9 @@ func (s *Server) createMonitor(c *gin.Context) {
|
||||
fail(c, http.StatusUnprocessableEntity, "invalid_alert_group")
|
||||
return
|
||||
}
|
||||
if failLimit(c, err) {
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
@@ -380,6 +397,9 @@ func (s *Server) updateMonitor(c *gin.Context) {
|
||||
if old.Type != req.Type && !s.offered(ctx, p.Org, req.Type) {
|
||||
return errCheckTypeDisabled
|
||||
}
|
||||
if err := checkRegions(s.orgLimits(ctx, p.Org), req.Regions, previous, req.platform); err != nil {
|
||||
return err
|
||||
}
|
||||
if old.Type == req.Type {
|
||||
req.Config = s.sealMonitorConfig(check.Type(req.Type), req.Config, old.Config)
|
||||
} else {
|
||||
@@ -418,6 +438,9 @@ func (s *Server) updateMonitor(c *gin.Context) {
|
||||
fail(c, http.StatusUnprocessableEntity, "check_type_disabled")
|
||||
return
|
||||
}
|
||||
if failLimit(c, err) {
|
||||
return
|
||||
}
|
||||
if errors.Is(err, pgx.ErrNoRows) || (err == nil && denied) {
|
||||
fail(c, http.StatusNotFound, "not_found")
|
||||
return
|
||||
|
||||
+11
-1
@@ -283,6 +283,11 @@ func (s *Server) ssoSettingsView(c *gin.Context, p *principal, page web.Page, me
|
||||
|
||||
func (s *Server) orgSettingsView(c *gin.Context, p *principal, page web.Page, me web.Me) (templ.Component, error) {
|
||||
v := web.OrgSettings{RequireTOTP: p.Org.RequireTotp, RequireSSO: p.Org.RequireSso}
|
||||
u, err := s.orgUsage(c.Request.Context(), p)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
v.Usage = web.UsageView{Limits: webLimits(u.Limits), Monitors: u.Usage.Monitors, StatusPages: u.Usage.StatusPages}
|
||||
off := s.disabledChecks(c.Request.Context())
|
||||
for _, t := range check.Types {
|
||||
if !off[string(t)] {
|
||||
@@ -511,7 +516,12 @@ func (s *Server) adminPage(c *gin.Context) {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
web.Render(c, http.StatusOK, web.AdminPage(s.pageFor(c, "admin.title"), me, v, storageView(c, stats), types, s.platformPrivate(ctx), mod))
|
||||
orgs, err := s.orgsView(c)
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
web.Render(c, http.StatusOK, web.AdminPage(s.pageFor(c, "admin.title"), me, v, storageView(c, stats), types, s.platformPrivate(ctx), mod, orgs))
|
||||
}
|
||||
|
||||
func (s *Server) buildRegionsView(ctx context.Context, regions []store.Region, agents []store.ListAgentsRow, apiBase, next string, manageable func(store.Region) bool) (web.RegionsView, error) {
|
||||
|
||||
@@ -49,6 +49,8 @@ type Server struct {
|
||||
// checkerNet caches whether platform checkers may reach private
|
||||
// addresses.
|
||||
checkerNet *versioned[bool]
|
||||
// limits caches the platform's default limits.
|
||||
limits *versioned[Limits]
|
||||
}
|
||||
|
||||
// Deps are the external resources a Server needs.
|
||||
@@ -82,6 +84,7 @@ func New(cfg config.API, d Deps) *Server {
|
||||
legal: newVersioned[[]agentapi.LegalDoc]("legal"),
|
||||
checkTypes: newVersioned[map[string]bool]("check-types"),
|
||||
checkerNet: newVersioned[bool]("checker-network"),
|
||||
limits: newVersioned[Limits]("limits"),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -144,6 +147,7 @@ func (s *Server) Mount(r gin.IRouter) {
|
||||
org.DELETE("/alertmanager/receivers/:id", sessionOnly(), can(authz.OrgManage), s.deleteReceiver)
|
||||
org.GET("/alertmanager/alerts", can(authz.MonitorsRead), s.listFiringAlerts)
|
||||
org.GET("/check-types", s.orgCheckTypes)
|
||||
org.GET("/limits", s.getOrgLimits)
|
||||
org.PUT("/check-types", sessionOnly(), can(authz.OrgManage), s.orgSetCheckTypes)
|
||||
org.GET("/maintenance", s.listMaintenance)
|
||||
org.POST("/maintenance", s.createMaintenance)
|
||||
@@ -167,6 +171,11 @@ func (s *Server) Mount(r gin.IRouter) {
|
||||
admin.GET("/check-types", s.adminListCheckTypes)
|
||||
admin.PUT("/check-types", s.adminSetCheckTypes)
|
||||
admin.GET("/checker-network", s.adminGetCheckerNetwork)
|
||||
admin.GET("/limits", s.adminGetLimits)
|
||||
admin.PUT("/limits", s.adminSetLimits)
|
||||
admin.GET("/orgs", s.adminListOrgs)
|
||||
admin.PUT("/orgs/:id/limits", s.adminSetOrgLimits)
|
||||
admin.PUT("/users/:id/limits", s.adminSetUserLimits)
|
||||
admin.GET("/status-pages", s.adminListStatusPages)
|
||||
admin.PUT("/status-pages/:id/suspension", s.adminSuspendStatusPage)
|
||||
admin.DELETE("/status-pages/:id", s.adminDeleteStatusPage)
|
||||
|
||||
@@ -472,6 +472,9 @@ func (s *Server) createStatusPage(c *gin.Context) {
|
||||
theme, _ := json.Marshal(req.Theme)
|
||||
var row store.StatusPage
|
||||
err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
|
||||
if err := reserve(ctx, q, p.Org.ID, s.orgLimits(ctx, p.Org).StatusPages, "status_page_limit", q.CountStatusPages); err != nil {
|
||||
return err
|
||||
}
|
||||
var err error
|
||||
row, err = q.CreateStatusPage(ctx, store.CreateStatusPageParams{
|
||||
OrgID: p.Org.ID, Slug: req.Slug, Title: req.Title, Description: req.Description,
|
||||
@@ -480,6 +483,9 @@ func (s *Server) createStatusPage(c *gin.Context) {
|
||||
})
|
||||
return err
|
||||
})
|
||||
if failLimit(c, err) {
|
||||
return
|
||||
}
|
||||
if isUniqueViolation(err, "status_pages_slug_key") {
|
||||
fail(c, http.StatusConflict, "slug_taken")
|
||||
return
|
||||
|
||||
Reference in new issue
Block a user