diff --git a/cmd/api/admin.go b/cmd/api/admin.go index 3b8fc33..6b5e793 100644 --- a/cmd/api/admin.go +++ b/cmd/api/admin.go @@ -12,7 +12,6 @@ import ( "github.com/google/uuid" "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/config" "git.zb-server.de/ZB-Server/uptimesebi/internal/platform" "git.zb-server.de/ZB-Server/uptimesebi/internal/store" @@ -22,10 +21,14 @@ import ( const usage = `usage: api [serve] api migrate up|down|status + api admin grant|revoke api region add [name] api agent create --kind checker|statuspage [--region ] --name api agent list - api agent revoke ` + api agent revoke + +region and agent manage platform resources shared by all organizations; +organizations manage their own in the console.` // admin runs operator commands. They act across all organizations, hence the // system scope, and print to stdout for humans and scripts. @@ -41,15 +44,23 @@ func admin(ctx context.Context, cfg config.API, args []string) error { db := tenant.New(pool) switch { + case len(args) == 3 && args[0] == "admin" && (args[1] == "grant" || args[1] == "revoke"): + return db.Tx(ctx, tenant.Global(), func(q *store.Queries) error { + n, err := q.SetUserAdmin(ctx, store.SetUserAdminParams{Email: args[2], IsAdmin: args[1] == "grant"}) + if err == nil && n == 0 { + err = errors.New("no user with that email") + } + return err + }) case len(args) >= 3 && args[0] == "region" && args[1] == "add": - name := args[2] + name := "" if len(args) > 3 { name = args[3] } return db.Tx(ctx, tenant.System(), func(q *store.Queries) error { - r, err := q.UpsertRegion(ctx, store.UpsertRegionParams{Key: args[2], Name: name}) + r, err := q.EnsurePlatformRegion(ctx, store.EnsurePlatformRegionParams{Key: args[2], Name: name}) if err == nil { - fmt.Printf("region %s (%s)\n", r.Key, r.Name) + fmt.Printf("region %s %s (%s)\n", r.ID, r.Key, r.Name) } return err }) @@ -57,7 +68,7 @@ func admin(ctx context.Context, cfg config.API, args []string) error { return createAgent(ctx, db, args[2:]) case len(args) == 2 && args[0] == "agent" && args[1] == "list": return db.Tx(ctx, tenant.System(), func(q *store.Queries) error { - agents, err := q.ListAgents(ctx) + agents, err := q.ListAgents(ctx, nil) if err != nil { return err } @@ -68,7 +79,7 @@ func admin(ctx context.Context, cfg config.API, args []string) error { if a.LastSeenAt != nil { seen = a.LastSeenAt.Format(time.DateTime) } - _, _ = fmt.Fprintf(w, "%s\t%s\t%s\t%s\t%s…\t%s\t%s\n", a.ID, a.Kind, deref(a.Region), a.Name, a.Prefix, seen, deref(a.Release)) + _, _ = fmt.Fprintf(w, "%s\t%s\t%s\t%s\t%s…\t%s\t%s\n", a.ID, a.Kind, deref(a.RegionKey), a.Name, a.Prefix, seen, deref(a.Release)) } return w.Flush() }) @@ -78,9 +89,9 @@ func admin(ctx context.Context, cfg config.API, args []string) error { return err } return db.Tx(ctx, tenant.System(), func(q *store.Queries) error { - n, err := q.DeleteAgent(ctx, id) + n, err := q.DeleteAgent(ctx, store.DeleteAgentParams{ID: id}) if err == nil && n == 0 { - err = errors.New("agent not found") + err = errors.New("platform agent not found") } return err }) @@ -91,7 +102,7 @@ func admin(ctx context.Context, cfg config.API, args []string) error { func createAgent(ctx context.Context, db *tenant.DB, args []string) error { fs := flag.NewFlagSet("agent create", flag.ContinueOnError) kind := fs.String("kind", "checker", "checker or statuspage") - region := fs.String("region", "", "region key, required for checkers; created if missing") + region := fs.String("region", "", "platform region key, required for checkers; created if missing") name := fs.String("name", "", "display name") if err := fs.Parse(args); err != nil { return err @@ -99,17 +110,18 @@ func createAgent(ctx context.Context, db *tenant.DB, args []string) error { if *name == "" || (*kind == "checker") != (*region != "") { return errors.New(usage) } - tok := api.AgentTokenPrefix + auth.RandomToken() - params := store.CreateAgentParams{Kind: *kind, Name: *name, TokenHash: api.HashToken(tok), Prefix: tok[:len(api.AgentTokenPrefix)+6]} - if *region != "" { - params.Region = region - } + var tok string err := db.Tx(ctx, tenant.System(), func(q *store.Queries) error { + var regionID *uuid.UUID if *region != "" { - if _, err := q.UpsertRegion(ctx, store.UpsertRegionParams{Key: *region, Name: ""}); err != nil { + r, err := q.EnsurePlatformRegion(ctx, store.EnsurePlatformRegionParams{Key: *region}) + if err != nil { return err } + regionID = &r.ID } + var params store.CreateAgentParams + tok, params = api.NewAgentToken(nil, *kind, *name, regionID) _, err := q.CreateAgent(ctx, params) return err }) diff --git a/cmd/api/main.go b/cmd/api/main.go index cd73283..a0836ac 100644 --- a/cmd/api/main.go +++ b/cmd/api/main.go @@ -43,7 +43,7 @@ func run(log *slog.Logger, level *slog.LevelVar, args []string) error { switch args[0] { case "migrate": return migrate(ctx, log, cfg.DatabaseURL, args[1:]) - case "agent", "region": + case "admin", "agent", "region": return admin(ctx, cfg, args) case "serve": default: diff --git a/internal/agentapi/agentapi.go b/internal/agentapi/agentapi.go index dec6c3e..b1b8cd0 100644 --- a/internal/agentapi/agentapi.go +++ b/internal/agentapi/agentapi.go @@ -33,11 +33,16 @@ const ( // Hello describes the agent the token belongs to. type Hello struct { - AgentID uuid.UUID `json:"agent_id"` - Name string `json:"name"` - Kind string `json:"kind"` - Region string `json:"region,omitempty"` - Protocol int `json:"protocol"` + AgentID uuid.UUID `json:"agent_id"` + Name string `json:"name"` + Kind string `json:"kind"` + // Region is the region key; RegionID identifies it uniquely. + Region string `json:"region,omitempty"` + RegionID *uuid.UUID `json:"region_id,omitempty"` + RegionName string `json:"region_name,omitempty"` + // OrgOwned is set for agents that serve a single organization. + OrgOwned bool `json:"org_owned"` + Protocol int `json:"protocol"` } // JobsRequest asks for up to Max jobs, waiting up to WaitMS if none are diff --git a/internal/api/agent.go b/internal/api/agent.go index 90ad3a9..a65f6a2 100644 --- a/internal/api/agent.go +++ b/internal/api/agent.go @@ -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 } diff --git a/internal/api/alerting_test.go b/internal/api/alerting_test.go index 7dd4276..25767e2 100644 --- a/internal/api/alerting_test.go +++ b/internal/api/alerting_test.go @@ -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-")) diff --git a/internal/api/auth.go b/internal/api/auth.go index 6f84eba..a022385 100644 --- a/internal/api/auth.go +++ b/internal/api/auth.go @@ -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"): diff --git a/internal/api/checker_test.go b/internal/api/checker_test.go index f9ab00e..9bbedf5 100644 --- a/internal/api/checker_test.go +++ b/internal/api/checker_test.go @@ -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) diff --git a/internal/api/me.go b/internal/api/me.go index 8b0709a..2e24fec 100644 --- a/internal/api/me.go +++ b/internal/api/me.go @@ -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 { diff --git a/internal/api/monitors.go b/internal/api/monitors.go index b2e9a5d..8fc4ea0 100644 --- a/internal/api/monitors.go +++ b/internal/api/monitors.go @@ -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. diff --git a/internal/api/pages.go b/internal/api/pages.go index a317e69..5e7353a 100644 --- a/internal/api/pages.go +++ b/internal/api/pages.go @@ -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}) diff --git a/internal/api/regions.go b/internal/api/regions.go new file mode 100644 index 0000000..c13be61 --- /dev/null +++ b/internal/api/regions.go @@ -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" +} diff --git a/internal/api/regions_test.go b/internal/api/regions_test.go new file mode 100644 index 0000000..7e2875e --- /dev/null +++ b/internal/api/regions_test.go @@ -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)) +} diff --git a/internal/api/server.go b/internal/api/server.go index 85f45c3..f9141b0 100644 --- a/internal/api/server.go +++ b/internal/api/server.go @@ -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) diff --git a/internal/i18n/locales/de.json b/internal/i18n/locales/de.json index 9f6620f..516fde6 100644 --- a/internal/i18n/locales/de.json +++ b/internal/i18n/locales/de.json @@ -1,4 +1,15 @@ { + "admin.intro": "Hier angelegte Regionen, Checker und Statuspage-Server stehen allen Organisationen zur Verfügung. Organisationen legen ihre eigenen unter Regionen & Checker an.", + "admin.title": "Plattform-Verwaltung", + "agents.create": "Agent anlegen", + "agents.kind": "Art", + "agents.kind_checker": "Checker", + "agents.kind_statuspage": "Statuspage-Server", + "agents.list": "Agents", + "agents.no_region": "– (nur für Statuspage-Server)", + "agents.region": "Region", + "agents.revoke_confirm": "Diesen Agent widerrufen? Seine Instanzen hören sofort auf zu arbeiten.", + "agents.token_now": "Kopiere den Token jetzt und setze ihn als UPTIME_AGENT_TOKEN. Er wird nicht erneut angezeigt. Beliebig viele Instanzen können ihn teilen.", "app.network_error": "Verbindung fehlgeschlagen.", "auth.field.code": "Code", "auth.field.email": "E-Mail", @@ -23,9 +34,11 @@ "common.yes": "ja", "console.monitors.empty": "Noch keine Monitore angelegt.", "console.monitors.title": "Monitore", + "console.nav.admin": "Admin", "console.nav.logout": "Abmelden", "console.nav.members": "Mitglieder", "console.nav.org": "Organisation", + "console.nav.regions": "Regionen & Checker", "console.nav.roles": "Rollen", "console.nav.security": "Sicherheit", "console.nav.sso": "SSO", @@ -60,6 +73,7 @@ "error.invalid_permissions": "Mindestens eine Berechtigung auswählen.", "error.invalid_record": "Nicht unterstützter DNS-Record-Typ.", "error.invalid_region": "Unbekannte Region.", + "error.invalid_region_key": "Regions-Schlüssel haben 1–40 Zeichen: a–z, 0–9 und Bindestrich.", "error.invalid_resolver": "Der Resolver muss als host:port angegeben werden.", "error.invalid_slug": "Kurzname: 2–63 Zeichen, a–z, 0–9 und Bindestrich.", "error.invalid_target": "Das Ziel passt nicht zu diesem Check-Typ.", @@ -79,6 +93,8 @@ "error.permission_escalation": "Du kannst keine Berechtigungen vergeben, die du selbst nicht hast.", "error.policy_would_lock_you_out": "Deine aktuelle Anmeldung erfüllt diese Richtlinie nicht. Erfülle sie zuerst und aktiviere sie dann.", "error.rate_limited": "Zu viele Versuche, bitte später erneut.", + "error.region_in_use": "Die Region wird noch von Monitoren oder Agents genutzt.", + "error.region_key_taken": "Eine Region mit diesem Schlüssel gibt es bereits.", "error.role_built_in": "Eingebaute Rollen können nicht geändert werden.", "error.role_in_use": "Die Rolle ist noch Mitgliedern zugewiesen.", "error.role_name_taken": "Eine Rolle mit diesem Namen gibt es bereits.", @@ -151,6 +167,21 @@ "perm.statuspages.read": "Statuspages sehen", "perm.statuspages.write": "Statuspages bearbeiten", "perm.tokens.manage": "Alle API-Tokens sehen und widerrufen", + "regions.create": "Region anlegen", + "regions.delete": "Löschen", + "regions.delete_confirm": "Diese Region löschen?", + "regions.instances": "Checker", + "regions.intro": "Betreibe eigene Checker, z. B. in deinem Netzwerk, in Regionen, die nur deine Organisation sieht. Plattform-Regionen stehen allen zur Verfügung.", + "regions.key": "Schlüssel", + "regions.list": "Regionen", + "regions.live": { + "one": "{{.Count}} aktiv", + "other": "{{.Count}} aktiv" + }, + "regions.own": "diese Organisation", + "regions.owner": "Besitzer", + "regions.platform": "Plattform", + "regions.title": "Regionen & Checker", "roles.built_in": "eingebaut", "roles.create": "Rolle anlegen", "roles.delete": "Rolle löschen", diff --git a/internal/i18n/locales/en.json b/internal/i18n/locales/en.json index 3ff83ff..18fe7ad 100644 --- a/internal/i18n/locales/en.json +++ b/internal/i18n/locales/en.json @@ -1,4 +1,15 @@ { + "admin.intro": "Regions, checkers and status page servers created here are shared by every organization. Organizations add their own under Regions & checkers.", + "admin.title": "Platform administration", + "agents.create": "Create agent", + "agents.kind": "Kind", + "agents.kind_checker": "Checker", + "agents.kind_statuspage": "Status page server", + "agents.list": "Agents", + "agents.no_region": "– (status page servers only)", + "agents.region": "Region", + "agents.revoke_confirm": "Revoke this agent? Its instances stop working immediately.", + "agents.token_now": "Copy the token now and set it as UPTIME_AGENT_TOKEN. It will not be shown again. Any number of instances may share it.", "app.network_error": "Connection failed.", "auth.field.code": "Code", "auth.field.email": "Email", @@ -23,9 +34,11 @@ "common.yes": "yes", "console.monitors.empty": "No monitors yet.", "console.monitors.title": "Monitors", + "console.nav.admin": "Admin", "console.nav.logout": "Sign out", "console.nav.members": "Members", "console.nav.org": "Organization", + "console.nav.regions": "Regions & checkers", "console.nav.roles": "Roles", "console.nav.security": "Security", "console.nav.sso": "SSO", @@ -60,6 +73,7 @@ "error.invalid_permissions": "Choose at least one permission.", "error.invalid_record": "Unsupported DNS record type.", "error.invalid_region": "Unknown region.", + "error.invalid_region_key": "Region keys use 1–40 characters: a–z, 0–9 and hyphen.", "error.invalid_resolver": "The resolver must be given as host:port.", "error.invalid_slug": "Short name: 2–63 characters, a–z, 0–9 and hyphen.", "error.invalid_target": "The target is not valid for this check type.", @@ -79,6 +93,8 @@ "error.permission_escalation": "You cannot grant permissions you do not hold yourself.", "error.policy_would_lock_you_out": "Your current sign-in does not meet this policy. Meet it first, then turn it on.", "error.rate_limited": "Too many attempts, please try again later.", + "error.region_in_use": "The region is still used by monitors or agents.", + "error.region_key_taken": "A region with this key already exists.", "error.role_built_in": "Built-in roles cannot be changed.", "error.role_in_use": "The role is still assigned to members.", "error.role_name_taken": "A role with this name already exists.", @@ -151,6 +167,21 @@ "perm.statuspages.read": "View status pages", "perm.statuspages.write": "Edit status pages", "perm.tokens.manage": "View and revoke all API tokens", + "regions.create": "Create region", + "regions.delete": "Delete", + "regions.delete_confirm": "Delete this region?", + "regions.instances": "Checkers", + "regions.intro": "Run your own checkers, e.g. inside your network, in regions only your organization sees. Platform regions are available to everyone.", + "regions.key": "Key", + "regions.list": "Regions", + "regions.live": { + "one": "{{.Count}} live", + "other": "{{.Count}} live" + }, + "regions.own": "this organization", + "regions.owner": "Owner", + "regions.platform": "platform", + "regions.title": "Regions & checkers", "roles.built_in": "built-in", "roles.create": "Create role", "roles.delete": "Delete role", diff --git a/internal/migrations/migrations.go b/internal/migrations/migrations.go index 26587b3..82646e6 100644 --- a/internal/migrations/migrations.go +++ b/internal/migrations/migrations.go @@ -9,7 +9,8 @@ import ( "fmt" "io/fs" - _ "github.com/jackc/pgx/v5/stdlib" // registers the "pgx" database/sql driver + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/stdlib" "github.com/pressly/goose/v3" "github.com/pressly/goose/v3/lock" ) @@ -21,11 +22,16 @@ var files embed.FS // a rolling deploy serialize instead of racing. const lockID = 0x7570746d +// newProvider connects with app.scope=system as a session default: tables +// are under row-level security, and data changes in migrations would +// otherwise silently affect no rows. func newProvider(dsn string) (*goose.Provider, *sql.DB, error) { - db, err := sql.Open("pgx", dsn) + cfg, err := pgx.ParseConfig(dsn) if err != nil { return nil, nil, err } + cfg.RuntimeParams["app.scope"] = "system" + db := stdlib.OpenDB(*cfg) sub, err := fs.Sub(files, "sql") if err != nil { return nil, nil, err diff --git a/internal/migrations/migrations_test.go b/internal/migrations/migrations_test.go new file mode 100644 index 0000000..1a36e75 --- /dev/null +++ b/internal/migrations/migrations_test.go @@ -0,0 +1,35 @@ +package migrations + +import ( + "context" + "os" + "slices" + "testing" + + "github.com/jackc/pgx/v5" +) + +// TestDataMigrationsApply catches data changes that row-level security +// silently filtered out, as happened to 00009 and 00012. +func TestDataMigrationsApply(t *testing.T) { + dsn := os.Getenv("UPTIME_TEST_DATABASE_URL") + if dsn == "" { + t.Skip("UPTIME_TEST_DATABASE_URL not set") + } + ctx := context.Background() + if _, err := Up(ctx, dsn); err != nil { + t.Fatalf("Up() failed: %v", err) + } + conn, err := pgx.Connect(ctx, dsn) + if err != nil { + t.Fatal(err) + } + defer func() { _ = conn.Close(ctx) }() + var perms []string + if err := conn.QueryRow(ctx, `SELECT permissions FROM roles WHERE key = 'admin'`).Scan(&perms); err != nil { + t.Fatal(err) + } + if !slices.Contains(perms, "tokens.manage") { + t.Errorf("admin role permissions = %v, want tokens.manage", perms) + } +} diff --git a/internal/migrations/sql/00016_repair_scoped_data.sql b/internal/migrations/sql/00016_repair_scoped_data.sql new file mode 100644 index 0000000..4ab1eb7 --- /dev/null +++ b/internal/migrations/sql/00016_repair_scoped_data.sql @@ -0,0 +1,24 @@ +-- +goose Up +-- Migrations 00009 and 00012 changed data before migration connections ran +-- with the system scope, so row-level security hid every row from them. +-- Built-in roles were also not writable even in the system scope. + +DROP POLICY roles_write ON roles; +CREATE POLICY roles_write ON roles FOR ALL + USING (app_scope_system() OR (org_id IS NOT NULL AND org_id = app_org_id())) + WITH CHECK (app_scope_system() OR (org_id IS NOT NULL AND org_id = app_org_id())); + +UPDATE roles SET permissions = array_append(permissions, 'tokens.manage') +WHERE key = 'admin' AND NOT 'tokens.manage' = ANY (permissions); + +INSERT INTO role_assignments (org_id, user_id, role_id) +SELECT m.org_id, m.user_id, '00000000-0000-0000-0000-00000000a003' +FROM memberships m +WHERE NOT m.is_owner + AND NOT EXISTS (SELECT 1 FROM role_assignments a WHERE a.org_id = m.org_id AND a.user_id = m.user_id); + +-- +goose Down +DROP POLICY roles_write ON roles; +CREATE POLICY roles_write ON roles FOR ALL + USING (org_id IS NOT NULL AND (app_scope_system() OR org_id = app_org_id())) + WITH CHECK (org_id IS NOT NULL AND (app_scope_system() OR org_id = app_org_id())); diff --git a/internal/migrations/sql/00017_owned_regions.sql b/internal/migrations/sql/00017_owned_regions.sql new file mode 100644 index 0000000..13bfbd9 --- /dev/null +++ b/internal/migrations/sql/00017_owned_regions.sql @@ -0,0 +1,104 @@ +-- +goose Up +-- Regions, checkers and status page servers belong either to the platform +-- (org_id NULL, managed by platform admins, usable by every org) or to one +-- organization. Org-owned regions may reuse keys of other orgs, so regions +-- are now identified by id; check_results.region stores that id as text. + +ALTER TABLE regions ADD COLUMN id uuid NOT NULL DEFAULT gen_random_uuid(); +ALTER TABLE regions ADD COLUMN org_id uuid REFERENCES orgs (id) ON DELETE CASCADE; + +ALTER TABLE monitor_regions ADD COLUMN region_id uuid; +UPDATE monitor_regions mr SET region_id = r.id FROM regions r WHERE r.key = mr.region; +ALTER TABLE agents ADD COLUMN region_id uuid; +UPDATE agents a SET region_id = r.id FROM regions r WHERE r.key = a.region; +UPDATE check_results c SET region = r.id::text FROM regions r WHERE r.key = c.region; + +ALTER TABLE monitor_regions DROP CONSTRAINT monitor_regions_pkey; +ALTER TABLE monitor_regions DROP COLUMN region; +ALTER TABLE agents DROP CONSTRAINT agents_check; +ALTER TABLE agents DROP COLUMN region; + +ALTER TABLE regions DROP CONSTRAINT regions_pkey; +ALTER TABLE regions ADD PRIMARY KEY (id); +ALTER TABLE regions ADD CONSTRAINT regions_owner_key_key UNIQUE NULLS NOT DISTINCT (org_id, key); + +ALTER TABLE monitor_regions ALTER COLUMN region_id SET NOT NULL; +ALTER TABLE monitor_regions ADD PRIMARY KEY (monitor_id, region_id); +-- A region in use cannot be deleted; monitors have to move first. +ALTER TABLE monitor_regions ADD FOREIGN KEY (region_id) REFERENCES regions (id); +ALTER TABLE agents ADD FOREIGN KEY (region_id) REFERENCES regions (id); +ALTER TABLE agents ADD CONSTRAINT agents_checker_has_region CHECK ((kind = 'checker') = (region_id IS NOT NULL)); + +-- +goose StatementBegin +-- The region of an agent has the same owner as the agent, and monitors use +-- only platform regions or regions of their own org. A composite foreign +-- key cannot express this because platform rows have a NULL org_id. +CREATE FUNCTION region_owner(region uuid) RETURNS uuid +LANGUAGE sql STABLE AS $$ SELECT org_id FROM regions WHERE id = region $$; + +CREATE FUNCTION agents_region_owner_check() RETURNS trigger +LANGUAGE plpgsql AS $$ +BEGIN + IF NEW.region_id IS NOT NULL AND region_owner(NEW.region_id) IS DISTINCT FROM NEW.org_id THEN + RAISE EXCEPTION 'agent and region must have the same owner' USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; +END +$$; + +CREATE FUNCTION monitor_regions_owner_check() RETURNS trigger +LANGUAGE plpgsql AS $$ +DECLARE + owner uuid := region_owner(NEW.region_id); +BEGIN + IF owner IS NOT NULL AND owner <> NEW.org_id THEN + RAISE EXCEPTION 'region belongs to another organization' USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; +END +$$; +-- +goose StatementEnd + +CREATE TRIGGER agents_region_owner BEFORE INSERT OR UPDATE ON agents + FOR EACH ROW EXECUTE FUNCTION agents_region_owner_check(); +CREATE TRIGGER monitor_regions_owner BEFORE INSERT OR UPDATE ON monitor_regions + FOR EACH ROW EXECUTE FUNCTION monitor_regions_owner_check(); + +ALTER TABLE regions ENABLE ROW LEVEL SECURITY; +ALTER TABLE regions FORCE ROW LEVEL SECURITY; +CREATE POLICY regions_read ON regions FOR SELECT + USING (org_id IS NULL OR app_scope_system() OR org_id = app_org_id()); +CREATE POLICY regions_write ON regions FOR ALL + USING (app_scope_system() OR (org_id IS NOT NULL AND org_id = app_org_id())) + WITH CHECK (app_scope_system() OR (org_id IS NOT NULL AND org_id = app_org_id())); + +-- +goose Down +-- Only reversible while no organization owns regions. +DROP POLICY regions_write ON regions; +DROP POLICY regions_read ON regions; +ALTER TABLE regions NO FORCE ROW LEVEL SECURITY; +ALTER TABLE regions DISABLE ROW LEVEL SECURITY; +DROP TRIGGER monitor_regions_owner ON monitor_regions; +DROP TRIGGER agents_region_owner ON agents; +DROP FUNCTION monitor_regions_owner_check(); +DROP FUNCTION agents_region_owner_check(); +DROP FUNCTION region_owner(uuid); +ALTER TABLE monitor_regions ADD COLUMN region text; +UPDATE monitor_regions mr SET region = r.key FROM regions r WHERE r.id = mr.region_id; +ALTER TABLE agents ADD COLUMN region text; +UPDATE agents a SET region = r.key FROM regions r WHERE r.id = a.region_id; +UPDATE check_results c SET region = r.key FROM regions r WHERE r.id::text = c.region; +ALTER TABLE agents DROP CONSTRAINT agents_checker_has_region; +ALTER TABLE agents DROP COLUMN region_id; +ALTER TABLE monitor_regions DROP CONSTRAINT monitor_regions_pkey; +ALTER TABLE monitor_regions DROP COLUMN region_id; +ALTER TABLE regions DROP CONSTRAINT regions_owner_key_key; +ALTER TABLE regions DROP CONSTRAINT regions_pkey; +ALTER TABLE regions ADD PRIMARY KEY (key); +ALTER TABLE regions DROP COLUMN org_id; +ALTER TABLE regions DROP COLUMN id; +ALTER TABLE monitor_regions ALTER COLUMN region SET NOT NULL; +ALTER TABLE monitor_regions ADD PRIMARY KEY (monitor_id, region); +ALTER TABLE monitor_regions ADD FOREIGN KEY (region) REFERENCES regions (key); +ALTER TABLE agents ADD FOREIGN KEY (region) REFERENCES regions (key); +ALTER TABLE agents ADD CONSTRAINT agents_check CHECK ((kind = 'checker') = (region IS NOT NULL)); diff --git a/internal/migrations/sql/00018_platform_admins.sql b/internal/migrations/sql/00018_platform_admins.sql new file mode 100644 index 0000000..c213d90 --- /dev/null +++ b/internal/migrations/sql/00018_platform_admins.sql @@ -0,0 +1,8 @@ +-- +goose Up +-- Platform admins manage what all organizations share: platform regions, +-- checkers and status page servers. Granted with "api admin grant"; the +-- first user of a self-hosted installation becomes one at signup. +ALTER TABLE users ADD COLUMN is_admin boolean NOT NULL DEFAULT false; + +-- +goose Down +ALTER TABLE users DROP COLUMN is_admin; diff --git a/internal/store/agents.sql.go b/internal/store/agents.sql.go index c2fd43a..44218e6 100644 --- a/internal/store/agents.sql.go +++ b/internal/store/agents.sql.go @@ -7,21 +7,22 @@ package store import ( "context" + "time" "github.com/google/uuid" ) const createAgent = `-- name: CreateAgent :one -INSERT INTO agents (org_id, kind, name, region, token_hash, prefix) +INSERT INTO agents (org_id, kind, name, region_id, token_hash, prefix) VALUES ($1, $2, $3, $4, $5, $6) -RETURNING id, org_id, kind, name, region, token_hash, prefix, last_seen_at, release, created_at +RETURNING id, org_id, kind, name, token_hash, prefix, last_seen_at, release, created_at, region_id ` type CreateAgentParams struct { OrgID *uuid.UUID Kind string Name string - Region *string + RegionID *uuid.UUID TokenHash []byte Prefix string } @@ -31,7 +32,7 @@ func (q *Queries) CreateAgent(ctx context.Context, arg CreateAgentParams) (Agent arg.OrgID, arg.Kind, arg.Name, - arg.Region, + arg.RegionID, arg.TokenHash, arg.Prefix, ) @@ -41,74 +42,202 @@ func (q *Queries) CreateAgent(ctx context.Context, arg CreateAgentParams) (Agent &i.OrgID, &i.Kind, &i.Name, - &i.Region, &i.TokenHash, &i.Prefix, &i.LastSeenAt, &i.Release, &i.CreatedAt, + &i.RegionID, + ) + return i, err +} + +const createRegion = `-- name: CreateRegion :one +INSERT INTO regions (org_id, key, name) VALUES ($1, $2, $3) +RETURNING key, name, created_at, id, org_id +` + +type CreateRegionParams struct { + OrgID *uuid.UUID + Key string + Name string +} + +func (q *Queries) CreateRegion(ctx context.Context, arg CreateRegionParams) (Region, error) { + row := q.db.QueryRow(ctx, createRegion, arg.OrgID, arg.Key, arg.Name) + var i Region + err := row.Scan( + &i.Key, + &i.Name, + &i.CreatedAt, + &i.ID, + &i.OrgID, ) return i, err } const deleteAgent = `-- name: DeleteAgent :execrows -DELETE FROM agents WHERE id = $1 +DELETE FROM agents WHERE id = $1 AND org_id IS NOT DISTINCT FROM $2::uuid ` -func (q *Queries) DeleteAgent(ctx context.Context, id uuid.UUID) (int64, error) { - result, err := q.db.Exec(ctx, deleteAgent, id) +type DeleteAgentParams struct { + ID uuid.UUID + OrgID *uuid.UUID +} + +func (q *Queries) DeleteAgent(ctx context.Context, arg DeleteAgentParams) (int64, error) { + result, err := q.db.Exec(ctx, deleteAgent, arg.ID, arg.OrgID) if err != nil { return 0, err } return result.RowsAffected(), nil } -const getAgentByHash = `-- name: GetAgentByHash :one -SELECT id, org_id, kind, name, region, token_hash, prefix, last_seen_at, release, created_at FROM agents WHERE token_hash = $1 +const deleteRegion = `-- name: DeleteRegion :execrows +DELETE FROM regions WHERE id = $1 ` -func (q *Queries) GetAgentByHash(ctx context.Context, tokenHash []byte) (Agent, error) { +func (q *Queries) DeleteRegion(ctx context.Context, id uuid.UUID) (int64, error) { + result, err := q.db.Exec(ctx, deleteRegion, id) + if err != nil { + return 0, err + } + return result.RowsAffected(), nil +} + +const ensurePlatformRegion = `-- name: EnsurePlatformRegion :one +INSERT INTO regions (org_id, key, name) +VALUES (NULL, $1, coalesce(nullif($2::text, ''), $1)) +ON CONFLICT ON CONSTRAINT regions_owner_key_key +DO UPDATE SET name = CASE WHEN $2::text = '' THEN regions.name ELSE EXCLUDED.name END +RETURNING key, name, created_at, id, org_id +` + +type EnsurePlatformRegionParams struct { + Key string + Name string +} + +// An empty name names a new region after its key and keeps an existing name. +func (q *Queries) EnsurePlatformRegion(ctx context.Context, arg EnsurePlatformRegionParams) (Region, error) { + row := q.db.QueryRow(ctx, ensurePlatformRegion, arg.Key, arg.Name) + var i Region + err := row.Scan( + &i.Key, + &i.Name, + &i.CreatedAt, + &i.ID, + &i.OrgID, + ) + return i, err +} + +const getAgentByHash = `-- name: GetAgentByHash :one +SELECT a.id, a.org_id, a.kind, a.name, a.token_hash, a.prefix, a.last_seen_at, a.release, a.created_at, a.region_id, r.key AS region_key, r.name AS region_name +FROM agents a +LEFT JOIN regions r ON r.id = a.region_id +WHERE a.token_hash = $1 +` + +type GetAgentByHashRow struct { + ID uuid.UUID + OrgID *uuid.UUID + Kind string + Name string + TokenHash []byte + Prefix string + LastSeenAt *time.Time + Release *string + CreatedAt time.Time + RegionID *uuid.UUID + RegionKey *string + RegionName *string +} + +// System scope. +func (q *Queries) GetAgentByHash(ctx context.Context, tokenHash []byte) (GetAgentByHashRow, error) { row := q.db.QueryRow(ctx, getAgentByHash, tokenHash) - var i Agent + var i GetAgentByHashRow err := row.Scan( &i.ID, &i.OrgID, &i.Kind, &i.Name, - &i.Region, &i.TokenHash, &i.Prefix, &i.LastSeenAt, &i.Release, &i.CreatedAt, + &i.RegionID, + &i.RegionKey, + &i.RegionName, + ) + return i, err +} + +const getRegion = `-- name: GetRegion :one +SELECT key, name, created_at, id, org_id FROM regions WHERE id = $1 +` + +func (q *Queries) GetRegion(ctx context.Context, id uuid.UUID) (Region, error) { + row := q.db.QueryRow(ctx, getRegion, id) + var i Region + err := row.Scan( + &i.Key, + &i.Name, + &i.CreatedAt, + &i.ID, + &i.OrgID, ) return i, err } const listAgents = `-- name: ListAgents :many -SELECT id, org_id, kind, name, region, token_hash, prefix, last_seen_at, release, created_at FROM agents ORDER BY kind, region, name +SELECT a.id, a.org_id, a.kind, a.name, a.token_hash, a.prefix, a.last_seen_at, a.release, a.created_at, a.region_id, r.key AS region_key, r.name AS region_name +FROM agents a +LEFT JOIN regions r ON r.id = a.region_id +WHERE a.org_id IS NOT DISTINCT FROM $1::uuid +ORDER BY a.kind, r.name, a.name ` -func (q *Queries) ListAgents(ctx context.Context) ([]Agent, error) { - rows, err := q.db.Query(ctx, listAgents) +type ListAgentsRow struct { + ID uuid.UUID + OrgID *uuid.UUID + Kind string + Name string + TokenHash []byte + Prefix string + LastSeenAt *time.Time + Release *string + CreatedAt time.Time + RegionID *uuid.UUID + RegionKey *string + RegionName *string +} + +// Agents owned by org, or platform agents when org is NULL. +func (q *Queries) ListAgents(ctx context.Context, orgID *uuid.UUID) ([]ListAgentsRow, error) { + rows, err := q.db.Query(ctx, listAgents, orgID) if err != nil { return nil, err } defer rows.Close() - items := []Agent{} + items := []ListAgentsRow{} for rows.Next() { - var i Agent + var i ListAgentsRow if err := rows.Scan( &i.ID, &i.OrgID, &i.Kind, &i.Name, - &i.Region, &i.TokenHash, &i.Prefix, &i.LastSeenAt, &i.Release, &i.CreatedAt, + &i.RegionID, + &i.RegionKey, + &i.RegionName, ); err != nil { return nil, err } @@ -120,12 +249,12 @@ func (q *Queries) ListAgents(ctx context.Context) ([]Agent, error) { return items, nil } -const listRegions = `-- name: ListRegions :many -SELECT key, name, created_at FROM regions ORDER BY key +const listPlatformRegions = `-- name: ListPlatformRegions :many +SELECT key, name, created_at, id, org_id FROM regions WHERE org_id IS NULL ORDER BY name, key ` -func (q *Queries) ListRegions(ctx context.Context) ([]Region, error) { - rows, err := q.db.Query(ctx, listRegions) +func (q *Queries) ListPlatformRegions(ctx context.Context) ([]Region, error) { + rows, err := q.db.Query(ctx, listPlatformRegions) if err != nil { return nil, err } @@ -133,7 +262,45 @@ func (q *Queries) ListRegions(ctx context.Context) ([]Region, error) { items := []Region{} for rows.Next() { var i Region - if err := rows.Scan(&i.Key, &i.Name, &i.CreatedAt); err != nil { + if err := rows.Scan( + &i.Key, + &i.Name, + &i.CreatedAt, + &i.ID, + &i.OrgID, + ); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} + +const listVisibleRegions = `-- name: ListVisibleRegions :many +SELECT key, name, created_at, id, org_id FROM regions ORDER BY org_id IS NULL, name, key +` + +// Row-level security limits this to platform regions and the scope's org; +// the org's own regions come first. +func (q *Queries) ListVisibleRegions(ctx context.Context) ([]Region, error) { + rows, err := q.db.Query(ctx, listVisibleRegions) + if err != nil { + return nil, err + } + defer rows.Close() + items := []Region{} + for rows.Next() { + var i Region + if err := rows.Scan( + &i.Key, + &i.Name, + &i.CreatedAt, + &i.ID, + &i.OrgID, + ); err != nil { return nil, err } items = append(items, i) @@ -158,22 +325,3 @@ func (q *Queries) TouchAgent(ctx context.Context, arg TouchAgentParams) error { _, err := q.db.Exec(ctx, touchAgent, arg.ID, arg.Release) return err } - -const upsertRegion = `-- name: UpsertRegion :one -INSERT INTO regions (key, name) VALUES ($1, coalesce(nullif($2::text, ''), $1)) -ON CONFLICT (key) DO UPDATE SET name = CASE WHEN $2::text = '' THEN regions.name ELSE EXCLUDED.name END -RETURNING key, name, created_at -` - -type UpsertRegionParams struct { - Key string - Name string -} - -// An empty name names a new region after its key and keeps an existing name. -func (q *Queries) UpsertRegion(ctx context.Context, arg UpsertRegionParams) (Region, error) { - row := q.db.QueryRow(ctx, upsertRegion, arg.Key, arg.Name) - var i Region - err := row.Scan(&i.Key, &i.Name, &i.CreatedAt) - return i, err -} diff --git a/internal/store/models.go b/internal/store/models.go index 61049c5..9fc0e79 100644 --- a/internal/store/models.go +++ b/internal/store/models.go @@ -15,12 +15,12 @@ type Agent struct { OrgID *uuid.UUID Kind string Name string - Region *string TokenHash []byte Prefix string LastSeenAt *time.Time Release *string CreatedAt time.Time + RegionID *uuid.UUID } type ApiToken struct { @@ -116,7 +116,7 @@ type Monitor struct { type MonitorRegion struct { MonitorID uuid.UUID OrgID uuid.UUID - Region string + RegionID uuid.UUID } type Notification struct { @@ -166,6 +166,8 @@ type Region struct { Key string Name string CreatedAt time.Time + ID uuid.UUID + OrgID *uuid.UUID } type Role struct { @@ -215,6 +217,7 @@ type User struct { TotpSecret []byte TotpEnabledAt *time.Time Locale *string + IsAdmin bool } type UserIdentity struct { diff --git a/internal/store/monitors.sql.go b/internal/store/monitors.sql.go index f41a228..ca70fdc 100644 --- a/internal/store/monitors.sql.go +++ b/internal/store/monitors.sql.go @@ -12,27 +12,27 @@ import ( ) const addMonitorRegion = `-- name: AddMonitorRegion :exec -INSERT INTO monitor_regions (monitor_id, org_id, region) VALUES ($1, $2, $3) +INSERT INTO monitor_regions (monitor_id, org_id, region_id) VALUES ($1, $2, $3) ` type AddMonitorRegionParams struct { MonitorID uuid.UUID OrgID uuid.UUID - Region string + RegionID uuid.UUID } func (q *Queries) AddMonitorRegion(ctx context.Context, arg AddMonitorRegionParams) error { - _, err := q.db.Exec(ctx, addMonitorRegion, arg.MonitorID, arg.OrgID, arg.Region) + _, err := q.db.Exec(ctx, addMonitorRegion, arg.MonitorID, arg.OrgID, arg.RegionID) return err } const allMonitorRegions = `-- name: AllMonitorRegions :many -SELECT monitor_id, region FROM monitor_regions +SELECT monitor_id, region_id FROM monitor_regions ` type AllMonitorRegionsRow struct { MonitorID uuid.UUID - Region string + RegionID uuid.UUID } func (q *Queries) AllMonitorRegions(ctx context.Context) ([]AllMonitorRegionsRow, error) { @@ -44,7 +44,7 @@ func (q *Queries) AllMonitorRegions(ctx context.Context) ([]AllMonitorRegionsRow items := []AllMonitorRegionsRow{} for rows.Next() { var i AllMonitorRegionsRow - if err := rows.Scan(&i.MonitorID, &i.Region); err != nil { + if err := rows.Scan(&i.MonitorID, &i.RegionID); err != nil { return nil, err } items = append(items, i) @@ -149,7 +149,7 @@ func (q *Queries) GetMonitor(ctx context.Context, id uuid.UUID) (Monitor, error) } const listEnabledMonitorsForSchedule = `-- name: ListEnabledMonitorsForSchedule :many -SELECT m.id, m.interval_seconds, array_agg(r.region ORDER BY r.region)::text[] AS regions +SELECT m.id, m.interval_seconds, array_agg(r.region_id::text ORDER BY r.region_id)::text[] AS regions FROM monitors m JOIN monitor_regions r ON r.monitor_id = m.id WHERE m.enabled @@ -222,22 +222,22 @@ func (q *Queries) ListMonitors(ctx context.Context) ([]Monitor, error) { } const monitorRegions = `-- name: MonitorRegions :many -SELECT region FROM monitor_regions WHERE monitor_id = $1 ORDER BY region +SELECT region_id FROM monitor_regions WHERE monitor_id = $1 ORDER BY region_id ` -func (q *Queries) MonitorRegions(ctx context.Context, monitorID uuid.UUID) ([]string, error) { +func (q *Queries) MonitorRegions(ctx context.Context, monitorID uuid.UUID) ([]uuid.UUID, error) { rows, err := q.db.Query(ctx, monitorRegions, monitorID) if err != nil { return nil, err } defer rows.Close() - items := []string{} + items := []uuid.UUID{} for rows.Next() { - var region string - if err := rows.Scan(®ion); err != nil { + var region_id uuid.UUID + if err := rows.Scan(®ion_id); err != nil { return nil, err } - items = append(items, region) + items = append(items, region_id) } if err := rows.Err(); err != nil { return nil, err @@ -247,19 +247,22 @@ func (q *Queries) MonitorRegions(ctx context.Context, monitorID uuid.UUID) ([]st const monitorsForJobs = `-- name: MonitorsForJobs :many SELECT m.id, m.org_id, m.name, m.type, m.target, m.interval_seconds, m.timeout_ms, m.config, m.enabled, m.created_at, m.updated_at, m.confirmations FROM monitors m -JOIN monitor_regions r ON r.monitor_id = m.id AND r.region = $1 +JOIN monitor_regions r ON r.monitor_id = m.id AND r.region_id = $1 WHERE m.id = ANY ($2::uuid[]) AND m.enabled + AND ($3::uuid IS NULL OR m.org_id = $3) ` type MonitorsForJobsParams struct { - Region string - Ids []uuid.UUID + RegionID uuid.UUID + Ids []uuid.UUID + AgentOrg *uuid.UUID } // System scope: monitors to hand to a checker of region, skipping ones that -// were disabled, deleted or moved out of the region since dispatch. +// were disabled, deleted or moved out of the region since dispatch. An +// org-owned checker only ever sees its org's monitors. func (q *Queries) MonitorsForJobs(ctx context.Context, arg MonitorsForJobsParams) ([]Monitor, error) { - rows, err := q.db.Query(ctx, monitorsForJobs, arg.Region, arg.Ids) + rows, err := q.db.Query(ctx, monitorsForJobs, arg.RegionID, arg.Ids, arg.AgentOrg) if err != nil { return nil, err } @@ -293,15 +296,17 @@ func (q *Queries) MonitorsForJobs(ctx context.Context, arg MonitorsForJobsParams const monitorsForResults = `-- name: MonitorsForResults :many SELECT m.id, m.org_id, m.name, m.target, m.interval_seconds, m.confirmations, - (SELECT array_agg(r2.region ORDER BY r2.region) FROM monitor_regions r2 WHERE r2.monitor_id = m.id)::text[] AS regions + (SELECT array_agg(r2.region_id::text ORDER BY r2.region_id) FROM monitor_regions r2 WHERE r2.monitor_id = m.id)::text[] AS regions FROM monitors m -JOIN monitor_regions r ON r.monitor_id = m.id AND r.region = $1 +JOIN monitor_regions r ON r.monitor_id = m.id AND r.region_id = $1 WHERE m.id = ANY ($2::uuid[]) AND m.enabled + AND ($3::uuid IS NULL OR m.org_id = $3) ` type MonitorsForResultsParams struct { - Region string - Ids []uuid.UUID + RegionID uuid.UUID + Ids []uuid.UUID + AgentOrg *uuid.UUID } type MonitorsForResultsRow struct { @@ -317,7 +322,7 @@ type MonitorsForResultsRow struct { // System scope: monitors a checker of region may report, with every region // they are assigned to, for evaluation. func (q *Queries) MonitorsForResults(ctx context.Context, arg MonitorsForResultsParams) ([]MonitorsForResultsRow, error) { - rows, err := q.db.Query(ctx, monitorsForResults, arg.Region, arg.Ids) + rows, err := q.db.Query(ctx, monitorsForResults, arg.RegionID, arg.Ids, arg.AgentOrg) if err != nil { return nil, err } diff --git a/internal/store/querier.go b/internal/store/querier.go index d8570f9..d88bdd4 100644 --- a/internal/store/querier.go +++ b/internal/store/querier.go @@ -31,11 +31,12 @@ type Querier interface { CreateInvitation(ctx context.Context, arg CreateInvitationParams) (Invitation, error) CreateMonitor(ctx context.Context, arg CreateMonitorParams) (Monitor, error) CreateOrg(ctx context.Context, arg CreateOrgParams) (Org, error) + CreateRegion(ctx context.Context, arg CreateRegionParams) (Region, error) CreateRole(ctx context.Context, arg CreateRoleParams) (Role, error) CreateSSOProvider(ctx context.Context, arg CreateSSOProviderParams) (SsoProvider, error) CreateUser(ctx context.Context, arg CreateUserParams) (User, error) DeleteAPIToken(ctx context.Context, id uuid.UUID) (int64, error) - DeleteAgent(ctx context.Context, id uuid.UUID) (int64, error) + DeleteAgent(ctx context.Context, arg DeleteAgentParams) (int64, error) DeleteAssignment(ctx context.Context, id uuid.UUID) (int64, error) DeleteChannel(ctx context.Context, id uuid.UUID) (int64, error) DeleteInvitation(ctx context.Context, id uuid.UUID) (int64, error) @@ -43,15 +44,19 @@ type Querier interface { DeleteMonitorRegions(ctx context.Context, monitorID uuid.UUID) error DeleteOrg(ctx context.Context, id uuid.UUID) (int64, error) DeleteRecoveryCodes(ctx context.Context, userID uuid.UUID) error + DeleteRegion(ctx context.Context, id uuid.UUID) (int64, error) DeleteRole(ctx context.Context, id uuid.UUID) (int64, error) DeleteSSOProvider(ctx context.Context, id uuid.UUID) (int64, error) DeleteUser(ctx context.Context, id uuid.UUID) (int64, error) DisableTOTP(ctx context.Context, id uuid.UUID) error EnableTOTP(ctx context.Context, arg EnableTOTPParams) error EnqueueNotification(ctx context.Context, arg EnqueueNotificationParams) error + // An empty name names a new region after its key and keeps an existing name. + EnsurePlatformRegion(ctx context.Context, arg EnsurePlatformRegionParams) (Region, error) GetAPIToken(ctx context.Context, id uuid.UUID) (ApiToken, error) GetAPITokenByHash(ctx context.Context, tokenHash []byte) (ApiToken, error) - GetAgentByHash(ctx context.Context, tokenHash []byte) (Agent, error) + // System scope. + GetAgentByHash(ctx context.Context, tokenHash []byte) (GetAgentByHashRow, error) GetAssignment(ctx context.Context, id uuid.UUID) (RoleAssignment, error) GetChannel(ctx context.Context, id uuid.UUID) (NotificationChannel, error) GetIdentity(ctx context.Context, arg GetIdentityParams) (UserIdentity, error) @@ -61,6 +66,7 @@ type Querier interface { GetMonitor(ctx context.Context, id uuid.UUID) (Monitor, error) GetOrg(ctx context.Context, id uuid.UUID) (Org, error) GetOrgBySlug(ctx context.Context, slug string) (Org, error) + GetRegion(ctx context.Context, id uuid.UUID) (Region, error) GetRole(ctx context.Context, id uuid.UUID) (Role, error) GetSSOProvider(ctx context.Context, id uuid.UUID) (SsoProvider, error) GetUser(ctx context.Context, id uuid.UUID) (User, error) @@ -75,7 +81,8 @@ type Querier interface { LatestResults(ctx context.Context, orgID uuid.UUID) ([]LatestResultsRow, error) LatestResultsForMonitor(ctx context.Context, arg LatestResultsForMonitorParams) ([]LatestResultsForMonitorRow, error) ListAPITokens(ctx context.Context, arg ListAPITokensParams) ([]ListAPITokensRow, error) - ListAgents(ctx context.Context) ([]Agent, error) + // Agents owned by org, or platform agents when org is NULL. + ListAgents(ctx context.Context, orgID *uuid.UUID) ([]ListAgentsRow, error) ListAssignments(ctx context.Context, orgID uuid.UUID) ([]ListAssignmentsRow, error) ListChannels(ctx context.Context) ([]NotificationChannel, error) ListEnabledChannelIDs(ctx context.Context, orgID uuid.UUID) ([]uuid.UUID, error) @@ -88,19 +95,24 @@ type Querier interface { ListOrgMembers(ctx context.Context, orgID uuid.UUID) ([]ListOrgMembersRow, error) ListOrgs(ctx context.Context) ([]Org, error) ListPendingInvitations(ctx context.Context) ([]ListPendingInvitationsRow, error) - ListRegions(ctx context.Context) ([]Region, error) + ListPlatformRegions(ctx context.Context) ([]Region, error) ListRoles(ctx context.Context) ([]Role, error) ListSSOProviders(ctx context.Context) ([]SsoProvider, error) ListUserIdentitiesInOrg(ctx context.Context, userID uuid.UUID) ([]ListUserIdentitiesInOrgRow, error) ListUserOrgs(ctx context.Context, userID uuid.UUID) ([]ListUserOrgsRow, error) + // Row-level security limits this to platform regions and the scope's org; + // the org's own regions come first. + ListVisibleRegions(ctx context.Context) ([]Region, error) + MakeAdmin(ctx context.Context, id uuid.UUID) error MarkInvitationAccepted(ctx context.Context, id uuid.UUID) (int64, error) MarkNotificationFailed(ctx context.Context, arg MarkNotificationFailedParams) error MarkNotificationSent(ctx context.Context, id uuid.UUID) error // Every role a member holds, with the scope it applies to. MemberGrants(ctx context.Context, arg MemberGrantsParams) ([]MemberGrantsRow, error) - MonitorRegions(ctx context.Context, monitorID uuid.UUID) ([]string, error) + MonitorRegions(ctx context.Context, monitorID uuid.UUID) ([]uuid.UUID, error) // System scope: monitors to hand to a checker of region, skipping ones that - // were disabled, deleted or moved out of the region since dispatch. + // were disabled, deleted or moved out of the region since dispatch. An + // org-owned checker only ever sees its org's monitors. MonitorsForJobs(ctx context.Context, arg MonitorsForJobsParams) ([]Monitor, error) // System scope: monitors a checker of region may report, with every region // they are assigned to, for evaluation. @@ -113,6 +125,7 @@ type Querier interface { RemoveMembership(ctx context.Context, arg RemoveMembershipParams) (int64, error) ResolveIncident(ctx context.Context, arg ResolveIncidentParams) (Incident, error) SetPasswordHash(ctx context.Context, arg SetPasswordHashParams) error + SetUserAdmin(ctx context.Context, arg SetUserAdminParams) (int64, error) SetUserLocale(ctx context.Context, arg SetUserLocaleParams) error TouchAPIToken(ctx context.Context, id uuid.UUID) error TouchAgent(ctx context.Context, arg TouchAgentParams) error @@ -122,8 +135,6 @@ type Querier interface { UpdateOrgPolicy(ctx context.Context, arg UpdateOrgPolicyParams) (Org, error) UpdateRole(ctx context.Context, arg UpdateRoleParams) (Role, error) UpdateSSOProvider(ctx context.Context, arg UpdateSSOProviderParams) (SsoProvider, error) - // An empty name names a new region after its key and keeps an existing name. - UpsertRegion(ctx context.Context, arg UpsertRegionParams) (Region, error) // Uptime per monitor from the hourly aggregate, including the not yet // materialized most recent hours (real-time aggregation). UptimeSince(ctx context.Context, arg UptimeSinceParams) ([]UptimeSinceRow, error) diff --git a/internal/store/queries/agents.sql b/internal/store/queries/agents.sql index e1b1282..4bed5ef 100644 --- a/internal/store/queries/agents.sql +++ b/internal/store/queries/agents.sql @@ -1,25 +1,51 @@ --- name: UpsertRegion :one --- An empty name names a new region after its key and keeps an existing name. -INSERT INTO regions (key, name) VALUES (sqlc.arg(key), coalesce(nullif(sqlc.arg(name)::text, ''), sqlc.arg(key))) -ON CONFLICT (key) DO UPDATE SET name = CASE WHEN sqlc.arg(name)::text = '' THEN regions.name ELSE EXCLUDED.name END +-- name: CreateRegion :one +INSERT INTO regions (org_id, key, name) VALUES ($1, $2, $3) RETURNING *; --- name: ListRegions :many -SELECT * FROM regions ORDER BY key; +-- name: EnsurePlatformRegion :one +-- An empty name names a new region after its key and keeps an existing name. +INSERT INTO regions (org_id, key, name) +VALUES (NULL, sqlc.arg(key), coalesce(nullif(sqlc.arg(name)::text, ''), sqlc.arg(key))) +ON CONFLICT ON CONSTRAINT regions_owner_key_key +DO UPDATE SET name = CASE WHEN sqlc.arg(name)::text = '' THEN regions.name ELSE EXCLUDED.name END +RETURNING *; + +-- name: GetRegion :one +SELECT * FROM regions WHERE id = $1; + +-- name: ListVisibleRegions :many +-- Row-level security limits this to platform regions and the scope's org; +-- the org's own regions come first. +SELECT * FROM regions ORDER BY org_id IS NULL, name, key; + +-- name: ListPlatformRegions :many +SELECT * FROM regions WHERE org_id IS NULL ORDER BY name, key; + +-- name: DeleteRegion :execrows +DELETE FROM regions WHERE id = $1; -- name: CreateAgent :one -INSERT INTO agents (org_id, kind, name, region, token_hash, prefix) +INSERT INTO agents (org_id, kind, name, region_id, token_hash, prefix) VALUES ($1, $2, $3, $4, $5, $6) RETURNING *; -- name: GetAgentByHash :one -SELECT * FROM agents WHERE token_hash = $1; +-- System scope. +SELECT a.*, r.key AS region_key, r.name AS region_name +FROM agents a +LEFT JOIN regions r ON r.id = a.region_id +WHERE a.token_hash = $1; -- name: ListAgents :many -SELECT * FROM agents ORDER BY kind, region, name; +-- Agents owned by org, or platform agents when org is NULL. +SELECT a.*, r.key AS region_key, r.name AS region_name +FROM agents a +LEFT JOIN regions r ON r.id = a.region_id +WHERE a.org_id IS NOT DISTINCT FROM sqlc.narg(org_id)::uuid +ORDER BY a.kind, r.name, a.name; -- name: DeleteAgent :execrows -DELETE FROM agents WHERE id = $1; +DELETE FROM agents WHERE id = sqlc.arg(id) AND org_id IS NOT DISTINCT FROM sqlc.narg(org_id)::uuid; -- name: TouchAgent :exec UPDATE agents SET last_seen_at = now(), release = $2 diff --git a/internal/store/queries/monitors.sql b/internal/store/queries/monitors.sql index c14bbab..5674820 100644 --- a/internal/store/queries/monitors.sql +++ b/internal/store/queries/monitors.sql @@ -19,21 +19,21 @@ SELECT * FROM monitors WHERE id = $1; SELECT * FROM monitors ORDER BY name; -- name: MonitorRegions :many -SELECT region FROM monitor_regions WHERE monitor_id = $1 ORDER BY region; +SELECT region_id FROM monitor_regions WHERE monitor_id = $1 ORDER BY region_id; -- name: AllMonitorRegions :many -SELECT monitor_id, region FROM monitor_regions; +SELECT monitor_id, region_id FROM monitor_regions; -- name: DeleteMonitorRegions :exec DELETE FROM monitor_regions WHERE monitor_id = $1; -- name: AddMonitorRegion :exec -INSERT INTO monitor_regions (monitor_id, org_id, region) VALUES ($1, $2, $3); +INSERT INTO monitor_regions (monitor_id, org_id, region_id) VALUES ($1, $2, $3); -- name: ListEnabledMonitorsForSchedule :many -- System scope: every enabled monitor with its regions, for reconciling the -- schedule. -SELECT m.id, m.interval_seconds, array_agg(r.region ORDER BY r.region)::text[] AS regions +SELECT m.id, m.interval_seconds, array_agg(r.region_id::text ORDER BY r.region_id)::text[] AS regions FROM monitors m JOIN monitor_regions r ON r.monitor_id = m.id WHERE m.enabled @@ -41,16 +41,19 @@ GROUP BY m.id, m.interval_seconds; -- name: MonitorsForJobs :many -- System scope: monitors to hand to a checker of region, skipping ones that --- were disabled, deleted or moved out of the region since dispatch. +-- were disabled, deleted or moved out of the region since dispatch. An +-- org-owned checker only ever sees its org's monitors. SELECT m.* FROM monitors m -JOIN monitor_regions r ON r.monitor_id = m.id AND r.region = sqlc.arg(region) -WHERE m.id = ANY (sqlc.arg(ids)::uuid[]) AND m.enabled; +JOIN monitor_regions r ON r.monitor_id = m.id AND r.region_id = sqlc.arg(region_id) +WHERE m.id = ANY (sqlc.arg(ids)::uuid[]) AND m.enabled + AND (sqlc.narg(agent_org)::uuid IS NULL OR m.org_id = sqlc.narg(agent_org)); -- name: MonitorsForResults :many -- System scope: monitors a checker of region may report, with every region -- they are assigned to, for evaluation. SELECT m.id, m.org_id, m.name, m.target, m.interval_seconds, m.confirmations, - (SELECT array_agg(r2.region ORDER BY r2.region) FROM monitor_regions r2 WHERE r2.monitor_id = m.id)::text[] AS regions + (SELECT array_agg(r2.region_id::text ORDER BY r2.region_id) FROM monitor_regions r2 WHERE r2.monitor_id = m.id)::text[] AS regions FROM monitors m -JOIN monitor_regions r ON r.monitor_id = m.id AND r.region = sqlc.arg(region) -WHERE m.id = ANY (sqlc.arg(ids)::uuid[]) AND m.enabled; +JOIN monitor_regions r ON r.monitor_id = m.id AND r.region_id = sqlc.arg(region_id) +WHERE m.id = ANY (sqlc.arg(ids)::uuid[]) AND m.enabled + AND (sqlc.narg(agent_org)::uuid IS NULL OR m.org_id = sqlc.narg(agent_org)); diff --git a/internal/store/queries/users.sql b/internal/store/queries/users.sql index a4a951a..824f1be 100644 --- a/internal/store/queries/users.sql +++ b/internal/store/queries/users.sql @@ -25,3 +25,9 @@ DELETE FROM users WHERE id = $1; -- name: SetUserLocale :exec UPDATE users SET locale = $2, updated_at = now() WHERE id = $1; + +-- name: SetUserAdmin :execrows +UPDATE users SET is_admin = $2, updated_at = now() WHERE email = $1; + +-- name: MakeAdmin :exec +UPDATE users SET is_admin = true, updated_at = now() WHERE id = $1; diff --git a/internal/store/users.sql.go b/internal/store/users.sql.go index e734baa..d74976a 100644 --- a/internal/store/users.sql.go +++ b/internal/store/users.sql.go @@ -24,7 +24,7 @@ func (q *Queries) AnyUserExists(ctx context.Context) (bool, error) { const createUser = `-- name: CreateUser :one INSERT INTO users (email, display_name, password_hash, locale) VALUES ($1, $2, $3, $4) -RETURNING id, email, display_name, password_hash, disabled_at, created_at, updated_at, totp_secret, totp_enabled_at, locale +RETURNING id, email, display_name, password_hash, disabled_at, created_at, updated_at, totp_secret, totp_enabled_at, locale, is_admin ` type CreateUserParams struct { @@ -53,6 +53,7 @@ func (q *Queries) CreateUser(ctx context.Context, arg CreateUserParams) (User, e &i.TotpSecret, &i.TotpEnabledAt, &i.Locale, + &i.IsAdmin, ) return i, err } @@ -93,7 +94,7 @@ func (q *Queries) EnableTOTP(ctx context.Context, arg EnableTOTPParams) error { } const getUser = `-- name: GetUser :one -SELECT id, email, display_name, password_hash, disabled_at, created_at, updated_at, totp_secret, totp_enabled_at, locale FROM users WHERE id = $1 +SELECT id, email, display_name, password_hash, disabled_at, created_at, updated_at, totp_secret, totp_enabled_at, locale, is_admin FROM users WHERE id = $1 ` func (q *Queries) GetUser(ctx context.Context, id uuid.UUID) (User, error) { @@ -110,12 +111,13 @@ func (q *Queries) GetUser(ctx context.Context, id uuid.UUID) (User, error) { &i.TotpSecret, &i.TotpEnabledAt, &i.Locale, + &i.IsAdmin, ) return i, err } const getUserByEmail = `-- name: GetUserByEmail :one -SELECT id, email, display_name, password_hash, disabled_at, created_at, updated_at, totp_secret, totp_enabled_at, locale FROM users WHERE email = $1 +SELECT id, email, display_name, password_hash, disabled_at, created_at, updated_at, totp_secret, totp_enabled_at, locale, is_admin FROM users WHERE email = $1 ` func (q *Queries) GetUserByEmail(ctx context.Context, email string) (User, error) { @@ -132,10 +134,20 @@ func (q *Queries) GetUserByEmail(ctx context.Context, email string) (User, error &i.TotpSecret, &i.TotpEnabledAt, &i.Locale, + &i.IsAdmin, ) return i, err } +const makeAdmin = `-- name: MakeAdmin :exec +UPDATE users SET is_admin = true, updated_at = now() WHERE id = $1 +` + +func (q *Queries) MakeAdmin(ctx context.Context, id uuid.UUID) error { + _, err := q.db.Exec(ctx, makeAdmin, id) + return err +} + const setPasswordHash = `-- name: SetPasswordHash :exec UPDATE users SET password_hash = $2, updated_at = now() WHERE id = $1 ` @@ -150,6 +162,23 @@ func (q *Queries) SetPasswordHash(ctx context.Context, arg SetPasswordHashParams return err } +const setUserAdmin = `-- name: SetUserAdmin :execrows +UPDATE users SET is_admin = $2, updated_at = now() WHERE email = $1 +` + +type SetUserAdminParams struct { + Email string + IsAdmin bool +} + +func (q *Queries) SetUserAdmin(ctx context.Context, arg SetUserAdminParams) (int64, error) { + result, err := q.db.Exec(ctx, setUserAdmin, arg.Email, arg.IsAdmin) + if err != nil { + return 0, err + } + return result.RowsAffected(), nil +} + const setUserLocale = `-- name: SetUserLocale :exec UPDATE users SET locale = $2, updated_at = now() WHERE id = $1 ` diff --git a/internal/web/console.templ b/internal/web/console.templ index 319f9fa..1740aa1 100644 --- a/internal/web/console.templ +++ b/internal/web/console.templ @@ -19,6 +19,8 @@ type Me struct { Policy string // RecoveryCodesLeft counts unused TOTP recovery codes. RecoveryCodesLeft int + // IsAdmin marks platform admins. + IsAdmin bool } // Org is one entry of the organization switcher. @@ -52,10 +54,14 @@ templ consoleShell(p Page, me Me) { { i18n.T(ctx, "console.nav.tokens") } } if me.Can["org.manage"] { + { i18n.T(ctx, "console.nav.regions") } { i18n.T(ctx, "console.nav.org") } { i18n.T(ctx, "console.nav.sso") } } { i18n.T(ctx, "console.nav.security") } + if me.IsAdmin { + { i18n.T(ctx, "console.nav.admin") } + } @languageSwitch(p.Languages) diff --git a/internal/web/console_templ.go b/internal/web/console_templ.go index 21595a6..8acca37 100644 --- a/internal/web/console_templ.go +++ b/internal/web/console_templ.go @@ -28,6 +28,8 @@ type Me struct { Policy string // RecoveryCodesLeft counts unused TOTP recovery codes. RecoveryCodesLeft int + // IsAdmin marks platform admins. + IsAdmin bool } // Org is one entry of the organization switcher. @@ -85,7 +87,7 @@ func consoleShell(p Page, me Me) templ.Component { var templ_7745c5c3_Var3 string templ_7745c5c3_Var3, templ_7745c5c3_Err = templruntime.NewAttributeExpression(o.ID).Resolve(ctx) if templ_7745c5c3_Err != nil { - return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 40, Col: 27} + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 42, Col: 27} } _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var3) if templ_7745c5c3_Err != nil { @@ -108,7 +110,7 @@ func consoleShell(p Page, me Me) templ.Component { var templ_7745c5c3_Var4 string templ_7745c5c3_Var4, templ_7745c5c3_Err = templ.JoinStringErrs(o.Name) if templ_7745c5c3_Err != nil { - return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 40, Col: 73} + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 42, Col: 73} } _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var4)) if templ_7745c5c3_Err != nil { @@ -131,7 +133,7 @@ func consoleShell(p Page, me Me) templ.Component { var templ_7745c5c3_Var5 string templ_7745c5c3_Var5, templ_7745c5c3_Err = templ.JoinStringErrs(me.Orgs[0].Name) if templ_7745c5c3_Err != nil { - return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 44, Col: 47} + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 46, Col: 47} } _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var5)) if templ_7745c5c3_Err != nil { @@ -154,7 +156,7 @@ func consoleShell(p Page, me Me) templ.Component { var templ_7745c5c3_Var6 string templ_7745c5c3_Var6, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "console.nav.members")) if templ_7745c5c3_Err != nil { - return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 48, Col: 104} + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 50, Col: 104} } _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var6)) if templ_7745c5c3_Err != nil { @@ -167,7 +169,7 @@ func consoleShell(p Page, me Me) templ.Component { var templ_7745c5c3_Var7 string templ_7745c5c3_Var7, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "console.nav.roles")) if templ_7745c5c3_Err != nil { - return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 49, Col: 100} + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 51, Col: 100} } _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var7)) if templ_7745c5c3_Err != nil { @@ -186,7 +188,7 @@ func consoleShell(p Page, me Me) templ.Component { var templ_7745c5c3_Var8 string templ_7745c5c3_Var8, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "console.nav.tokens")) if templ_7745c5c3_Err != nil { - return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 52, Col: 102} + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 54, Col: 102} } _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var8)) if templ_7745c5c3_Err != nil { @@ -198,64 +200,100 @@ func consoleShell(p Page, me Me) templ.Component { } } if me.Can["org.manage"] { - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 17, "") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 17, "") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } var templ_7745c5c3_Var9 string - templ_7745c5c3_Var9, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "console.nav.org")) + templ_7745c5c3_Var9, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "console.nav.regions")) if templ_7745c5c3_Err != nil { - return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 55, Col: 96} + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 57, Col: 104} } _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var9)) if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 18, " ") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 18, " ") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } var templ_7745c5c3_Var10 string - templ_7745c5c3_Var10, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "console.nav.sso")) + templ_7745c5c3_Var10, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "console.nav.org")) if templ_7745c5c3_Err != nil { - return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 56, Col: 96} + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 58, Col: 96} } _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var10)) if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 19, " ") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 19, " ") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + var templ_7745c5c3_Var11 string + templ_7745c5c3_Var11, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "console.nav.sso")) + if templ_7745c5c3_Err != nil { + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 59, Col: 96} + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var11)) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 20, " ") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } } - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 20, "") - if templ_7745c5c3_Err != nil { - return templ_7745c5c3_Err - } - var templ_7745c5c3_Var11 string - templ_7745c5c3_Var11, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "console.nav.security")) - if templ_7745c5c3_Err != nil { - return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 58, Col: 105} - } - _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var11)) - if templ_7745c5c3_Err != nil { - return templ_7745c5c3_Err - } - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 21, " ") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 22, " ") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + if me.IsAdmin { + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 23, "") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + var templ_7745c5c3_Var13 string + templ_7745c5c3_Var13, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "console.nav.admin")) + if templ_7745c5c3_Err != nil { + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 63, Col: 93} + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var13)) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 24, " ") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 25, "") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } @@ -263,7 +301,7 @@ func consoleShell(p Page, me Me) templ.Component { if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 23, "") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 27, "") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } @@ -279,7 +317,7 @@ func consoleShell(p Page, me Me) templ.Component { return templ_7745c5c3_Err } } - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 24, "
") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 28, "
") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } @@ -291,7 +329,7 @@ func consoleShell(p Page, me Me) templ.Component { if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 25, "
") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 29, "
") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } @@ -322,7 +360,7 @@ func Dashboard(p Page, me Me) templ.Component { } ctx = templ.InitializeContext(ctx) ctx = templ.ClearChildren(ctx) - templ_7745c5c3_Var14 := templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) { + templ_7745c5c3_Var16 := templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) { templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context templ_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W) if !templ_7745c5c3_IsBuffer { @@ -334,39 +372,39 @@ func Dashboard(p Page, me Me) templ.Component { }() } ctx = templ.InitializeContext(ctx) - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 26, "

") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 30, "

") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - var templ_7745c5c3_Var15 string - templ_7745c5c3_Var15, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "console.monitors.title")) + var templ_7745c5c3_Var17 string + templ_7745c5c3_Var17, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "console.monitors.title")) if templ_7745c5c3_Err != nil { - return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 79, Col: 75} + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 85, Col: 75} } - _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var15)) + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var17)) if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 27, "

") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 31, "

") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - var templ_7745c5c3_Var16 string - templ_7745c5c3_Var16, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "console.monitors.empty")) + var templ_7745c5c3_Var18 string + templ_7745c5c3_Var18, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "console.monitors.empty")) if templ_7745c5c3_Err != nil { - return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 80, Col: 76} + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 86, Col: 76} } - _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var16)) + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var18)) if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 28, "

") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 32, "

") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } return nil }) - templ_7745c5c3_Err = consoleShell(p, me).Render(templ.WithChildren(ctx, templ_7745c5c3_Var14), templ_7745c5c3_Buffer) + templ_7745c5c3_Err = consoleShell(p, me).Render(templ.WithChildren(ctx, templ_7745c5c3_Var16), templ_7745c5c3_Buffer) if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } @@ -397,7 +435,7 @@ func Security(p Page, me Me, identities []Identity, canLink bool) templ.Componen } ctx = templ.InitializeContext(ctx) ctx = templ.ClearChildren(ctx) - templ_7745c5c3_Var18 := templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) { + templ_7745c5c3_Var20 := templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) { templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context templ_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W) if !templ_7745c5c3_IsBuffer { @@ -409,51 +447,51 @@ func Security(p Page, me Me, identities []Identity, canLink bool) templ.Componen }() } ctx = templ.InitializeContext(ctx) - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 29, "

") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 33, "

") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - var templ_7745c5c3_Var19 string - templ_7745c5c3_Var19, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "security.title")) + var templ_7745c5c3_Var21 string + templ_7745c5c3_Var21, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "security.title")) if templ_7745c5c3_Err != nil { - return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 92, Col: 72} + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 98, Col: 72} } - _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var19)) + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var21)) if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 30, "

") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 34, "

") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - var templ_7745c5c3_Var20 string - templ_7745c5c3_Var20, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "security.totp.heading")) + var templ_7745c5c3_Var22 string + templ_7745c5c3_Var22, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "security.totp.heading")) if templ_7745c5c3_Err != nil { - return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 94, Col: 114} + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 100, Col: 114} } - _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var20)) + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var22)) if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 31, "

") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 35, "") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } if me.TOTP { - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 32, "

● ") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 36, "

● ") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - var templ_7745c5c3_Var21 string - templ_7745c5c3_Var21, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "security.totp.active")) + var templ_7745c5c3_Var23 string + templ_7745c5c3_Var23, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "security.totp.active")) if templ_7745c5c3_Err != nil { - return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 96, Col: 98} + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 102, Col: 98} } - _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var21)) + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var23)) if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 33, "

") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 37, "

") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } @@ -461,25 +499,25 @@ func Security(p Page, me Me, identities []Identity, canLink bool) templ.Componen templ_7745c5c3_ElementWriter := templ_7745c5c3_Buffer templ_7745c5c3_Buffer := templ.GetBuffer() var templ_7745c5c3_ElementScripts []templ.ComponentScript - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 34, "

= 3)} - templ_7745c5c3_Err = templ.RenderCSSItems(ctx, templ_7745c5c3_ElementWriter, templ_7745c5c3_Var22...) + var templ_7745c5c3_Var24 = []any{"mb-6 text-sm", templ.KV("text-down", me.RecoveryCodesLeft < 3), templ.KV("text-muted", me.RecoveryCodesLeft >= 3)} + templ_7745c5c3_Err = templ.RenderCSSItems(ctx, templ_7745c5c3_ElementWriter, templ_7745c5c3_Var24...) if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - var templ_7745c5c3_Var23 string - templ_7745c5c3_Var23, templ_7745c5c3_Err = templruntime.NewAttributeExpression(templ.CSSClasses(templ_7745c5c3_Var22).String()).Resolve(ctx) + var templ_7745c5c3_Var25 string + templ_7745c5c3_Var25, templ_7745c5c3_Err = templruntime.NewAttributeExpression(templ.CSSClasses(templ_7745c5c3_Var24).String()).Resolve(ctx) if templ_7745c5c3_Err != nil { return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 1, Col: 0} } - _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var23) + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var25) if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 35, "\"") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 39, "\"") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } @@ -493,33 +531,33 @@ func Security(p Page, me Me, identities []Identity, canLink bool) templ.Componen } templ.ReleaseBuffer(templ_7745c5c3_Buffer) } - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 36, ">") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 40, ">") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - var templ_7745c5c3_Var24 string - templ_7745c5c3_Var24, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "security.recovery.left", "Count", me.RecoveryCodesLeft)) + var templ_7745c5c3_Var26 string + templ_7745c5c3_Var26, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "security.recovery.left", "Count", me.RecoveryCodesLeft)) if templ_7745c5c3_Err != nil { - return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 98, Col: 75} + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 104, Col: 75} } - _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var24)) + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var26)) if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 37, "

") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 41, "

") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - var templ_7745c5c3_Var25 string - templ_7745c5c3_Var25, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "security.recovery.regenerate")) + var templ_7745c5c3_Var27 string + templ_7745c5c3_Var27, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "security.recovery.regenerate")) if templ_7745c5c3_Err != nil { - return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 101, Col: 116} + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 107, Col: 116} } - _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var25)) + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var27)) if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 38, "
") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 42, "
") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } @@ -543,20 +581,20 @@ func Security(p Page, me Me, identities []Identity, canLink bool) templ.Componen if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 39, "
") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 43, "
") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - var templ_7745c5c3_Var26 string - templ_7745c5c3_Var26, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "security.totp.disable")) + var templ_7745c5c3_Var28 string + templ_7745c5c3_Var28, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "security.totp.disable")) if templ_7745c5c3_Err != nil { - return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 111, Col: 109} + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 117, Col: 109} } - _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var26)) + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var28)) if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 40, "
") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 44, "") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } @@ -576,51 +614,51 @@ func Security(p Page, me Me, identities []Identity, canLink bool) templ.Componen if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 41, "
") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 45, "") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } } else { - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 42, "

● ") - if templ_7745c5c3_Err != nil { - return templ_7745c5c3_Err - } - var templ_7745c5c3_Var27 string - templ_7745c5c3_Var27, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "security.totp.inactive")) - if templ_7745c5c3_Err != nil { - return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 120, Col: 105} - } - _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var27)) - if templ_7745c5c3_Err != nil { - return templ_7745c5c3_Err - } - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 43, "

") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } } - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 47, "

") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 51, "

") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - var templ_7745c5c3_Var30 string - templ_7745c5c3_Var30, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "security.sso.heading")) + var templ_7745c5c3_Var32 string + templ_7745c5c3_Var32, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "security.sso.heading")) if templ_7745c5c3_Err != nil { - return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 137, Col: 113} + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 143, Col: 113} } - _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var30)) + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var32)) if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 48, "

") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 52, "") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } if len(identities) == 0 { - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 49, "

") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 53, "

") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - var templ_7745c5c3_Var31 string - templ_7745c5c3_Var31, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "security.sso.none")) + var templ_7745c5c3_Var33 string + templ_7745c5c3_Var33, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "security.sso.none")) if templ_7745c5c3_Err != nil { - return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 139, Col: 73} + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 145, Col: 73} } - _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var31)) + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var33)) if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 50, "

") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 54, "

") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } } else { - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 51, "
    ") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 55, "
      ") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } for _, id := range identities { - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 52, "
    • ") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 56, "
    • ") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - var templ_7745c5c3_Var32 string - templ_7745c5c3_Var32, templ_7745c5c3_Err = templ.JoinStringErrs(id.Provider) + var templ_7745c5c3_Var34 string + templ_7745c5c3_Var34, templ_7745c5c3_Err = templ.JoinStringErrs(id.Provider) if templ_7745c5c3_Err != nil { - return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 143, Col: 69} + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 149, Col: 69} } - _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var32)) + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var34)) if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 53, "") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 57, "") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - var templ_7745c5c3_Var33 string - templ_7745c5c3_Var33, templ_7745c5c3_Err = templ.JoinStringErrs(id.Email) + var templ_7745c5c3_Var35 string + templ_7745c5c3_Var35, templ_7745c5c3_Err = templ.JoinStringErrs(id.Email) if templ_7745c5c3_Err != nil { - return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 143, Col: 131} + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 149, Col: 131} } - _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var33)) + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var35)) if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 54, "
    • ") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 58, "") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } } - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 55, "
    ") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 59, "
") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } } if canLink { - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 56, "") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 61, "\" class=\"inline-block border border-ink px-3 py-1.5 text-sm hover:bg-ink hover:text-paper\">") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - var templ_7745c5c3_Var35 string - templ_7745c5c3_Var35, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "security.sso.link")) + var templ_7745c5c3_Var37 string + templ_7745c5c3_Var37, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "security.sso.link")) if templ_7745c5c3_Err != nil { - return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 148, Col: 190} + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 154, Col: 190} } - _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var35)) + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var37)) if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 58, "") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 62, "") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } } - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 59, "
") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 63, "
") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } return nil }) - templ_7745c5c3_Err = consoleShell(p, me).Render(templ.WithChildren(ctx, templ_7745c5c3_Var18), templ_7745c5c3_Buffer) + templ_7745c5c3_Err = consoleShell(p, me).Render(templ.WithChildren(ctx, templ_7745c5c3_Var20), templ_7745c5c3_Buffer) if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } @@ -787,33 +825,33 @@ func recoveryOutput() templ.Component { } ctx = templ.InitializeContext(ctx) ctx = templ.ClearChildren(ctx) - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 60, "") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } @@ -838,46 +876,46 @@ func policyBanner(msgID, actionID, href string) templ.Component { } ctx = templ.InitializeContext(ctx) ctx = templ.ClearChildren(ctx) - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 63, "

") - if templ_7745c5c3_Err != nil { - return templ_7745c5c3_Err - } - var templ_7745c5c3_Var40 string - templ_7745c5c3_Var40, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, msgID)) - if templ_7745c5c3_Err != nil { - return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 167, Col: 23} - } - _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var40)) - if templ_7745c5c3_Err != nil { - return templ_7745c5c3_Err - } - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 64, " ") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 67, "

") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 68, " ") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + var templ_7745c5c3_Var44 string + templ_7745c5c3_Var44, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, actionID)) + if templ_7745c5c3_Err != nil { + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 174, Col: 95} + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var44)) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 70, "

") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } diff --git a/internal/web/regions.templ b/internal/web/regions.templ new file mode 100644 index 0000000..8135c73 --- /dev/null +++ b/internal/web/regions.templ @@ -0,0 +1,151 @@ +package web + +import "git.zb-server.de/ZB-Server/uptimesebi/internal/i18n" + +// Region is a row in a region list. +type Region struct { + ID string + Key string + Name string + // Platform regions are shared by all organizations. + Platform bool + // Manageable regions can be deleted on the current page. + Manageable bool + Instances int64 +} + +// Agent is a checker or status page server. +type Agent struct { + ID string + Kind string + Name string + Region string + Prefix string + LastSeen string +} + +// RegionsView is the data of the org regions page and the admin panel. +type RegionsView struct { + Regions []Region + Agents []Agent + // APIBase is the prefix of the endpoints the forms post to, either + // /org or /admin. + APIBase string + // Next is the page to reload after a change. + Next string + // OwnRegions are the regions agents can be created in. + OwnRegions []Region +} + +templ regionsBody(v RegionsView) { +
+ @sectionHeading("regions.list") + + + + + + + + + + + + for _, r := range v.Regions { + + + + + + + + } + +
{ i18n.T(ctx, "sso.field.name") }{ i18n.T(ctx, "regions.key") }{ i18n.T(ctx, "regions.owner") }{ i18n.T(ctx, "regions.instances") }
{ r.Name }{ r.Key } + if r.Platform { + { i18n.T(ctx, "regions.platform") } + } else { + { i18n.T(ctx, "regions.own") } + } + + 0), templ.KV("text-unknown", r.Instances == 0) }>● { i18n.T(ctx, "regions.live", "Count", int(r.Instances)) } + + if r.Manageable { + + } +
+
+
+
+ @sectionHeading("regions.create") +
+ @formError() + @valueField(i18n.T(ctx, "regions.key"), "key", "", "office-berlin", true) + @valueField(i18n.T(ctx, "sso.field.name"), "name", "", "Office Berlin", false) + @submit(i18n.T(ctx, "regions.create")) +
+
+
+ @sectionHeading("agents.create") +
+ @formError() + @valueField(i18n.T(ctx, "sso.field.name"), "name", "", "checker-1", true) + + + @submit(i18n.T(ctx, "agents.create")) + +
+
+
+ if len(v.Agents) > 0 { +
+ @sectionHeading("agents.list") +
    + for _, a := range v.Agents { +
  • + + { a.Name } + · { i18n.T(ctx, "agents.kind_"+a.Kind) } + if a.Region != "" { + · { a.Region } + } + { a.Prefix }… · { a.LastSeen } + + +
  • + } +
+
+ } +} + +templ RegionsPage(p Page, me Me, v RegionsView) { + @consoleShell(p, me) { + @settingsHeading("regions.title", "regions.intro") + @regionsBody(v) + } +} + +templ AdminPage(p Page, me Me, v RegionsView) { + @consoleShell(p, me) { + @settingsHeading("admin.title", "admin.intro") + @regionsBody(v) + } +} diff --git a/internal/web/regions_templ.go b/internal/web/regions_templ.go new file mode 100644 index 0000000..2c17247 --- /dev/null +++ b/internal/web/regions_templ.go @@ -0,0 +1,746 @@ +// Code generated by templ - DO NOT EDIT. + +// templ: version: v0.3.1118 + +package web + +//lint:file-ignore SA4006 This context is only used if a nested component is present. + +import "github.com/a-h/templ" +import templruntime "github.com/a-h/templ/runtime" + +import "git.zb-server.de/ZB-Server/uptimesebi/internal/i18n" + +// Region is a row in a region list. +type Region struct { + ID string + Key string + Name string + // Platform regions are shared by all organizations. + Platform bool + // Manageable regions can be deleted on the current page. + Manageable bool + Instances int64 +} + +// Agent is a checker or status page server. +type Agent struct { + ID string + Kind string + Name string + Region string + Prefix string + LastSeen string +} + +// RegionsView is the data of the org regions page and the admin panel. +type RegionsView struct { + Regions []Region + Agents []Agent + // APIBase is the prefix of the endpoints the forms post to, either + // /org or /admin. + APIBase string + // Next is the page to reload after a change. + Next string + // OwnRegions are the regions agents can be created in. + OwnRegions []Region +} + +func regionsBody(v RegionsView) templ.Component { + return templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) { + templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context + if templ_7745c5c3_CtxErr := ctx.Err(); templ_7745c5c3_CtxErr != nil { + return templ_7745c5c3_CtxErr + } + templ_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W) + if !templ_7745c5c3_IsBuffer { + defer func() { + templ_7745c5c3_BufErr := templruntime.ReleaseBuffer(templ_7745c5c3_Buffer) + if templ_7745c5c3_Err == nil { + templ_7745c5c3_Err = templ_7745c5c3_BufErr + } + }() + } + ctx = templ.InitializeContext(ctx) + ctx = templ.ClearChildren(ctx) + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 1, "
") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = sectionHeading("regions.list").Render(ctx, templ_7745c5c3_Buffer) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 2, "") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + for _, r := range v.Regions { + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 7, "") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 22, "
") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + var templ_7745c5c3_Var2 string + templ_7745c5c3_Var2, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "sso.field.name")) + if templ_7745c5c3_Err != nil { + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/regions.templ`, Line: 46, Col: 70} + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var2)) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 3, "") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + var templ_7745c5c3_Var3 string + templ_7745c5c3_Var3, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "regions.key")) + if templ_7745c5c3_Err != nil { + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/regions.templ`, Line: 47, Col: 67} + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var3)) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 4, "") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + var templ_7745c5c3_Var4 string + templ_7745c5c3_Var4, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "regions.owner")) + if templ_7745c5c3_Err != nil { + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/regions.templ`, Line: 48, Col: 69} + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var4)) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 5, "") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + var templ_7745c5c3_Var5 string + templ_7745c5c3_Var5, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "regions.instances")) + if templ_7745c5c3_Err != nil { + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/regions.templ`, Line: 49, Col: 73} + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var5)) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 6, "
") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + var templ_7745c5c3_Var6 string + templ_7745c5c3_Var6, templ_7745c5c3_Err = templ.JoinStringErrs(r.Name) + if templ_7745c5c3_Err != nil { + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/regions.templ`, Line: 56, Col: 38} + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var6)) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 8, "") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + var templ_7745c5c3_Var7 string + templ_7745c5c3_Var7, templ_7745c5c3_Err = templ.JoinStringErrs(r.Key) + if templ_7745c5c3_Err != nil { + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/regions.templ`, Line: 57, Col: 55} + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var7)) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 9, "") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + if r.Platform { + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 10, "") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + var templ_7745c5c3_Var8 string + templ_7745c5c3_Var8, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "regions.platform")) + if templ_7745c5c3_Err != nil { + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/regions.templ`, Line: 60, Col: 66} + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var8)) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 11, "") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + } else { + var templ_7745c5c3_Var9 string + templ_7745c5c3_Var9, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "regions.own")) + if templ_7745c5c3_Err != nil { + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/regions.templ`, Line: 62, Col: 36} + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var9)) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 12, "") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + { + templ_7745c5c3_ElementWriter := templ_7745c5c3_Buffer + templ_7745c5c3_Buffer := templ.GetBuffer() + var templ_7745c5c3_ElementScripts []templ.ComponentScript + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 13, " 0), templ.KV("text-unknown", r.Instances == 0)} + templ_7745c5c3_Err = templ.RenderCSSItems(ctx, templ_7745c5c3_ElementWriter, templ_7745c5c3_Var10...) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + var templ_7745c5c3_Var11 string + templ_7745c5c3_Var11, templ_7745c5c3_Err = templruntime.NewAttributeExpression(templ.CSSClasses(templ_7745c5c3_Var10).String()).Resolve(ctx) + if templ_7745c5c3_Err != nil { + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/regions.templ`, Line: 1, Col: 0} + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var11) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 14, "\"") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templ.RenderScriptItems(ctx, templ_7745c5c3_ElementWriter, templ_7745c5c3_ElementScripts...) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteTo(templ_7745c5c3_ElementWriter) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ.ReleaseBuffer(templ_7745c5c3_Buffer) + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 15, ">● ") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + var templ_7745c5c3_Var12 string + templ_7745c5c3_Var12, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "regions.live", "Count", int(r.Instances))) + if templ_7745c5c3_Err != nil { + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/regions.templ`, Line: 66, Col: 171} + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var12)) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 16, "") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + if r.Manageable { + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 17, "") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 21, "
") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = sectionHeading("regions.create").Render(ctx, templ_7745c5c3_Buffer) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 23, "
") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = formError().Render(ctx, templ_7745c5c3_Buffer) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = valueField(i18n.T(ctx, "regions.key"), "key", "", "office-berlin", true).Render(ctx, templ_7745c5c3_Buffer) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = valueField(i18n.T(ctx, "sso.field.name"), "name", "", "Office Berlin", false).Render(ctx, templ_7745c5c3_Buffer) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = submit(i18n.T(ctx, "regions.create")).Render(ctx, templ_7745c5c3_Buffer) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 26, "
") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = sectionHeading("agents.create").Render(ctx, templ_7745c5c3_Buffer) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 27, "
") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = formError().Render(ctx, templ_7745c5c3_Buffer) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = valueField(i18n.T(ctx, "sso.field.name"), "name", "", "checker-1", true).Render(ctx, templ_7745c5c3_Buffer) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 29, " ") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = submit(i18n.T(ctx, "agents.create")).Render(ctx, templ_7745c5c3_Buffer) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 39, "
") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + if len(v.Agents) > 0 { + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 41, "
") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = sectionHeading("agents.list").Render(ctx, templ_7745c5c3_Buffer) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 42, "
    ") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + for _, a := range v.Agents { + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 43, "
  • ") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + var templ_7745c5c3_Var27 string + templ_7745c5c3_Var27, templ_7745c5c3_Err = templ.JoinStringErrs(a.Name) + if templ_7745c5c3_Err != nil { + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/regions.templ`, Line: 124, Col: 15} + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var27)) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 44, " · ") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + var templ_7745c5c3_Var28 string + templ_7745c5c3_Var28, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "agents.kind_"+a.Kind)) + if templ_7745c5c3_Err != nil { + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/regions.templ`, Line: 125, Col: 71} + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var28)) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 45, " ") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + if a.Region != "" { + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 46, "· ") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + var templ_7745c5c3_Var29 string + templ_7745c5c3_Var29, templ_7745c5c3_Err = templ.JoinStringErrs(a.Region) + if templ_7745c5c3_Err != nil { + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/regions.templ`, Line: 127, Col: 46} + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var29)) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 47, " ") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 48, "") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + var templ_7745c5c3_Var30 string + templ_7745c5c3_Var30, templ_7745c5c3_Err = templ.JoinStringErrs(a.Prefix) + if templ_7745c5c3_Err != nil { + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/regions.templ`, Line: 129, Col: 66} + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var30)) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 49, "… · ") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + var templ_7745c5c3_Var31 string + templ_7745c5c3_Var31, templ_7745c5c3_Err = templ.JoinStringErrs(a.LastSeen) + if templ_7745c5c3_Err != nil { + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/regions.templ`, Line: 129, Col: 87} + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var31)) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 50, "
  • ") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 54, "
") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + } + return nil + }) +} + +func RegionsPage(p Page, me Me, v RegionsView) templ.Component { + return templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) { + templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context + if templ_7745c5c3_CtxErr := ctx.Err(); templ_7745c5c3_CtxErr != nil { + return templ_7745c5c3_CtxErr + } + templ_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W) + if !templ_7745c5c3_IsBuffer { + defer func() { + templ_7745c5c3_BufErr := templruntime.ReleaseBuffer(templ_7745c5c3_Buffer) + if templ_7745c5c3_Err == nil { + templ_7745c5c3_Err = templ_7745c5c3_BufErr + } + }() + } + ctx = templ.InitializeContext(ctx) + ctx = templ.ClearChildren(ctx) + templ_7745c5c3_Var36 := templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) { + templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context + templ_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W) + if !templ_7745c5c3_IsBuffer { + defer func() { + templ_7745c5c3_BufErr := templruntime.ReleaseBuffer(templ_7745c5c3_Buffer) + if templ_7745c5c3_Err == nil { + templ_7745c5c3_Err = templ_7745c5c3_BufErr + } + }() + } + ctx = templ.InitializeContext(ctx) + templ_7745c5c3_Err = settingsHeading("regions.title", "regions.intro").Render(ctx, templ_7745c5c3_Buffer) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = regionsBody(v).Render(ctx, templ_7745c5c3_Buffer) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + return nil + }) + templ_7745c5c3_Err = consoleShell(p, me).Render(templ.WithChildren(ctx, templ_7745c5c3_Var36), templ_7745c5c3_Buffer) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + return nil + }) +} + +func AdminPage(p Page, me Me, v RegionsView) templ.Component { + return templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) { + templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context + if templ_7745c5c3_CtxErr := ctx.Err(); templ_7745c5c3_CtxErr != nil { + return templ_7745c5c3_CtxErr + } + templ_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W) + if !templ_7745c5c3_IsBuffer { + defer func() { + templ_7745c5c3_BufErr := templruntime.ReleaseBuffer(templ_7745c5c3_Buffer) + if templ_7745c5c3_Err == nil { + templ_7745c5c3_Err = templ_7745c5c3_BufErr + } + }() + } + ctx = templ.InitializeContext(ctx) + ctx = templ.ClearChildren(ctx) + templ_7745c5c3_Var38 := templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) { + templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context + templ_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W) + if !templ_7745c5c3_IsBuffer { + defer func() { + templ_7745c5c3_BufErr := templruntime.ReleaseBuffer(templ_7745c5c3_Buffer) + if templ_7745c5c3_Err == nil { + templ_7745c5c3_Err = templ_7745c5c3_BufErr + } + }() + } + ctx = templ.InitializeContext(ctx) + templ_7745c5c3_Err = settingsHeading("admin.title", "admin.intro").Render(ctx, templ_7745c5c3_Buffer) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = regionsBody(v).Render(ctx, templ_7745c5c3_Buffer) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + return nil + }) + templ_7745c5c3_Err = consoleShell(p, me).Render(templ.WithChildren(ctx, templ_7745c5c3_Var38), templ_7745c5c3_Buffer) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + return nil + }) +} + +var _ = templruntime.GeneratedTemplate