Lists that were cut off by a fixed LIMIT, or could grow without bound, are paged by keyset: the cursor holds the sort key and an ID, so pages neither skip nor repeat items as others are added. The audit logs had a timestamp-only cursor that could skip entries with equal times. The API returns at most 100 items per list (limit takes up to 500) with next_cursor and prev_cursor, passed back as after and before. The console shows Newer/Older (or Previous/Next) links and To the start, without JavaScript. Paged: incidents (optionally of one monitor), a monitor's results and evidence, a checker's results, the audit logs, members, maintenance windows, firing Alertmanager alerts, the monitors API and the admin lists of status pages and organizations, which move to their own admin pages. A monitor's page shows its latest incidents and results and links to all of them. The dashboard caps every group at 50 of its own monitors with a link to a paged view of the group, and gains a search by name or target. Lists filtered by permission after reading may show fewer items on a page. Closes #116 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
498 lines
13 KiB
Go
498 lines
13 KiB
Go
package api
|
|
|
|
import (
|
|
"errors"
|
|
"net/http"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
"github.com/google/uuid"
|
|
"github.com/jackc/pgx/v5"
|
|
|
|
"git.zb-server.de/ZB-Server/uptimesebi/internal/authz"
|
|
"git.zb-server.de/ZB-Server/uptimesebi/internal/store"
|
|
)
|
|
|
|
type assignmentView struct {
|
|
ID uuid.UUID `json:"id"`
|
|
RoleID uuid.UUID `json:"role_id"`
|
|
RoleName string `json:"role_name"`
|
|
RoleKey *string `json:"role_key,omitempty"`
|
|
ResourceType *string `json:"resource_type,omitempty"`
|
|
ResourceID *uuid.UUID `json:"resource_id,omitempty"`
|
|
}
|
|
|
|
type memberView struct {
|
|
UserID uuid.UUID `json:"user_id"`
|
|
Email string `json:"email"`
|
|
DisplayName string `json:"display_name"`
|
|
IsOwner bool `json:"is_owner"`
|
|
JoinedAt time.Time `json:"joined_at"`
|
|
Assignments []assignmentView `json:"assignments"`
|
|
}
|
|
|
|
// loadMembers reads a page of members by email.
|
|
func (s *Server) loadMembers(c *gin.Context, pg pageReq) ([]memberView, pageInfo, error) {
|
|
p := current(c)
|
|
ctx := c.Request.Context()
|
|
var out []memberView
|
|
var info pageInfo
|
|
err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
|
|
members, err := q.ListOrgMembersPage(ctx, store.ListOrgMembersPageParams{
|
|
OrgID: p.Org.ID, AfterS: pg.afterS(), AfterID: pg.afterID(), BeforeS: pg.beforeS(), BeforeID: pg.beforeID(), MaxRows: pg.fetch(),
|
|
})
|
|
if err != nil {
|
|
return err
|
|
}
|
|
members, info = paginate(pg, members, func(m store.ListOrgMembersPageRow) cursor { return cursor{S: m.Email, ID: m.ID} })
|
|
assigns, err := q.ListAssignments(ctx, p.Org.ID)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
byUser := map[uuid.UUID][]assignmentView{}
|
|
for _, a := range assigns {
|
|
byUser[a.UserID] = append(byUser[a.UserID], assignmentView{
|
|
ID: a.ID, RoleID: a.RoleID, RoleName: a.RoleName, RoleKey: a.RoleKey,
|
|
ResourceType: a.ResourceType, ResourceID: a.ResourceID,
|
|
})
|
|
}
|
|
out = make([]memberView, len(members))
|
|
for i, m := range members {
|
|
out[i] = memberView{
|
|
UserID: m.ID, Email: m.Email, DisplayName: m.DisplayName, IsOwner: m.IsOwner,
|
|
JoinedAt: m.JoinedAt, Assignments: byUser[m.ID],
|
|
}
|
|
if out[i].Assignments == nil {
|
|
out[i].Assignments = []assignmentView{}
|
|
}
|
|
}
|
|
return nil
|
|
})
|
|
return out, info, err
|
|
}
|
|
|
|
func (s *Server) listMembers(c *gin.Context) {
|
|
pg, ok := parsePage(c, apiPageSize)
|
|
if !ok {
|
|
return
|
|
}
|
|
members, info, err := s.loadMembers(c, pg)
|
|
if err != nil {
|
|
internalError(c, err)
|
|
return
|
|
}
|
|
c.JSON(http.StatusOK, gin.H{"members": members, "next_cursor": info.Next, "prev_cursor": info.Prev})
|
|
}
|
|
|
|
// removeMember requires the actor to hold every permission the member holds
|
|
// organization-wide, so a delegated admin cannot remove a stronger one.
|
|
func (s *Server) removeMember(c *gin.Context) {
|
|
target, err := uuid.Parse(c.Param("user"))
|
|
if err != nil {
|
|
fail(c, http.StatusNotFound, "not_found")
|
|
return
|
|
}
|
|
p := current(c)
|
|
ctx := c.Request.Context()
|
|
var code string
|
|
err = s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
|
|
g, member, err := loadGrants(ctx, q, p.Org.ID, target)
|
|
switch {
|
|
case err != nil:
|
|
return err
|
|
case !member:
|
|
code = "not_found"
|
|
case g.Owner:
|
|
code = "owner_cannot_be_removed"
|
|
case !p.Grants.CanGrant(g.Org, nil):
|
|
code = "permission_escalation"
|
|
default:
|
|
_, err = q.RemoveMembership(ctx, store.RemoveMembershipParams{OrgID: p.Org.ID, UserID: target})
|
|
}
|
|
return err
|
|
})
|
|
if err != nil {
|
|
internalError(c, err)
|
|
return
|
|
}
|
|
switch code {
|
|
case "":
|
|
_ = s.sessions.DeleteAllForUser(ctx, target)
|
|
c.Status(http.StatusNoContent)
|
|
case "not_found":
|
|
fail(c, http.StatusNotFound, code)
|
|
default:
|
|
fail(c, http.StatusForbidden, code)
|
|
}
|
|
}
|
|
|
|
type assignRequest struct {
|
|
RoleID uuid.UUID `json:"role_id" binding:"required"`
|
|
ResourceType string `json:"resource_type" binding:"omitempty,oneof=monitor_group status_page"`
|
|
ResourceID *uuid.UUID `json:"resource_id"`
|
|
}
|
|
|
|
func (r assignRequest) scope() (*authz.Resource, bool) {
|
|
if r.ResourceType == "" && r.ResourceID == nil {
|
|
return nil, true
|
|
}
|
|
if r.ResourceID == nil {
|
|
return nil, false
|
|
}
|
|
res := authz.Resource{Type: authz.ResourceType(r.ResourceType), ID: *r.ResourceID}
|
|
return &res, res.Valid()
|
|
}
|
|
|
|
func (s *Server) assignRole(c *gin.Context) {
|
|
target, err := uuid.Parse(c.Param("user"))
|
|
if err != nil {
|
|
fail(c, http.StatusNotFound, "not_found")
|
|
return
|
|
}
|
|
var req assignRequest
|
|
if !bind(c, &req) {
|
|
return
|
|
}
|
|
scope, ok := req.scope()
|
|
if !ok {
|
|
fail(c, http.StatusUnprocessableEntity, "invalid_input")
|
|
return
|
|
}
|
|
p := current(c)
|
|
ctx := c.Request.Context()
|
|
var (
|
|
code string
|
|
row store.RoleAssignment
|
|
)
|
|
err = s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
|
|
role, err := q.GetRole(ctx, req.RoleID)
|
|
if errors.Is(err, pgx.ErrNoRows) {
|
|
code = "role_not_found"
|
|
return nil
|
|
}
|
|
if err != nil {
|
|
return err
|
|
}
|
|
m, err := q.GetMembership(ctx, store.GetMembershipParams{OrgID: p.Org.ID, UserID: target})
|
|
switch {
|
|
case errors.Is(err, pgx.ErrNoRows):
|
|
code = "not_found"
|
|
return nil
|
|
case err != nil:
|
|
return err
|
|
case m.IsOwner:
|
|
code = "owner_has_all_permissions"
|
|
return nil
|
|
case !p.Grants.CanGrant(authz.NewSet(role.Permissions...), scope):
|
|
code = "permission_escalation"
|
|
return nil
|
|
}
|
|
params := store.CreateAssignmentParams{OrgID: p.Org.ID, UserID: target, RoleID: role.ID}
|
|
if scope != nil {
|
|
rt := string(scope.Type)
|
|
params.ResourceType, params.ResourceID = &rt, &scope.ID
|
|
}
|
|
row, err = q.CreateAssignment(ctx, params)
|
|
if isUniqueViolation(err, "role_assignments_org_id_user_id_role_id_resource_type_resou_key") {
|
|
code = "already_assigned"
|
|
return nil
|
|
}
|
|
return err
|
|
})
|
|
if err != nil {
|
|
internalError(c, err)
|
|
return
|
|
}
|
|
switch code {
|
|
case "":
|
|
c.JSON(http.StatusCreated, gin.H{"id": row.ID})
|
|
case "not_found", "role_not_found":
|
|
fail(c, http.StatusNotFound, code)
|
|
case "already_assigned", "owner_has_all_permissions":
|
|
fail(c, http.StatusConflict, code)
|
|
default:
|
|
fail(c, http.StatusForbidden, code)
|
|
}
|
|
}
|
|
|
|
func (s *Server) unassignRole(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()
|
|
var code string
|
|
err = s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
|
|
a, err := q.GetAssignment(ctx, id)
|
|
if errors.Is(err, pgx.ErrNoRows) {
|
|
code = "not_found"
|
|
return nil
|
|
}
|
|
if err != nil {
|
|
return err
|
|
}
|
|
role, err := q.GetRole(ctx, a.RoleID)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
var scope *authz.Resource
|
|
if a.ResourceType != nil && a.ResourceID != nil {
|
|
scope = &authz.Resource{Type: authz.ResourceType(*a.ResourceType), ID: *a.ResourceID}
|
|
}
|
|
if !p.Grants.CanGrant(authz.NewSet(role.Permissions...), scope) {
|
|
code = "permission_escalation"
|
|
return nil
|
|
}
|
|
_, err = q.DeleteAssignment(ctx, id)
|
|
return err
|
|
})
|
|
if err != nil {
|
|
internalError(c, err)
|
|
return
|
|
}
|
|
switch code {
|
|
case "":
|
|
c.Status(http.StatusNoContent)
|
|
case "not_found":
|
|
fail(c, http.StatusNotFound, code)
|
|
default:
|
|
fail(c, http.StatusForbidden, code)
|
|
}
|
|
}
|
|
|
|
type roleView struct {
|
|
ID uuid.UUID `json:"id"`
|
|
Key *string `json:"key,omitempty"`
|
|
Name string `json:"name"`
|
|
BuiltIn bool `json:"built_in"`
|
|
Permissions []string `json:"permissions"`
|
|
}
|
|
|
|
func viewRole(r store.Role) roleView {
|
|
return roleView{ID: r.ID, Key: r.Key, Name: r.Name, BuiltIn: r.OrgID == nil, Permissions: authz.NewSet(r.Permissions...).Strings()}
|
|
}
|
|
|
|
func (s *Server) listRoles(c *gin.Context) {
|
|
p := current(c)
|
|
ctx := c.Request.Context()
|
|
var rows []store.Role
|
|
err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
|
|
var err error
|
|
rows, err = q.ListRoles(ctx)
|
|
return err
|
|
})
|
|
if err != nil {
|
|
internalError(c, err)
|
|
return
|
|
}
|
|
out := make([]roleView, len(rows))
|
|
for i, r := range rows {
|
|
out[i] = viewRole(r)
|
|
}
|
|
c.JSON(http.StatusOK, gin.H{"roles": out, "permissions": authz.NewSet(authz.All...).Strings()})
|
|
}
|
|
|
|
type roleRequest struct {
|
|
Name string `json:"name" binding:"required,max=100"`
|
|
Permissions []string `json:"permissions" binding:"required,min=1,max=50,dive,max=50"`
|
|
}
|
|
|
|
func (s *Server) createRole(c *gin.Context) {
|
|
var req roleRequest
|
|
if !bind(c, &req) {
|
|
return
|
|
}
|
|
perms := authz.NewSet(req.Permissions...)
|
|
p := current(c)
|
|
if len(perms) == 0 || strings.TrimSpace(req.Name) == "" {
|
|
fail(c, http.StatusUnprocessableEntity, "invalid_permissions")
|
|
return
|
|
}
|
|
if !p.Grants.CanGrant(perms, nil) {
|
|
fail(c, http.StatusForbidden, "permission_escalation")
|
|
return
|
|
}
|
|
ctx := c.Request.Context()
|
|
var row store.Role
|
|
err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
|
|
var err error
|
|
row, err = q.CreateRole(ctx, store.CreateRoleParams{OrgID: &p.Org.ID, Name: strings.TrimSpace(req.Name), Permissions: perms.Strings()})
|
|
return err
|
|
})
|
|
if isUniqueViolation(err, "roles_org_id_name_key") {
|
|
fail(c, http.StatusConflict, "role_name_taken")
|
|
return
|
|
}
|
|
if err != nil {
|
|
internalError(c, err)
|
|
return
|
|
}
|
|
c.JSON(http.StatusCreated, viewRole(row))
|
|
}
|
|
|
|
// updateRole requires the actor to hold both the old and the new
|
|
// permissions: otherwise they could strip rights they cannot grant back, or
|
|
// widen a role they are assigned to.
|
|
func (s *Server) updateRole(c *gin.Context) {
|
|
id, err := uuid.Parse(c.Param("id"))
|
|
if err != nil {
|
|
fail(c, http.StatusNotFound, "not_found")
|
|
return
|
|
}
|
|
var req roleRequest
|
|
if !bind(c, &req) {
|
|
return
|
|
}
|
|
perms := authz.NewSet(req.Permissions...)
|
|
if len(perms) == 0 || strings.TrimSpace(req.Name) == "" {
|
|
fail(c, http.StatusUnprocessableEntity, "invalid_permissions")
|
|
return
|
|
}
|
|
p := current(c)
|
|
ctx := c.Request.Context()
|
|
var (
|
|
code string
|
|
row store.Role
|
|
)
|
|
err = s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
|
|
old, err := q.GetRole(ctx, id)
|
|
switch {
|
|
case errors.Is(err, pgx.ErrNoRows):
|
|
code = "not_found"
|
|
return nil
|
|
case err != nil:
|
|
return err
|
|
case old.OrgID == nil:
|
|
code = "role_built_in"
|
|
return nil
|
|
case !p.Grants.CanGrant(perms.Union(authz.NewSet(old.Permissions...)), nil):
|
|
code = "permission_escalation"
|
|
return nil
|
|
}
|
|
row, err = q.UpdateRole(ctx, store.UpdateRoleParams{ID: id, Name: strings.TrimSpace(req.Name), Permissions: perms.Strings()})
|
|
if isUniqueViolation(err, "roles_org_id_name_key") {
|
|
code = "role_name_taken"
|
|
return nil
|
|
}
|
|
return err
|
|
})
|
|
s.roleResult(c, err, code, func() { c.JSON(http.StatusOK, viewRole(row)) })
|
|
}
|
|
|
|
func (s *Server) deleteRole(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()
|
|
var code string
|
|
err = s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
|
|
old, err := q.GetRole(ctx, id)
|
|
switch {
|
|
case errors.Is(err, pgx.ErrNoRows):
|
|
code = "not_found"
|
|
return nil
|
|
case err != nil:
|
|
return err
|
|
case old.OrgID == nil:
|
|
code = "role_built_in"
|
|
return nil
|
|
case !p.Grants.CanGrant(authz.NewSet(old.Permissions...), nil):
|
|
code = "permission_escalation"
|
|
return nil
|
|
}
|
|
n, err := q.CountRoleAssignments(ctx, id)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if n > 0 {
|
|
code = "role_in_use"
|
|
return nil
|
|
}
|
|
_, err = q.DeleteRole(ctx, id)
|
|
return err
|
|
})
|
|
s.roleResult(c, err, code, func() { c.Status(http.StatusNoContent) })
|
|
}
|
|
|
|
func (s *Server) roleResult(c *gin.Context, err error, code string, ok func()) {
|
|
switch {
|
|
case err != nil:
|
|
internalError(c, err)
|
|
case code == "":
|
|
ok()
|
|
case code == "not_found":
|
|
fail(c, http.StatusNotFound, code)
|
|
case code == "permission_escalation":
|
|
fail(c, http.StatusForbidden, code)
|
|
default:
|
|
fail(c, http.StatusConflict, code)
|
|
}
|
|
}
|
|
|
|
type policyRequest struct {
|
|
RequireTOTP bool `json:"require_totp"`
|
|
RequireSSO bool `json:"require_sso"`
|
|
// APITokenMaxDays limits how long API tokens stay valid; 0 or null
|
|
// means no limit.
|
|
APITokenMaxDays *int `json:"api_token_max_days" binding:"omitempty,min=0,max=3650"`
|
|
}
|
|
|
|
func (s *Server) updatePolicy(c *gin.Context) {
|
|
var req policyRequest
|
|
if !bind(c, &req) {
|
|
return
|
|
}
|
|
p := current(c)
|
|
// The actor must already meet a policy before switching it on, or the
|
|
// change would lock them out on their next request.
|
|
probe := p.Org
|
|
probe.RequireTotp, probe.RequireSso = req.RequireTOTP, req.RequireSSO
|
|
if code := policyViolation(probe, p.Grants.Owner, p.Session); code != "" {
|
|
fail(c, http.StatusConflict, "policy_would_lock_you_out")
|
|
return
|
|
}
|
|
ctx := c.Request.Context()
|
|
var org store.Org
|
|
err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
|
|
if req.RequireSSO {
|
|
providers, err := q.ListEnabledSSOProviders(ctx)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if len(providers) == 0 {
|
|
return errNoSSOProvider
|
|
}
|
|
}
|
|
var maxDays *int32
|
|
if req.APITokenMaxDays != nil && *req.APITokenMaxDays > 0 {
|
|
maxDays = ptr(int32(*req.APITokenMaxDays))
|
|
}
|
|
var err error
|
|
org, err = q.UpdateOrgPolicy(ctx, store.UpdateOrgPolicyParams{
|
|
ID: p.Org.ID, RequireTotp: req.RequireTOTP, RequireSso: req.RequireSSO, ApiTokenMaxDays: maxDays,
|
|
})
|
|
if err != nil || maxDays == nil {
|
|
return err
|
|
}
|
|
_, err = q.ClampAPITokenExpiry(ctx, store.ClampAPITokenExpiryParams{OrgID: p.Org.ID, MaxDays: *maxDays})
|
|
return err
|
|
})
|
|
if errors.Is(err, errNoSSOProvider) {
|
|
fail(c, http.StatusConflict, "sso_no_provider")
|
|
return
|
|
}
|
|
if err != nil {
|
|
internalError(c, err)
|
|
return
|
|
}
|
|
c.JSON(http.StatusOK, gin.H{"require_totp": org.RequireTotp, "require_sso": org.RequireSso, "api_token_max_days": org.ApiTokenMaxDays})
|
|
}
|
|
|
|
var errNoSSOProvider = errors.New("api: no enabled sso provider")
|