package api import ( "context" "errors" "net/http" "strings" "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/authz" "git.zb-server.de/ZB-Server/uptimesebi/internal/store" "git.zb-server.de/ZB-Server/uptimesebi/internal/tenant" ) // groupTree is an organization's monitor groups. Role assignments scoped to // a group cover its whole subtree, so permission checks look at a group and // all its ancestors. type groupTree struct { byID map[uuid.UUID]store.MonitorGroup children map[uuid.UUID][]uuid.UUID roots []uuid.UUID } func newGroupTree(groups []store.MonitorGroup) groupTree { t := groupTree{byID: map[uuid.UUID]store.MonitorGroup{}, children: map[uuid.UUID][]uuid.UUID{}} for _, g := range groups { t.byID[g.ID] = g } for _, g := range groups { if g.ParentID != nil { if _, ok := t.byID[*g.ParentID]; ok { t.children[*g.ParentID] = append(t.children[*g.ParentID], g.ID) continue } } t.roots = append(t.roots, g.ID) } return t } func (s *Server) loadGroupTree(ctx context.Context, scope tenant.Scope) (groupTree, error) { var groups []store.MonitorGroup err := s.db.Tx(ctx, scope, func(q *store.Queries) error { var err error groups, err = q.ListGroups(ctx) return err }) return newGroupTree(groups), err } // resources returns the group and its ancestors as authorization scopes, // nearest first. A monitor without a group has none: only org-wide rights // cover it. func (t groupTree) resources(group *uuid.UUID) []authz.Resource { var out []authz.Resource for id := group; id != nil; { g, ok := t.byID[*id] if !ok || len(out) > 20 { break } out = append(out, authz.Resource{Type: authz.MonitorGroup, ID: g.ID}) id = g.ParentID } return out } // depth returns how many ancestors a group has. func (t groupTree) depth(id uuid.UUID) int { return len(t.resources(&id)) - 1 } // walk visits groups depth-first in name order. func (t groupTree) walk(fn func(g store.MonitorGroup, depth int)) { var visit func(ids []uuid.UUID, depth int) visit = func(ids []uuid.UUID, depth int) { for _, id := range ids { fn(t.byID[id], depth) visit(t.children[id], depth+1) } } visit(t.roots, 0) } // canInGroup reports whether p holds perm for things in group. func canInGroup(p *principal, perm authz.Permission, t groupTree, group *uuid.UUID) bool { return p.Grants.Can(perm, t.resources(group)...) } type groupView struct { ID uuid.UUID `json:"id"` Name string `json:"name"` ParentID *uuid.UUID `json:"parent_id"` } func (s *Server) listGroups(c *gin.Context) { p := current(c) t, err := s.loadGroupTree(c.Request.Context(), p.scope()) if err != nil { internalError(c, err) return } out := []groupView{} t.walk(func(g store.MonitorGroup, _ int) { out = append(out, groupView{ID: g.ID, Name: g.Name, ParentID: g.ParentID}) }) c.JSON(http.StatusOK, gin.H{"groups": out}) } type groupRequest struct { Name string `json:"name" binding:"required,max=100"` ParentID *uuid.UUID `json:"parent_id"` } func groupError(c *gin.Context, err error) bool { var pgErr *pgconn.PgError if !errors.As(err, &pgErr) { return false } switch { case pgErr.ConstraintName == "monitor_groups_cycle", pgErr.ConstraintName == "monitor_groups_check": fail(c, http.StatusUnprocessableEntity, "group_cycle") case pgErr.ConstraintName == "monitor_groups_depth": fail(c, http.StatusUnprocessableEntity, "group_too_deep") case pgErr.Code == "23503": fail(c, http.StatusUnprocessableEntity, "invalid_group") default: return false } return true } func (s *Server) createGroup(c *gin.Context) { var req groupRequest if !bind(c, &req) { return } req.Name = strings.TrimSpace(req.Name) if req.Name == "" { fail(c, http.StatusUnprocessableEntity, "invalid_input") return } p := current(c) ctx := c.Request.Context() t, err := s.loadGroupTree(ctx, p.scope()) if err != nil { internalError(c, err) return } if req.ParentID != nil { if _, ok := t.byID[*req.ParentID]; !ok { fail(c, http.StatusUnprocessableEntity, "invalid_group") return } } if !canInGroup(p, authz.MonitorsWrite, t, req.ParentID) { fail(c, http.StatusForbidden, "forbidden") return } var g store.MonitorGroup err = s.db.Tx(ctx, p.scope(), func(q *store.Queries) error { var err error g, err = q.CreateGroup(ctx, store.CreateGroupParams{OrgID: p.Org.ID, ParentID: req.ParentID, Name: req.Name}) return err }) if groupError(c, err) { return } if err != nil { internalError(c, err) return } c.JSON(http.StatusCreated, groupView{ID: g.ID, Name: g.Name, ParentID: g.ParentID}) } // updateGroup renames or moves a group. Moving needs write access both where // the group is and where it goes. func (s *Server) updateGroup(c *gin.Context) { id, err := uuid.Parse(c.Param("id")) if err != nil { fail(c, http.StatusNotFound, "not_found") return } var req groupRequest if !bind(c, &req) { return } req.Name = strings.TrimSpace(req.Name) p := current(c) ctx := c.Request.Context() t, err := s.loadGroupTree(ctx, p.scope()) if err != nil { internalError(c, err) return } if _, ok := t.byID[id]; !ok || req.Name == "" { fail(c, http.StatusNotFound, "not_found") return } if req.ParentID != nil { if _, ok := t.byID[*req.ParentID]; !ok { fail(c, http.StatusUnprocessableEntity, "invalid_group") return } } if !canInGroup(p, authz.MonitorsWrite, t, &id) || !canInGroup(p, authz.MonitorsWrite, t, req.ParentID) { fail(c, http.StatusForbidden, "forbidden") return } var g store.MonitorGroup err = s.db.Tx(ctx, p.scope(), func(q *store.Queries) error { var err error g, err = q.UpdateGroup(ctx, store.UpdateGroupParams{ID: id, Name: req.Name, ParentID: req.ParentID}) return err }) if groupError(c, err) { return } if err != nil { internalError(c, err) return } c.JSON(http.StatusOK, groupView{ID: g.ID, Name: g.Name, ParentID: g.ParentID}) } // deleteGroup moves the group's subgroups and monitors to its parent and // removes assignments scoped to it. As things move up, write access to the // parent is required. func (s *Server) deleteGroup(c *gin.Context) { id, err := uuid.Parse(c.Param("id")) if err != nil { fail(c, http.StatusNotFound, "not_found") return } p := current(c) ctx := c.Request.Context() t, err := s.loadGroupTree(ctx, p.scope()) if err != nil { internalError(c, err) return } g, ok := t.byID[id] if !ok { fail(c, http.StatusNotFound, "not_found") return } if !canInGroup(p, authz.MonitorsWrite, t, g.ParentID) { fail(c, http.StatusForbidden, "forbidden") return } err = s.db.Tx(ctx, p.scope(), func(q *store.Queries) error { if err := q.ReparentGroups(ctx, store.ReparentGroupsParams{OldParent: &id, NewParent: g.ParentID}); err != nil { return err } if err := q.RegroupMonitors(ctx, store.RegroupMonitorsParams{OldGroup: &id, NewGroup: g.ParentID}); err != nil { return err } rt := string(authz.MonitorGroup) if err := q.DeleteAssignmentsForResource(ctx, store.DeleteAssignmentsForResourceParams{ResourceType: &rt, ResourceID: &id}); err != nil { return err } _, err := q.DeleteGroup(ctx, id) return err }) if errors.Is(err, pgx.ErrNoRows) { fail(c, http.StatusNotFound, "not_found") return } if err != nil { internalError(c, err) return } c.Status(http.StatusNoContent) }