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
+21
-9
@@ -58,7 +58,7 @@ func (s *Server) agentAuth() gin.HandlerFunc {
|
||||
return
|
||||
}
|
||||
ctx := c.Request.Context()
|
||||
var a store.Agent
|
||||
var a store.GetAgentByHashRow
|
||||
release := truncate(c.GetHeader(agentapi.ReleaseHeader), 64)
|
||||
err = s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
|
||||
var err error
|
||||
@@ -91,11 +91,21 @@ func requireAgentKind(kind string) gin.HandlerFunc {
|
||||
}
|
||||
}
|
||||
|
||||
func agentOf(c *gin.Context) store.Agent { return c.MustGet(ctxAgent).(store.Agent) }
|
||||
func agentOf(c *gin.Context) store.GetAgentByHashRow {
|
||||
return c.MustGet(ctxAgent).(store.GetAgentByHashRow)
|
||||
}
|
||||
func instanceOf(c *gin.Context) uuid.UUID { return c.MustGet(ctxInstance).(uuid.UUID) }
|
||||
func regionOf(c *gin.Context) string { return deref(agentOf(c).Region) }
|
||||
func (s *Server) cloud() bool { return s.cfg.Edition == config.EditionCloud }
|
||||
func (s *Server) allowPrivate(a store.Agent) bool {
|
||||
|
||||
// regionOf returns the agent's region ID in the string form used for the
|
||||
// schedule and check results.
|
||||
func regionOf(c *gin.Context) string {
|
||||
if id := agentOf(c).RegionID; id != nil {
|
||||
return id.String()
|
||||
}
|
||||
return ""
|
||||
}
|
||||
func (s *Server) cloud() bool { return s.cfg.Edition == config.EditionCloud }
|
||||
func (s *Server) allowPrivate(a store.GetAgentByHashRow) bool {
|
||||
// Operator checkers in the cloud share our network; customers must not
|
||||
// reach it through them. Customer-run checkers and self-hosted
|
||||
// installations check whatever their operator can reach.
|
||||
@@ -105,7 +115,8 @@ func (s *Server) allowPrivate(a store.Agent) bool {
|
||||
func (s *Server) agentHello(c *gin.Context) {
|
||||
a := agentOf(c)
|
||||
c.JSON(http.StatusOK, agentapi.Hello{
|
||||
AgentID: a.ID, Name: a.Name, Kind: a.Kind, Region: deref(a.Region), Protocol: agentapi.Version,
|
||||
AgentID: a.ID, Name: a.Name, Kind: a.Kind, Region: deref(a.RegionKey), RegionID: a.RegionID,
|
||||
RegionName: deref(a.RegionName), OrgOwned: a.OrgID != nil, Protocol: agentapi.Version,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -136,7 +147,7 @@ func (s *Server) agentJobs(c *gin.Context) {
|
||||
|
||||
// resolveJobs attaches the current monitor settings to dispatched runs.
|
||||
// Checking is cross-tenant work, hence the system scope.
|
||||
func (s *Server) resolveJobs(ctx context.Context, a store.Agent, entries []schedule.Entry) ([]agentapi.Job, error) {
|
||||
func (s *Server) resolveJobs(ctx context.Context, a store.GetAgentByHashRow, entries []schedule.Entry) ([]agentapi.Job, error) {
|
||||
jobs := []agentapi.Job{}
|
||||
if len(entries) == 0 {
|
||||
return jobs, nil
|
||||
@@ -148,7 +159,7 @@ func (s *Server) resolveJobs(ctx context.Context, a store.Agent, entries []sched
|
||||
var rows []store.Monitor
|
||||
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
|
||||
var err error
|
||||
rows, err = q.MonitorsForJobs(ctx, store.MonitorsForJobsParams{Region: deref(a.Region), Ids: ids})
|
||||
rows, err = q.MonitorsForJobs(ctx, store.MonitorsForJobsParams{RegionID: deref(a.RegionID), Ids: ids, AgentOrg: a.OrgID})
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
@@ -190,7 +201,8 @@ func (s *Server) agentResults(c *gin.Context) {
|
||||
monitors := map[uuid.UUID]store.MonitorsForResultsRow{}
|
||||
var accepted []agentapi.Result
|
||||
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
|
||||
rows, err := q.MonitorsForResults(ctx, store.MonitorsForResultsParams{Region: region, Ids: ids})
|
||||
a := agentOf(c)
|
||||
rows, err := q.MonitorsForResults(ctx, store.MonitorsForResultsParams{RegionID: deref(a.RegionID), Ids: ids, AgentOrg: a.OrgID})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -75,9 +75,10 @@ func TestAlerting(t *testing.T) {
|
||||
}))
|
||||
defer target.Close()
|
||||
|
||||
eu, us := uniq("eu-"), uniq("us-")
|
||||
e.startChecker(t, e.agentToken(t, eu))
|
||||
e.startChecker(t, e.agentToken(t, us))
|
||||
euTok, eu := e.platformChecker(t, uniq("eu-"))
|
||||
usTok, us := e.platformChecker(t, uniq("us-"))
|
||||
e.startChecker(t, euTok)
|
||||
e.startChecker(t, usTok)
|
||||
|
||||
owner := e.browser(t)
|
||||
owner.signup("o@"+uniq("a")+".test", uniq("alert-"))
|
||||
@@ -169,8 +170,8 @@ func TestLostEvaluationStateDoesNotDuplicateIncidents(t *testing.T) {
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
}))
|
||||
defer target.Close()
|
||||
region := uniq("eu-")
|
||||
e.startChecker(t, e.agentToken(t, region))
|
||||
tok, region := e.platformChecker(t, uniq("eu-"))
|
||||
e.startChecker(t, tok)
|
||||
|
||||
owner := e.browser(t)
|
||||
owner.signup("o@"+uniq("l")+".test", uniq("lost-"))
|
||||
|
||||
@@ -75,7 +75,14 @@ func (s *Server) signup(c *gin.Context) {
|
||||
if _, err := q.CreateOrg(ctx, store.CreateOrgParams{ID: orgID, Slug: strings.ToLower(req.OrgSlug), Name: strings.TrimSpace(req.OrgName)}); err != nil {
|
||||
return err
|
||||
}
|
||||
return q.AddMembership(ctx, store.AddMembershipParams{OrgID: orgID, UserID: user.ID, IsOwner: true})
|
||||
if err := q.AddMembership(ctx, store.AddMembershipParams{OrgID: orgID, UserID: user.ID, IsOwner: true}); err != nil {
|
||||
return err
|
||||
}
|
||||
// Whoever sets up a self-hosted installation operates it.
|
||||
if s.cfg.Signup == config.SignupFirstUser && s.cfg.Edition == config.EditionSelfHosted {
|
||||
return q.MakeAdmin(ctx, user.ID)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
switch {
|
||||
case isUniqueViolation(err, "users_email_key"):
|
||||
|
||||
@@ -13,31 +13,35 @@ import (
|
||||
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/agentapi"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/api"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/auth"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/checker"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/store"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/tenant"
|
||||
)
|
||||
|
||||
// agentToken creates a checker agent for region directly in the database,
|
||||
// as "api agent create" would.
|
||||
func (e *env) agentToken(t *testing.T, region string) string {
|
||||
// platformChecker creates a platform region with a checker agent directly
|
||||
// in the database, as "api agent create" would, and returns the agent token
|
||||
// and the region ID.
|
||||
func (e *env) platformChecker(t *testing.T, key string) (string, string) {
|
||||
t.Helper()
|
||||
tok := api.AgentTokenPrefix + auth.RandomToken()
|
||||
ctx := context.Background()
|
||||
var (
|
||||
tok string
|
||||
region store.Region
|
||||
)
|
||||
err := tenant.New(e.dbPool).Tx(ctx, tenant.System(), func(q *store.Queries) error {
|
||||
if _, err := q.UpsertRegion(ctx, store.UpsertRegionParams{Key: region}); err != nil {
|
||||
var err error
|
||||
if region, err = q.EnsurePlatformRegion(ctx, store.EnsurePlatformRegionParams{Key: key}); err != nil {
|
||||
return err
|
||||
}
|
||||
_, err := q.CreateAgent(ctx, store.CreateAgentParams{
|
||||
Kind: "checker", Name: "test-" + region, Region: ®ion, TokenHash: api.HashToken(tok), Prefix: tok[:10],
|
||||
})
|
||||
var params store.CreateAgentParams
|
||||
tok, params = api.NewAgentToken(nil, "checker", "test-"+key, ®ion.ID)
|
||||
_, err = q.CreateAgent(ctx, params)
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("creating agent: %v", err)
|
||||
}
|
||||
return tok
|
||||
return tok, region.ID.String()
|
||||
}
|
||||
|
||||
// startChecker runs a checker instance until the returned stop is called.
|
||||
@@ -77,8 +81,8 @@ func TestCheckersPerRegion(t *testing.T) {
|
||||
}))
|
||||
defer target.Close()
|
||||
|
||||
eu, us := uniq("eu-"), uniq("us-")
|
||||
euTok, usTok := e.agentToken(t, eu), e.agentToken(t, us)
|
||||
euTok, eu := e.platformChecker(t, uniq("eu-"))
|
||||
usTok, us := e.platformChecker(t, uniq("us-"))
|
||||
euA, stopA := e.startChecker(t, euTok)
|
||||
euB, _ := e.startChecker(t, euTok)
|
||||
usC, _ := e.startChecker(t, usTok)
|
||||
@@ -89,10 +93,10 @@ func TestCheckersPerRegion(t *testing.T) {
|
||||
|
||||
// Instances register on their first poll.
|
||||
waitFor(t, 5*time.Second, "both eu instances registered", func() bool {
|
||||
_, body := owner.do("GET", "/api/v1/regions", nil)
|
||||
_, body := owner.do("GET", "/api/v1/org/regions", nil)
|
||||
for _, r := range body["regions"].([]any) {
|
||||
r := r.(map[string]any)
|
||||
if r["key"] == eu && r["instances"] == float64(2) {
|
||||
if r["id"] == eu && r["instances"] == float64(2) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
@@ -169,7 +173,7 @@ func TestCheckersPerRegion(t *testing.T) {
|
||||
|
||||
func TestAgentAuth(t *testing.T) {
|
||||
e := newEnv(t)
|
||||
tok := e.agentToken(t, uniq("x-"))
|
||||
tok, _ := e.platformChecker(t, uniq("x-"))
|
||||
ctx := context.Background()
|
||||
if _, err := agentapi.NewClient(e.srv.URL, "usa_wrong", uuid.New(), "t").WithHTTPClient(e.srv.Client()).Hello(ctx); !errors.Is(err, agentapi.ErrUnauthorized) {
|
||||
t.Errorf("Hello(wrong token) = %v, want %v", err, agentapi.ErrUnauthorized)
|
||||
|
||||
+3
-1
@@ -38,6 +38,8 @@ type meView struct {
|
||||
// Set when an org the user belongs to enforces TOTP and the user has none.
|
||||
TOTPEnrollmentRequired bool `json:"totp_enrollment_required"`
|
||||
RecoveryCodesLeft int `json:"recovery_codes_left"`
|
||||
// IsAdmin marks platform admins, who manage shared regions and agents.
|
||||
IsAdmin bool `json:"is_admin"`
|
||||
}
|
||||
|
||||
func (s *Server) loadMe(ctx context.Context, sess *auth.Session) (meView, error) {
|
||||
@@ -55,7 +57,7 @@ func (s *Server) loadMe(ctx context.Context, sess *auth.Session) (meView, error)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
me = meView{ID: u.ID, Email: u.Email, DisplayName: u.DisplayName, TOTP: u.TotpSecret != nil, ActiveOrg: sess.OrgID, Orgs: []orgView{}, RecoveryCodesLeft: int(left)}
|
||||
me = meView{ID: u.ID, Email: u.Email, DisplayName: u.DisplayName, TOTP: u.TotpSecret != nil, ActiveOrg: sess.OrgID, Orgs: []orgView{}, RecoveryCodesLeft: int(left), IsAdmin: u.IsAdmin}
|
||||
for _, o := range orgs {
|
||||
me.Orgs = append(me.Orgs, orgView{ID: o.ID, Slug: o.Slug, Name: o.Name, IsOwner: o.IsOwner, RequireTOTP: o.RequireTotp})
|
||||
if o.RequireTotp && !me.TOTP {
|
||||
|
||||
+27
-47
@@ -27,7 +27,7 @@ type monitorRequest struct {
|
||||
TimeoutMS int `json:"timeout_ms"`
|
||||
Config json.RawMessage `json:"config"`
|
||||
Enabled *bool `json:"enabled"`
|
||||
Regions []string `json:"regions" binding:"required,min=1,max=50"`
|
||||
Regions []uuid.UUID `json:"regions" binding:"required,min=1,max=50"`
|
||||
// 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"`
|
||||
@@ -52,11 +52,11 @@ type monitorView struct {
|
||||
Config json.RawMessage `json:"config"`
|
||||
Enabled bool `json:"enabled"`
|
||||
Confirmations int32 `json:"confirmations"`
|
||||
Regions []string `json:"regions"`
|
||||
Regions []uuid.UUID `json:"regions"`
|
||||
Latest []latestView `json:"latest"`
|
||||
}
|
||||
|
||||
func viewMonitor(m store.Monitor, regions []string) monitorView {
|
||||
func viewMonitor(m store.Monitor, regions []uuid.UUID) monitorView {
|
||||
return monitorView{
|
||||
ID: m.ID, Name: m.Name, Type: m.Type, Target: m.Target, IntervalSeconds: m.IntervalSeconds,
|
||||
TimeoutMS: m.TimeoutMs, Config: m.Config, Enabled: m.Enabled, Confirmations: m.Confirmations, Regions: regions, Latest: []latestView{},
|
||||
@@ -105,13 +105,13 @@ func (s *Server) validateMonitor(c *gin.Context, req *monitorRequest) bool {
|
||||
return false
|
||||
}
|
||||
req.Config = cfg
|
||||
slices.Sort(req.Regions)
|
||||
slices.SortFunc(req.Regions, func(a, b uuid.UUID) int { return strings.Compare(a.String(), b.String()) })
|
||||
req.Regions = slices.Compact(req.Regions)
|
||||
ctx := c.Request.Context()
|
||||
var known []store.Region
|
||||
err = s.db.Tx(ctx, current(c).scope(), func(q *store.Queries) error {
|
||||
var err error
|
||||
known, err = q.ListRegions(ctx)
|
||||
known, err = q.ListVisibleRegions(ctx)
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
@@ -119,7 +119,9 @@ func (s *Server) validateMonitor(c *gin.Context, req *monitorRequest) bool {
|
||||
return false
|
||||
}
|
||||
for _, r := range req.Regions {
|
||||
if !slices.ContainsFunc(known, func(k store.Region) bool { return k.Key == r }) {
|
||||
// Row-level security limits known to the org's own and the
|
||||
// platform regions.
|
||||
if !slices.ContainsFunc(known, func(k store.Region) bool { return k.ID == r }) {
|
||||
fail(c, http.StatusUnprocessableEntity, "invalid_region")
|
||||
return false
|
||||
}
|
||||
@@ -144,9 +146,9 @@ func (s *Server) listMonitors(c *gin.Context) {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
byMonitor := map[uuid.UUID][]string{}
|
||||
byMonitor := map[uuid.UUID][]uuid.UUID{}
|
||||
for _, r := range regions {
|
||||
byMonitor[r.MonitorID] = append(byMonitor[r.MonitorID], r.Region)
|
||||
byMonitor[r.MonitorID] = append(byMonitor[r.MonitorID], r.RegionID)
|
||||
}
|
||||
latestBy := map[uuid.UUID][]latestView{}
|
||||
for _, l := range latest {
|
||||
@@ -201,12 +203,12 @@ func (s *Server) createMonitor(c *gin.Context) {
|
||||
c.JSON(http.StatusCreated, viewMonitor(m, req.Regions))
|
||||
}
|
||||
|
||||
func setRegions(ctx context.Context, q *store.Queries, m store.Monitor, regions []string) error {
|
||||
func setRegions(ctx context.Context, q *store.Queries, m store.Monitor, regions []uuid.UUID) error {
|
||||
if err := q.DeleteMonitorRegions(ctx, m.ID); err != nil {
|
||||
return err
|
||||
}
|
||||
for _, r := range regions {
|
||||
if err := q.AddMonitorRegion(ctx, store.AddMonitorRegionParams{MonitorID: m.ID, OrgID: m.OrgID, Region: r}); err != nil {
|
||||
if err := q.AddMonitorRegion(ctx, store.AddMonitorRegionParams{MonitorID: m.ID, OrgID: m.OrgID, RegionID: r}); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
@@ -215,13 +217,21 @@ func setRegions(ctx context.Context, q *store.Queries, m store.Monitor, regions
|
||||
|
||||
// syncSchedule applies a committed monitor change to the scheduler. Should it
|
||||
// fail, the periodic reconciliation repairs the schedule.
|
||||
func (s *Server) syncSchedule(ctx context.Context, m store.Monitor, regions, previous []string) error {
|
||||
func (s *Server) syncSchedule(ctx context.Context, m store.Monitor, regions, previous []uuid.UUID) error {
|
||||
if !m.Enabled {
|
||||
return s.sched.Remove(ctx, m.ID, append(regions, previous...))
|
||||
return s.sched.Remove(ctx, m.ID, idStrings(append(regions, previous...)))
|
||||
}
|
||||
return s.sched.Upsert(ctx, schedule.Monitor{
|
||||
ID: m.ID, Interval: time.Duration(m.IntervalSeconds) * time.Second, Regions: regions,
|
||||
}, previous)
|
||||
ID: m.ID, Interval: time.Duration(m.IntervalSeconds) * time.Second, Regions: idStrings(regions),
|
||||
}, idStrings(previous))
|
||||
}
|
||||
|
||||
func idStrings(ids []uuid.UUID) []string {
|
||||
out := make([]string, len(ids))
|
||||
for i, id := range ids {
|
||||
out[i] = id.String()
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func (s *Server) updateMonitor(c *gin.Context) {
|
||||
@@ -238,7 +248,7 @@ func (s *Server) updateMonitor(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
var (
|
||||
m store.Monitor
|
||||
previous []string
|
||||
previous []uuid.UUID
|
||||
)
|
||||
err = s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
|
||||
var err error
|
||||
@@ -279,7 +289,7 @@ func (s *Server) deleteMonitor(c *gin.Context) {
|
||||
p := current(c)
|
||||
ctx := c.Request.Context()
|
||||
var (
|
||||
regions []string
|
||||
regions []uuid.UUID
|
||||
n int64
|
||||
)
|
||||
err = s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
|
||||
@@ -298,7 +308,7 @@ func (s *Server) deleteMonitor(c *gin.Context) {
|
||||
fail(c, http.StatusNotFound, "not_found")
|
||||
return
|
||||
}
|
||||
if err := s.sched.Remove(ctx, id, regions); err != nil {
|
||||
if err := s.sched.Remove(ctx, id, idStrings(regions)); err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
@@ -306,36 +316,6 @@ func (s *Server) deleteMonitor(c *gin.Context) {
|
||||
c.Status(http.StatusNoContent)
|
||||
}
|
||||
|
||||
type regionView struct {
|
||||
Key string `json:"key"`
|
||||
Name string `json:"name"`
|
||||
Instances int64 `json:"instances"`
|
||||
}
|
||||
|
||||
func (s *Server) listRegions(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
var rows []store.Region
|
||||
err := s.db.Tx(ctx, tenant.Global(), func(q *store.Queries) error {
|
||||
var err error
|
||||
rows, err = q.ListRegions(ctx)
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
out := make([]regionView, len(rows))
|
||||
for i, r := range rows {
|
||||
n, err := s.sched.Instances(ctx, r.Key)
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
out[i] = regionView{Key: r.Key, Name: r.Name, Instances: n}
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"regions": out})
|
||||
}
|
||||
|
||||
// RunScheduler dispatches due checks and periodically reconciles the
|
||||
// schedule with the database until ctx ends. Every API replica runs it;
|
||||
// dispatch is atomic in Redis and reconciliation is idempotent.
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"slices"
|
||||
"strings"
|
||||
@@ -29,6 +30,8 @@ func (s *Server) registerPages(r gin.IRouter) {
|
||||
r.GET("/settings/members", s.orgPage("members.title", authz.MembersRead, s.membersView))
|
||||
r.GET("/settings/roles", s.orgPage("roles.title", authz.MembersRead, s.rolesView))
|
||||
r.GET("/settings/tokens", s.orgPage("tokens.title", "", s.tokensView))
|
||||
r.GET("/settings/regions", s.orgPage("regions.title", authz.OrgManage, s.regionsView))
|
||||
r.GET("/admin", s.adminPage)
|
||||
}
|
||||
|
||||
// flashErrors lists the codes a redirect may ask a page to display. Anything
|
||||
@@ -398,6 +401,94 @@ func expiryChoices(limit *int32) []int {
|
||||
return out
|
||||
}
|
||||
|
||||
func (s *Server) regionsView(c *gin.Context, p *principal, page web.Page, me web.Me) (templ.Component, error) {
|
||||
ctx := c.Request.Context()
|
||||
var (
|
||||
regions []store.Region
|
||||
agents []store.ListAgentsRow
|
||||
)
|
||||
err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
|
||||
var err error
|
||||
if regions, err = q.ListVisibleRegions(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
agents, err = q.ListAgents(ctx, &p.Org.ID)
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
v, err := s.buildRegionsView(ctx, regions, agents, "/org", "/settings/regions", func(r store.Region) bool { return r.OrgID != nil })
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return web.RegionsPage(page, me, v), nil
|
||||
}
|
||||
|
||||
func (s *Server) adminPage(c *gin.Context) {
|
||||
sess := auth.Current(c)
|
||||
if sess == nil {
|
||||
c.Redirect(http.StatusSeeOther, "/login?next=/admin")
|
||||
return
|
||||
}
|
||||
me, _, err := s.consoleMe(c, sess)
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
if !me.IsAdmin {
|
||||
c.Redirect(http.StatusSeeOther, "/")
|
||||
return
|
||||
}
|
||||
ctx := c.Request.Context()
|
||||
var (
|
||||
regions []store.Region
|
||||
agents []store.ListAgentsRow
|
||||
)
|
||||
err = s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
|
||||
var err error
|
||||
if regions, err = q.ListPlatformRegions(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
agents, err = q.ListAgents(ctx, nil)
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
v, err := s.buildRegionsView(ctx, regions, agents, "/admin", "/admin", func(store.Region) bool { return true })
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
web.Render(c, http.StatusOK, web.AdminPage(s.pageFor(c, "admin.title"), me, v))
|
||||
}
|
||||
|
||||
func (s *Server) buildRegionsView(ctx context.Context, regions []store.Region, agents []store.ListAgentsRow, apiBase, next string, manageable func(store.Region) bool) (web.RegionsView, error) {
|
||||
v := web.RegionsView{APIBase: apiBase, Next: next}
|
||||
never := i18n.T(ctx, "tokens.never")
|
||||
for _, r := range regions {
|
||||
n, err := s.sched.Instances(ctx, r.ID.String())
|
||||
if err != nil {
|
||||
return v, err
|
||||
}
|
||||
wr := web.Region{ID: r.ID.String(), Key: r.Key, Name: r.Name, Platform: r.OrgID == nil, Manageable: manageable(r), Instances: n}
|
||||
v.Regions = append(v.Regions, wr)
|
||||
if wr.Manageable {
|
||||
v.OwnRegions = append(v.OwnRegions, wr)
|
||||
}
|
||||
}
|
||||
for _, a := range agents {
|
||||
seen := never
|
||||
if a.LastSeenAt != nil {
|
||||
seen = a.LastSeenAt.Format(time.DateTime)
|
||||
}
|
||||
v.Agents = append(v.Agents, web.Agent{ID: a.ID.String(), Kind: a.Kind, Name: a.Name, Region: deref(a.RegionName), Prefix: a.Prefix, LastSeen: seen})
|
||||
}
|
||||
return v, nil
|
||||
}
|
||||
|
||||
func toWebMe(m meView) web.Me {
|
||||
out := web.Me{
|
||||
Email: m.Email,
|
||||
@@ -405,6 +496,7 @@ func toWebMe(m meView) web.Me {
|
||||
TOTP: m.TOTP,
|
||||
ActiveOrg: m.ActiveOrg.String(),
|
||||
RecoveryCodesLeft: m.RecoveryCodesLeft,
|
||||
IsAdmin: m.IsAdmin,
|
||||
}
|
||||
for _, o := range m.Orgs {
|
||||
out.Orgs = append(out.Orgs, web.Org{ID: o.ID.String(), Name: o.Name, Slug: o.Slug, IsOwner: o.IsOwner})
|
||||
|
||||
@@ -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"
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
package api_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/store"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/tenant"
|
||||
)
|
||||
|
||||
func (b *browser) createRegion(key string) string {
|
||||
b.t.Helper()
|
||||
st, body := b.do("POST", "/api/v1/org/regions", map[string]any{"key": key, "name": "Office " + key})
|
||||
if st != http.StatusCreated {
|
||||
b.t.Fatalf("create region %s = %d %v", key, st, body)
|
||||
}
|
||||
return body["id"].(string)
|
||||
}
|
||||
|
||||
func (b *browser) regionIDs() []string {
|
||||
b.t.Helper()
|
||||
_, body := b.do("GET", "/api/v1/org/regions", nil)
|
||||
var ids []string
|
||||
for _, r := range body["regions"].([]any) {
|
||||
ids = append(ids, r.(map[string]any)["id"].(string))
|
||||
}
|
||||
return ids
|
||||
}
|
||||
|
||||
func TestOrgRegionsAndAgents(t *testing.T) {
|
||||
e := newEnv(t)
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
t.Cleanup(cancel)
|
||||
go e.api.RunScheduler(ctx)
|
||||
|
||||
_, platformRegion := e.platformChecker(t, uniq("shared-"))
|
||||
|
||||
a := e.browser(t)
|
||||
a.signup("a@"+uniq("a")+".test", uniq("org-a-"))
|
||||
b := e.browser(t)
|
||||
b.signup("b@"+uniq("b")+".test", uniq("org-b-"))
|
||||
|
||||
aOffice := a.createRegion("office")
|
||||
bOffice := b.createRegion("office") // same key in another org is fine
|
||||
|
||||
t.Run("own regions first, then platform", func(t *testing.T) {
|
||||
ids := a.regionIDs()
|
||||
if len(ids) < 2 || ids[0] != aOffice {
|
||||
t.Errorf("org A regions = %v, want %s first", ids, aOffice)
|
||||
}
|
||||
for _, id := range ids {
|
||||
if id == bOffice {
|
||||
t.Errorf("org A sees org B's region")
|
||||
}
|
||||
}
|
||||
found := false
|
||||
for _, id := range ids {
|
||||
found = found || id == platformRegion
|
||||
}
|
||||
if !found {
|
||||
t.Errorf("org A regions = %v, want platform region %s", ids, platformRegion)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("foreign regions are unusable", func(t *testing.T) {
|
||||
st, body := b.do("POST", "/api/v1/org/monitors", map[string]any{
|
||||
"name": "x", "type": "tcp", "target": "example.com:443", "interval_seconds": 60, "regions": []string{aOffice},
|
||||
})
|
||||
expect(t, "monitor in foreign region", st, body, http.StatusUnprocessableEntity, "invalid_region")
|
||||
st, body = a.do("POST", "/api/v1/org/agents", map[string]any{"kind": "checker", "name": "x", "region_id": bOffice})
|
||||
expect(t, "agent in foreign region", st, body, http.StatusUnprocessableEntity, "invalid_region")
|
||||
st, body = a.do("POST", "/api/v1/org/agents", map[string]any{"kind": "checker", "name": "x", "region_id": platformRegion})
|
||||
expect(t, "org agent in platform region", st, body, http.StatusUnprocessableEntity, "invalid_region")
|
||||
st, body = a.do("DELETE", "/api/v1/org/regions/"+platformRegion, nil)
|
||||
expect(t, "org deletes platform region", st, body, http.StatusNotFound, "not_found")
|
||||
})
|
||||
|
||||
t.Run("org checker runs only its org's monitors", func(t *testing.T) {
|
||||
st, body := a.do("POST", "/api/v1/org/agents", map[string]any{"kind": "checker", "name": "office-1", "region_id": aOffice})
|
||||
if st != http.StatusCreated {
|
||||
t.Fatalf("create org agent = %d %v", st, body)
|
||||
}
|
||||
checker, _ := e.startChecker(t, body["token"].(string))
|
||||
|
||||
target := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {}))
|
||||
defer target.Close()
|
||||
st, body = a.do("POST", "/api/v1/org/monitors", map[string]any{
|
||||
"name": "intranet", "type": "http", "target": target.URL, "interval_seconds": 60, "regions": []string{aOffice},
|
||||
})
|
||||
if st != http.StatusCreated {
|
||||
t.Fatalf("create monitor = %d %v", st, body)
|
||||
}
|
||||
waitFor(t, 10*time.Second, "org checker reports", func() bool {
|
||||
var n int
|
||||
_ = e.dbPool.QueryRow(context.Background(), `SELECT count(*) FROM check_results WHERE checker_id = $1 AND region = $2`, checker, aOffice).Scan(&n)
|
||||
return n > 0
|
||||
})
|
||||
st, body = a.do("DELETE", "/api/v1/org/regions/"+aOffice, nil)
|
||||
expect(t, "delete region in use", st, body, http.StatusConflict, "region_in_use")
|
||||
_, agents := a.do("GET", "/api/v1/org/agents", nil)
|
||||
if n := len(agents["agents"].([]any)); n != 1 {
|
||||
t.Errorf("org A agents = %d, want 1", n)
|
||||
}
|
||||
_, agents = b.do("GET", "/api/v1/org/agents", nil)
|
||||
if n := len(agents["agents"].([]any)); n != 0 {
|
||||
t.Errorf("org B agents = %d, want 0", n)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("platform regions are admin only", func(t *testing.T) {
|
||||
st, body := a.do("POST", "/api/v1/admin/regions", map[string]any{"key": "global"})
|
||||
expect(t, "non-admin creates platform region", st, body, http.StatusForbidden, "forbidden")
|
||||
|
||||
err := tenant.New(e.dbPool).Tx(context.Background(), tenant.Global(), func(q *store.Queries) error {
|
||||
return q.MakeAdmin(context.Background(), a.userIDSelf())
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
key := uniq("glob-")
|
||||
st, body = a.do("POST", "/api/v1/admin/regions", map[string]any{"key": key, "name": "Global"})
|
||||
if st != http.StatusCreated || body["own"] != false {
|
||||
t.Fatalf("admin creates platform region = %d %v", st, body)
|
||||
}
|
||||
global := body["id"].(string)
|
||||
st, body = a.do("POST", "/api/v1/admin/agents", map[string]any{"kind": "checker", "name": "g1", "region_id": global})
|
||||
expect(t, "admin creates platform agent", st, body, http.StatusCreated, "")
|
||||
found := false
|
||||
for _, id := range b.regionIDs() {
|
||||
found = found || id == global
|
||||
}
|
||||
if !found {
|
||||
t.Errorf("org B does not see the new platform region")
|
||||
}
|
||||
for _, path := range []string{"/admin", "/settings/regions"} {
|
||||
if got := a.visit(path); got.Path != path {
|
||||
t.Errorf("admin GET %s ended at %s", path, got.Path)
|
||||
}
|
||||
}
|
||||
if got := b.visit("/admin"); got.Path != "/" {
|
||||
t.Errorf("non-admin GET /admin ended at %s, want /", got.Path)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func (b *browser) userIDSelf() uuid.UUID {
|
||||
b.t.Helper()
|
||||
_, me := b.do("GET", "/api/v1/me", nil)
|
||||
return uuid.MustParse(me["id"].(string))
|
||||
}
|
||||
+15
-1
@@ -86,7 +86,6 @@ func (s *Server) Mount(r gin.IRouter) {
|
||||
|
||||
v1 := g.Group("/api/v1")
|
||||
v1.POST("/locale", s.setLocale)
|
||||
v1.GET("/regions", auth.Require(), s.listRegions)
|
||||
|
||||
a := v1.Group("/auth")
|
||||
a.POST("/signup", s.signup)
|
||||
@@ -113,6 +112,21 @@ func (s *Server) Mount(r gin.IRouter) {
|
||||
org.PUT("/monitors/:id", can(authz.MonitorsWrite), s.updateMonitor)
|
||||
org.DELETE("/monitors/:id", can(authz.MonitorsWrite), s.deleteMonitor)
|
||||
|
||||
org.GET("/regions", can(authz.MonitorsRead), 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.DELETE("/agents/:id", sessionOnly(), can(authz.OrgManage), s.deleteOrgAgent)
|
||||
|
||||
admin := v1.Group("/admin", s.requireAdmin())
|
||||
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("/incidents", can(authz.IncidentsRead), s.listIncidents)
|
||||
|
||||
org.GET("/channels", can(authz.NotificationsRead), s.listChannels)
|
||||
|
||||
Reference in new issue
Block a user