Files
uptimesebi/internal/api/server.go
T
Sebastian UnterschützandClaude Opus 5.5 e4ce619fbe
ci / image (pull_request) Successful in 4m25s
ci / build (pull_request) Successful in 8m15s
ci / test (pull_request) Successful in 8m51s
ci / lint (pull_request) Successful in 12m8s
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
2026-11-22 21:06:45 +01:00

361 lines
14 KiB
Go

// Package api serves the management JSON API under /api/v1 and the
// server-rendered console pages that call it.
package api
import (
"errors"
"log/slog"
"net/http"
"github.com/gin-gonic/gin"
"github.com/go-playground/validator/v10"
"github.com/redis/go-redis/v9"
"git.zb-server.de/ZB-Server/uptimesebi/internal/agentapi"
"git.zb-server.de/ZB-Server/uptimesebi/internal/auth"
"git.zb-server.de/ZB-Server/uptimesebi/internal/authz"
"git.zb-server.de/ZB-Server/uptimesebi/internal/config"
"git.zb-server.de/ZB-Server/uptimesebi/internal/evaluate"
"git.zb-server.de/ZB-Server/uptimesebi/internal/i18n"
"git.zb-server.de/ZB-Server/uptimesebi/internal/notify"
"git.zb-server.de/ZB-Server/uptimesebi/internal/requestid"
"git.zb-server.de/ZB-Server/uptimesebi/internal/schedule"
"git.zb-server.de/ZB-Server/uptimesebi/internal/sealed"
"git.zb-server.de/ZB-Server/uptimesebi/internal/sso"
"git.zb-server.de/ZB-Server/uptimesebi/internal/store"
"git.zb-server.de/ZB-Server/uptimesebi/internal/tenant"
)
const localeCookie = "lang"
// Server holds the dependencies shared by all handlers.
type Server struct {
cfg config.API
log *slog.Logger
db *tenant.DB
rdb redis.UniversalClient
keys *sealed.Keyring
catalog *i18n.Catalog
sessions *auth.Sessions
limiter *auth.Limiter
totp *auth.TOTPVerifier
sso *sso.Client
sched *schedule.Scheduler
eval *evaluate.Evaluator
smtp *notify.SMTP
legal *versioned[[]agentapi.LegalDoc]
// checkTypes caches the check types switched off platform-wide.
checkTypes *versioned[map[string]bool]
// 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.
type Deps struct {
Log *slog.Logger
DB *tenant.DB
Redis redis.UniversalClient
Keys *sealed.Keyring
Catalog *i18n.Catalog
}
// New returns a Server. It does not register any routes; see Mount.
// cfg must have passed Validate.
func New(cfg config.API, d Deps) *Server {
allowPrivate := cfg.SSOAllowPrivate()
mail, _ := notify.ParseSMTP(cfg.SMTPURL)
return &Server{
eval: evaluate.New(d.Redis),
smtp: mail,
cfg: cfg,
log: d.Log,
db: d.DB,
rdb: d.Redis,
keys: d.Keys,
catalog: d.Catalog,
sessions: auth.NewSessions(d.Redis, cfg.SessionIdle, cfg.SessionAbsolute),
limiter: auth.NewLimiter(d.Redis),
totp: auth.NewTOTPVerifier(d.Redis),
sso: sso.New(sso.SafeHTTPClient(allowPrivate), cfg.PublicURL+"/sso/callback", allowPrivate),
sched: schedule.New(d.Redis),
legal: newVersioned[[]agentapi.LegalDoc]("legal"),
checkTypes: newVersioned[map[string]bool]("check-types"),
checkerNet: newVersioned[bool]("checker-network"),
limits: newVersioned[Limits]("limits"),
}
}
// Mount installs session loading, locale resolution and CSRF protection and
// registers the JSON API and the console pages below them.
func (s *Server) Mount(r gin.IRouter) {
// Agents authenticate with tokens and never carry cookies, so they skip
// the session and CSRF middleware.
s.mountAgentAPI(r)
s.mountHeartbeats(r)
s.mountAlertmanager(r)
g := r.Group("/", s.sessions.Load(), s.localize(), auth.CSRF(), s.audit())
r.GET("/api/openapi.json", s.openAPIJSON)
g.GET("/api/docs", s.apiDocsPage)
v1 := g.Group("/api/v1")
v1.POST("/locale", s.setLocale)
v1.POST("/markdown/preview", auth.Require(), s.previewMarkdown)
a := v1.Group("/auth")
a.POST("/signup", s.signup)
a.POST("/login", s.login)
a.POST("/login/totp", s.loginTOTP)
a.POST("/logout", s.logout)
me := v1.Group("/me", auth.Require())
me.GET("", s.me)
me.POST("/org", s.switchOrg)
me.POST("/totp/setup", s.totpSetup)
me.POST("/totp/enable", s.totpEnable)
me.POST("/totp/disable", s.totpDisable)
me.POST("/totp/recovery-codes", s.regenerateRecoveryCodes)
me.GET("/audit", s.listMyAudit)
me.GET("/export", s.exportAccount)
me.POST("/delete", s.deleteAccount)
v1.POST("/invitations/:token/accept", auth.Require(), s.acceptInvitation)
v1.POST("/invitations/:token/signup", s.inviteSignup)
org := v1.Group("/org", s.orgAccess())
org.PUT("/policy", sessionOnly(), can(authz.OrgManage), s.updatePolicy)
org.GET("/export", sessionOnly(), can(authz.OrgManage), s.exportOrg)
org.GET("/legal", can(authz.OrgManage), s.orgListLegal)
org.PUT("/legal/:kind", can(authz.OrgManage), s.orgSaveLegal)
org.POST("/delete", sessionOnly(), s.deleteOrg)
// Monitor and group handlers check permissions themselves: assignments
// scoped to a group grant access below that group only.
org.GET("/monitors", s.listMonitors)
org.POST("/monitors", s.createMonitor)
org.PUT("/monitors/:id", s.updateMonitor)
org.DELETE("/monitors/:id", s.deleteMonitor)
org.GET("/monitors/:id/evidence", s.listEvidence)
org.GET("/checkers/:id", s.getChecker)
org.GET("/monitors/:id/evidence/:evidence", s.getEvidence)
org.GET("/alertmanager/receivers", can(authz.OrgManage), s.listReceivers)
org.POST("/alertmanager/receivers", sessionOnly(), can(authz.OrgManage), s.createReceiver)
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)
org.PUT("/maintenance/:id", s.updateMaintenance)
org.DELETE("/maintenance/:id", s.deleteMaintenance)
org.GET("/groups", s.listGroups)
org.POST("/groups", s.createGroup)
org.PUT("/groups/:id", s.updateGroup)
org.DELETE("/groups/:id", s.deleteGroup)
org.GET("/regions", s.listOrgRegions)
org.POST("/regions", sessionOnly(), can(authz.OrgManage), s.createOrgRegion)
org.DELETE("/regions/:id", sessionOnly(), can(authz.OrgManage), s.deleteOrgRegion)
org.GET("/agents", can(authz.OrgManage), s.listOrgAgents)
org.POST("/agents", sessionOnly(), can(authz.OrgManage), s.createOrgAgent)
org.PATCH("/agents/:id", sessionOnly(), can(authz.OrgManage), s.updateOrgAgent)
org.DELETE("/agents/:id", sessionOnly(), can(authz.OrgManage), s.deleteOrgAgent)
admin := v1.Group("/admin", s.requireAdmin())
admin.GET("/audit", s.listPlatformAudit)
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)
admin.PUT("/orgs/:id/suspension", s.adminSuspendOrg)
admin.DELETE("/orgs/:id", s.adminDeleteOrg)
admin.PUT("/users/:id/suspension", s.adminSuspendUser)
admin.DELETE("/users/:id", s.adminDeleteUser)
admin.PUT("/checker-network", s.adminSetCheckerNetwork)
admin.GET("/legal", s.adminListLegal)
admin.PUT("/legal/:kind", s.adminSaveLegal)
admin.GET("/regions", s.adminListRegions)
admin.POST("/regions", s.adminCreateRegion)
admin.DELETE("/regions/:id", s.adminDeleteRegion)
admin.GET("/agents", s.adminListAgents)
admin.POST("/agents", s.adminCreateAgent)
admin.DELETE("/agents/:id", s.adminDeleteAgent)
org.GET("/statuspages", s.listStatusPages)
org.POST("/statuspages", can(authz.StatusPagesWrite), s.createStatusPage)
page := org.Group("/statuspages/:id")
page.PUT("", canPage(authz.StatusPagesWrite), s.updateStatusPage)
page.DELETE("", canPage(authz.StatusPagesWrite), s.deleteStatusPage)
page.GET("/groups", canPage(authz.StatusPagesRead), s.listStatusPageGroups)
page.POST("/groups", canPage(authz.StatusPagesWrite), s.createStatusPageGroup)
page.PUT("/groups/:group_id", canPage(authz.StatusPagesWrite), s.updateStatusPageGroup)
page.DELETE("/groups/:group_id", canPage(authz.StatusPagesWrite), s.deleteStatusPageGroup)
page.POST("/groups/import", canPage(authz.StatusPagesWrite), s.importStatusPageGroups)
page.PUT("/monitors", canPage(authz.StatusPagesWrite), s.setPageMonitors)
page.PUT("/domain", canPage(authz.StatusPagesWrite), s.setPageDomain)
page.POST("/domain/verify", canPage(authz.StatusPagesWrite), s.verifyPageDomain)
page.GET("/export", canPage(authz.StatusPagesRead), s.exportStatusPage)
org.GET("/incidents", can(authz.IncidentsRead), s.listIncidents)
org.GET("/audit", can(authz.AuditRead), s.listOrgAudit)
org.GET("/alert-groups", can(authz.NotificationsRead), s.listAlertGroups)
org.POST("/alert-groups", can(authz.NotificationsWrite), s.saveAlertGroup)
org.PUT("/alert-groups/:id", can(authz.NotificationsWrite), s.saveAlertGroup)
org.DELETE("/alert-groups/:id", can(authz.NotificationsWrite), s.deleteAlertGroup)
org.GET("/channels", can(authz.NotificationsRead), s.listChannels)
org.POST("/channels", can(authz.NotificationsWrite), s.createChannel)
org.PUT("/channels/:id", can(authz.NotificationsWrite), s.updateChannel)
org.DELETE("/channels/:id", can(authz.NotificationsWrite), s.deleteChannel)
org.POST("/channels/:id/test", can(authz.NotificationsWrite), s.testChannel)
org.GET("/sso", can(authz.OrgManage), s.listSSOProviders)
org.POST("/sso", sessionOnly(), can(authz.OrgManage), s.createSSOProvider)
org.PUT("/sso/:id", sessionOnly(), can(authz.OrgManage), s.updateSSOProvider)
org.DELETE("/sso/:id", sessionOnly(), can(authz.OrgManage), s.deleteSSOProvider)
org.GET("/members", can(authz.MembersRead), s.listMembers)
org.DELETE("/members/:user", sessionOnly(), can(authz.MembersManage), s.removeMember)
org.POST("/members/:user/roles", sessionOnly(), can(authz.MembersManage), s.assignRole)
org.DELETE("/assignments/:id", sessionOnly(), can(authz.MembersManage), s.unassignRole)
org.GET("/invitations", can(authz.MembersRead), s.listInvitations)
org.POST("/invitations", sessionOnly(), can(authz.MembersManage), s.createInvitation)
org.DELETE("/invitations/:id", sessionOnly(), can(authz.MembersManage), s.deleteInvitation)
org.GET("/roles", can(authz.MembersRead), s.listRoles)
org.POST("/roles", sessionOnly(), can(authz.RolesManage), s.createRole)
org.PUT("/roles/:id", sessionOnly(), can(authz.RolesManage), s.updateRole)
org.DELETE("/roles/:id", sessionOnly(), can(authz.RolesManage), s.deleteRole)
// Every member may hold personal tokens; their rights are capped by the
// member's own.
org.GET("/tokens", s.listTokens)
org.POST("/tokens", sessionOnly(), s.createToken)
org.DELETE("/tokens/:id", s.deleteToken)
g.GET("/sso", s.ssoLookup)
g.GET("/sso/callback", s.ssoCallback)
g.GET("/sso/:slug", s.ssoChoose)
g.GET("/sso/:slug/:provider", s.ssoStartProvider)
s.registerPages(g)
}
// localize resolves the language from, in order: the signed-in user's
// setting, the lang cookie, and Accept-Language.
func (s *Server) localize() gin.HandlerFunc {
return func(c *gin.Context) {
var pref string
if sess := auth.Current(c); sess != nil {
pref = sess.Locale
}
cookie, _ := c.Cookie(localeCookie)
l := s.catalog.Match(pref, cookie, c.GetHeader("Accept-Language"))
c.Request = c.Request.WithContext(i18n.NewContext(c.Request.Context(), l))
c.Header("Content-Language", l.Lang())
c.Header("Vary", "Accept-Language, Cookie")
c.Next()
}
}
type localeRequest struct {
Locale string `json:"locale" binding:"required,max=10"`
}
func (s *Server) setLocale(c *gin.Context) {
var req localeRequest
if !bind(c, &req) {
return
}
if !s.catalog.IsSupported(req.Locale) {
fail(c, http.StatusUnprocessableEntity, "unsupported_locale")
return
}
ctx := c.Request.Context()
if sess := auth.Current(c); sess != nil {
err := s.db.Tx(ctx, tenant.User(sess.UserID), func(q *store.Queries) error {
return q.SetUserLocale(ctx, store.SetUserLocaleParams{ID: sess.UserID, Locale: &req.Locale})
})
if err == nil {
err = s.sessions.SetLocale(ctx, sess, req.Locale)
}
if err != nil {
internalError(c, err)
return
}
}
setCookie(c, localeCookie, req.Locale, 365*24*3600)
c.Status(http.StatusNoContent)
}
type apiError struct {
Error string `json:"error"`
Message string `json:"message"`
Fields map[string]string `json:"fields,omitempty"`
RequestID string `json:"request_id,omitempty"`
}
// fail aborts with a machine-readable code and a message translated from
// the catalog entry "error.<code>". kv fills placeholders in that message.
func fail(c *gin.Context, status int, code string, kv ...any) {
ctx := c.Request.Context()
c.AbortWithStatusJSON(status, apiError{
Error: code,
Message: i18n.T(ctx, "error."+code, kv...),
RequestID: requestid.FromContext(ctx),
})
}
func internalError(c *gin.Context, err error) {
_ = c.Error(err)
fail(c, http.StatusInternalServerError, "internal")
}
func bind(c *gin.Context, dst any) bool {
err := c.ShouldBindJSON(dst)
if err == nil {
return true
}
ctx := c.Request.Context()
e := apiError{Error: "invalid_input", Message: i18n.T(ctx, "error.invalid_input"), RequestID: requestid.FromContext(ctx)}
var ve validator.ValidationErrors
if errors.As(err, &ve) {
e.Fields = map[string]string{}
for _, f := range ve {
e.Fields[f.Field()] = f.Tag()
}
}
c.AbortWithStatusJSON(http.StatusBadRequest, e)
return false
}
func setCookie(c *gin.Context, name, value string, maxAge int) {
http.SetCookie(c.Writer, &http.Cookie{
Name: name, Value: value, Path: "/", MaxAge: maxAge,
Secure: true, HttpOnly: true, SameSite: http.SameSiteLaxMode,
})
}
func ptr[T any](v T) *T { return &v }
func deref[T any](p *T) T {
var zero T
if p == nil {
return zero
}
return *p
}