diff --git a/README.md b/README.md index c48a8d4..ba230ad 100644 --- a/README.md +++ b/README.md @@ -16,6 +16,7 @@ It is built for teams and hosting providers: organizations with members, roles a - **Multi-region:** checkers run per region, several per region for load and failover; any number of regions per monitor. - **Alerting:** incidents with webhooks (signed), email and over 100 services: chat and messengers (Slack, Discord, Microsoft Teams, Telegram, Matrix, WhatsApp gateways, Nostr, …), push (ntfy, Gotify, Pushover, …), SMS and calls (Twilio, Plivo, …), email APIs (SendGrid, Microsoft 365, …) and incident management (PagerDuty, Opsgenie, Grafana OnCall, Jira Service Management, …), plus Apprise; customers bring their own credentials. Confirmations, maintenance windows (one-off or recurring). - **History:** charts and SLA from one hour to a year, per region; see what the checker saw (redirect chain, timing, certificate, response body). +- **Incident communication:** give an outage a title and post updates with a status (investigating, identified, monitoring, resolved), public on status pages or as internal notes. - **Status pages:** unlimited, custom domains with automatic TLS, themes, Markdown, legal notice; served from cache during outages. - **Organizations:** members, custom roles scoped to monitor groups or status pages, API tokens, OpenID Connect SSO per organization, sign-up and sign-in with providers such as Google, Microsoft or GitHub, enforced 2FA, audit log. - **Privacy:** GDPR data export (JSON, PDF) and deletion, also for suspended accounts; legal notice, privacy policy and terms of service, with versioned consent on sign-up and again after material changes; configurable retention, no telemetry. diff --git a/internal/agentapi/pages.go b/internal/agentapi/pages.go index 2cffaf3..1cfcd78 100644 --- a/internal/agentapi/pages.go +++ b/internal/agentapi/pages.go @@ -88,6 +88,21 @@ type PageIncident struct { Component string `json:"component"` StartedAt time.Time `json:"started_at"` ResolvedAt *time.Time `json:"resolved_at,omitempty"` + // Title names the incident; empty shows the component. + Title string `json:"title,omitempty"` + // Status is investigating, identified, monitoring or resolved, empty + // while nobody said anything. + Status string `json:"status,omitempty"` + // Updates are the public updates, newest first. + Updates []PageIncidentUpdate `json:"updates,omitempty"` +} + +// PageIncidentUpdate is what the organization told about an incident. +type PageIncidentUpdate struct { + Status string `json:"status"` + // Message is Markdown. + Message string `json:"message"` + At time.Time `json:"at"` } // PageSnapshot is everything needed to render a status page. diff --git a/internal/api/apidocs.go b/internal/api/apidocs.go index 5250c68..80eed83 100644 --- a/internal/api/apidocs.go +++ b/internal/api/apidocs.go @@ -130,6 +130,16 @@ var endpoints = []endpoint{ status: http.StatusNoContent}, {method: "GET", path: "/api/v1/org/incidents", tag: "Monitors", summary: "List incidents", perm: "incidents.read", description: "Paged, newest first. `monitor_id` limits them to one monitor.", resp: paged(obj{"incidents": []incidentView{}})}, + {method: "GET", path: "/api/v1/org/incidents/:id", tag: "Monitors", summary: "An incident with its updates", perm: "incidents.read", + description: "`status` is `resolved` once the monitor recovered, otherwise the status of the latest update (`investigating`, `identified`, `monitoring`, `resolved`), empty before the first. Updates newest first, internal notes included.", + resp: incidentDetailView{}}, + {method: "PATCH", path: "/api/v1/org/incidents/:id", tag: "Monitors", summary: "Name an incident", perm: "incidents.write", + description: "The title status pages show; empty shows the monitor's name.", req: incidentTitleRequest{}, status: http.StatusNoContent}, + {method: "POST", path: "/api/v1/org/incidents/:id/updates", tag: "Monitors", summary: "Post an update with a status", perm: "incidents.write", + description: "`message` is Markdown. `public` (default true) shows it on status pages; false keeps it an internal note. The update's status becomes the incident's.", + req: incidentUpdateRequest{}, resp: incidentUpdateView{}, status: http.StatusCreated}, + {method: "DELETE", path: "/api/v1/org/incidents/:id/updates/:update", tag: "Monitors", summary: "Delete an update", perm: "incidents.write", + status: http.StatusNoContent}, // Status pages {method: "GET", path: "/api/v1/org/statuspages", tag: "Status pages", summary: "List status pages", resp: obj{"pages": []statusPageView{}}}, diff --git a/internal/api/audit.go b/internal/api/audit.go index 2456be0..e2ac15b 100644 --- a/internal/api/audit.go +++ b/internal/api/audit.go @@ -25,29 +25,32 @@ import ( // empty name marks a route deliberately not audited. A test fails for // routes missing here, so new endpoints cannot slip past the log. var auditActions = map[string]string{ - "POST /api/v1/org/alert-groups": "alert_group.create", - "PUT /api/v1/org/alert-groups/:id": "alert_group.update", - "DELETE /api/v1/org/alert-groups/:id": "alert_group.delete", - "POST /api/v1/locale": "", - "POST /api/v1/markdown/preview": "", - "POST /api/v1/auth/signup": "account.signup", - "POST /api/v1/auth/verify": "account.verify", - "POST /api/v1/auth/verify/resend": "", - "POST /api/v1/orgs": "org.create", - "POST /api/v1/auth/login": "auth.login", - "POST /api/v1/auth/login/totp": "auth.login", - "POST /api/v1/auth/logout": "auth.logout", - "POST /api/v1/consent": "account.consent", - "PUT /api/v1/org/members/:user/owner": "member.owner", - "POST /api/v1/me/org": "", - "POST /api/v1/me/totp/setup": "", - "POST /api/v1/me/totp/enable": "account.totp_enable", - "POST /api/v1/me/totp/disable": "account.totp_disable", - "POST /api/v1/me/totp/recovery-codes": "account.recovery_codes", - "POST /api/v1/me/delete": "account.delete", - "POST /api/v1/org/delete": "org.delete", - "POST /api/v1/invitations/:token/accept": "member.join", - "POST /api/v1/invitations/:token/signup": "member.join", + "POST /api/v1/org/alert-groups": "alert_group.create", + "PUT /api/v1/org/alert-groups/:id": "alert_group.update", + "DELETE /api/v1/org/alert-groups/:id": "alert_group.delete", + "POST /api/v1/locale": "", + "POST /api/v1/markdown/preview": "", + "POST /api/v1/auth/signup": "account.signup", + "POST /api/v1/auth/verify": "account.verify", + "POST /api/v1/auth/verify/resend": "", + "POST /api/v1/orgs": "org.create", + "POST /api/v1/auth/login": "auth.login", + "POST /api/v1/auth/login/totp": "auth.login", + "POST /api/v1/auth/logout": "auth.logout", + "POST /api/v1/consent": "account.consent", + "PUT /api/v1/org/members/:user/owner": "member.owner", + "PATCH /api/v1/org/incidents/:id": "incident.title", + "POST /api/v1/org/incidents/:id/updates": "incident.update", + "DELETE /api/v1/org/incidents/:id/updates/:update": "incident.update_delete", + "POST /api/v1/me/org": "", + "POST /api/v1/me/totp/setup": "", + "POST /api/v1/me/totp/enable": "account.totp_enable", + "POST /api/v1/me/totp/disable": "account.totp_disable", + "POST /api/v1/me/totp/recovery-codes": "account.recovery_codes", + "POST /api/v1/me/delete": "account.delete", + "POST /api/v1/org/delete": "org.delete", + "POST /api/v1/invitations/:token/accept": "member.join", + "POST /api/v1/invitations/:token/signup": "member.join", "PUT /api/v1/org/policy": "org.policy_update", "POST /api/v1/org/monitors": "monitor.create", diff --git a/internal/api/channels.go b/internal/api/channels.go index 511c811..532e3e4 100644 --- a/internal/api/channels.go +++ b/internal/api/channels.go @@ -289,6 +289,10 @@ type incidentView struct { StartedAt time.Time `json:"started_at"` ResolvedAt *time.Time `json:"resolved_at"` Cause map[string]string `json:"cause"` + Title string `json:"title"` + // Status is resolved once the monitor recovered, otherwise the status + // of the latest update, empty before the first. + Status string `json:"status"` } // incidentPage reads a page of incidents, newest first, of one monitor @@ -336,7 +340,10 @@ func (s *Server) listIncidents(c *gin.Context) { } out := make([]incidentView, len(rows)) for i, r := range rows { - out[i] = incidentView{ID: r.ID, MonitorID: r.MonitorID, MonitorName: r.MonitorName, StartedAt: r.StartedAt, ResolvedAt: r.ResolvedAt} + out[i] = incidentView{ + ID: r.ID, MonitorID: r.MonitorID, MonitorName: r.MonitorName, StartedAt: r.StartedAt, ResolvedAt: r.ResolvedAt, + Title: r.Title, Status: incidentStatus(store.Incident{ResolvedAt: r.ResolvedAt, Status: r.Status}), + } _ = json.Unmarshal(r.Cause, &out[i].Cause) } c.JSON(http.StatusOK, gin.H{"incidents": out, "next_cursor": info.Next, "prev_cursor": info.Prev}) diff --git a/internal/api/console.go b/internal/api/console.go index 537e614..a37c21e 100644 --- a/internal/api/console.go +++ b/internal/api/console.go @@ -533,6 +533,7 @@ func (s *Server) monitorDetail(c *gin.Context, p *principal, page web.Page, me w } v.Incidents = append(v.Incidents, d.incidentRow(store.Incident{ ID: i.ID, OrgID: i.OrgID, MonitorID: i.MonitorID, StartedAt: i.StartedAt, ResolvedAt: i.ResolvedAt, Cause: i.Cause, + Title: i.Title, Status: i.Status, }, m.Name)) } page.TitleID = "console.monitors.title" @@ -556,6 +557,7 @@ func (d monitorData) incidentRow(i store.Incident, monitor string) web.IncidentR row := web.IncidentRow{ ID: i.ID.String(), MonitorID: i.MonitorID.String(), Monitor: monitor, Started: i.StartedAt.UTC().Format(timeLayout), Open: i.ResolvedAt == nil, + Title: i.Title, Status: incidentStatus(i), } end := time.Now() if i.ResolvedAt != nil { @@ -906,6 +908,7 @@ func (s *Server) incidentsView(c *gin.Context, p *principal, page web.Page, me w for i, r := range rows { v.Rows[i] = d.incidentRow(store.Incident{ ID: r.ID, OrgID: r.OrgID, MonitorID: r.MonitorID, StartedAt: r.StartedAt, ResolvedAt: r.ResolvedAt, Cause: r.Cause, + Title: r.Title, Status: r.Status, }, r.MonitorName) } if monitor != nil { diff --git a/internal/api/gdpr.go b/internal/api/gdpr.go index 789c943..8c6f2e3 100644 --- a/internal/api/gdpr.go +++ b/internal/api/gdpr.go @@ -337,6 +337,16 @@ type exportIncident struct { StartedAt time.Time `json:"started_at"` ResolvedAt *time.Time `json:"resolved_at"` Cause json.RawMessage `json:"cause"` + Title string `json:"title"` + Status *string `json:"status"` + Updates []exportUpdate `json:"updates"` +} + +type exportUpdate struct { + Status string `json:"status"` + Message string `json:"message"` + Public bool `json:"public"` + CreatedAt time.Time `json:"created_at"` } type exportAuditEntry struct { @@ -518,10 +528,19 @@ func (s *Server) buildOrgExport(ctx context.Context, p *principal) (orgExport, e if err != nil { return err } + updates, err := q.OrgIncidentUpdatesExport(ctx, org) + if err != nil { + return err + } + updatesOf := map[uuid.UUID][]exportUpdate{} + for _, u := range updates { + updatesOf[u.IncidentID] = append(updatesOf[u.IncidentID], exportUpdate{Status: u.Status, Message: u.Message, Public: u.Public, CreatedAt: u.CreatedAt}) + } x.Incidents = []exportIncident{} for _, i := range incidents { x.Incidents = append(x.Incidents, exportIncident{ID: i.ID, MonitorID: i.MonitorID, Monitor: i.Monitor, - StartedAt: i.StartedAt, ResolvedAt: i.ResolvedAt, Cause: rawJSON(i.Cause)}) + StartedAt: i.StartedAt, ResolvedAt: i.ResolvedAt, Cause: rawJSON(i.Cause), + Title: i.Title, Status: i.Status, Updates: orEmpty(updatesOf[i.ID])}) } audit, err := q.OrgAuditExport(ctx, org) diff --git a/internal/api/incident_updates.go b/internal/api/incident_updates.go new file mode 100644 index 0000000..fd142dc --- /dev/null +++ b/internal/api/incident_updates.go @@ -0,0 +1,288 @@ +package api + +import ( + "errors" + "net/http" + "slices" + "strings" + "time" + + "github.com/a-h/templ" + "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" + "git.zb-server.de/ZB-Server/uptimesebi/internal/web" +) + +// Incidents open and close with their monitor. People explain them with a +// title, a status and updates, public on status pages or internal notes. + +// incidentStatus is what an incident shows: resolved once its monitor +// recovered, otherwise the status of its latest update, empty before one. +func incidentStatus(i store.Incident) string { + if i.ResolvedAt != nil { + return "resolved" + } + return deref(i.Status) +} + +type incidentUpdateView struct { + ID uuid.UUID `json:"id"` + Status string `json:"status"` + Message string `json:"message"` + Public bool `json:"public"` + Author string `json:"author"` + CreatedAt time.Time `json:"created_at"` +} + +type incidentDetailView struct { + ID uuid.UUID `json:"id"` + MonitorID uuid.UUID `json:"monitor_id"` + Monitor string `json:"monitor"` + Title string `json:"title"` + Status string `json:"status"` + StartedAt time.Time `json:"started_at"` + ResolvedAt *time.Time `json:"resolved_at"` + Updates []incidentUpdateView `json:"updates"` +} + +// loadIncident returns the incident of the request with its updates. +func (s *Server) loadIncident(c *gin.Context) (store.GetIncidentRow, []store.ListIncidentUpdatesRow, bool) { + id, err := uuid.Parse(c.Param("id")) + if err != nil { + fail(c, http.StatusNotFound, "not_found") + return store.GetIncidentRow{}, nil, false + } + ctx := c.Request.Context() + var ( + inc store.GetIncidentRow + updates []store.ListIncidentUpdatesRow + ) + err = s.db.Tx(ctx, current(c).scope(), func(q *store.Queries) error { + var err error + if inc, err = q.GetIncident(ctx, id); err != nil { + return err + } + updates, err = q.ListIncidentUpdates(ctx, id) + return err + }) + if errors.Is(err, pgx.ErrNoRows) { + fail(c, http.StatusNotFound, "not_found") + return inc, nil, false + } + if err != nil { + internalError(c, err) + return inc, nil, false + } + return inc, updates, true +} + +func incidentOf(r store.GetIncidentRow) store.Incident { + return store.Incident{ + ID: r.ID, OrgID: r.OrgID, MonitorID: r.MonitorID, StartedAt: r.StartedAt, ResolvedAt: r.ResolvedAt, + Cause: r.Cause, Title: r.Title, Status: r.Status, + } +} + +func toIncidentDetail(inc store.GetIncidentRow, updates []store.ListIncidentUpdatesRow) incidentDetailView { + v := incidentDetailView{ + ID: inc.ID, MonitorID: inc.MonitorID, Monitor: inc.MonitorName, Title: inc.Title, + Status: incidentStatus(incidentOf(inc)), StartedAt: inc.StartedAt, ResolvedAt: inc.ResolvedAt, + Updates: []incidentUpdateView{}, + } + for _, u := range updates { + v.Updates = append(v.Updates, incidentUpdateView{ + ID: u.ID, Status: u.Status, Message: u.Message, Public: u.Public, Author: u.AuthorName, CreatedAt: u.CreatedAt, + }) + } + return v +} + +func (s *Server) getIncident(c *gin.Context) { + inc, updates, ok := s.loadIncident(c) + if ok { + c.JSON(http.StatusOK, toIncidentDetail(inc, updates)) + } +} + +// mayWriteIncident checks incidents.write for the incident's monitor, +// which roles limited to monitor groups grant too. +func (s *Server) mayWriteIncident(c *gin.Context, inc store.GetIncidentRow) bool { + p := current(c) + t, err := s.loadGroupTree(c.Request.Context(), p.scope()) + if err != nil { + internalError(c, err) + return false + } + if !canInGroup(p, authz.IncidentsWrite, t, inc.MonitorGroupID) { + fail(c, http.StatusForbidden, "forbidden") + return false + } + return true +} + +type incidentTitleRequest struct { + Title string `json:"title" binding:"max=200"` +} + +// setIncidentTitle names the incident, e.g. on status pages; empty shows +// the monitor's name. +func (s *Server) setIncidentTitle(c *gin.Context) { + var req incidentTitleRequest + if !bind(c, &req) { + return + } + inc, _, ok := s.loadIncident(c) + if !ok || !s.mayWriteIncident(c, inc) { + return + } + ctx := c.Request.Context() + if err := s.db.Tx(ctx, current(c).scope(), func(q *store.Queries) error { + _, err := q.SetIncidentTitle(ctx, store.SetIncidentTitleParams{ID: inc.ID, Title: strings.TrimSpace(req.Title)}) + return err + }); err != nil { + internalError(c, err) + return + } + auditDetail(c, "incident_id", inc.ID.String()) + c.Status(http.StatusNoContent) +} + +type incidentUpdateRequest struct { + Status string `json:"status" binding:"required"` + Message string `json:"message" binding:"required,max=5000"` + // Public shows the update on status pages; otherwise it is an internal + // note. Defaults to public. + Public *bool `json:"public"` +} + +// addIncidentUpdate tells what is going on: a status and a message. +func (s *Server) addIncidentUpdate(c *gin.Context) { + var req incidentUpdateRequest + if !bind(c, &req) { + return + } + req.Message = strings.TrimSpace(req.Message) + if !slices.Contains(web.IncidentStatuses, req.Status) || req.Message == "" { + fail(c, http.StatusUnprocessableEntity, "invalid_input") + return + } + inc, _, ok := s.loadIncident(c) + if !ok || !s.mayWriteIncident(c, inc) { + return + } + public := req.Public == nil || *req.Public + p := current(c) + var author *uuid.UUID + if p.Session != nil { + author = &p.UserID + } + ctx := c.Request.Context() + var u store.IncidentUpdate + if err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error { + var err error + u, err = q.AddIncidentUpdate(ctx, store.AddIncidentUpdateParams{ + OrgID: p.Org.ID, IncidentID: inc.ID, Status: req.Status, Message: req.Message, Public: public, AuthorID: author, + }) + if err != nil { + return err + } + return q.RefreshIncidentStatus(ctx, inc.ID) + }); err != nil { + internalError(c, err) + return + } + auditDetail(c, "incident_id", inc.ID.String()) + auditDetail(c, "status", req.Status) + c.JSON(http.StatusCreated, incidentUpdateView{ID: u.ID, Status: u.Status, Message: u.Message, Public: u.Public, CreatedAt: u.CreatedAt}) +} + +func (s *Server) deleteIncidentUpdate(c *gin.Context) { + update, err := uuid.Parse(c.Param("update")) + if err != nil { + fail(c, http.StatusNotFound, "not_found") + return + } + inc, _, ok := s.loadIncident(c) + if !ok || !s.mayWriteIncident(c, inc) { + return + } + ctx := c.Request.Context() + var n int64 + if err := s.db.Tx(ctx, current(c).scope(), func(q *store.Queries) error { + var err error + if n, err = q.DeleteIncidentUpdate(ctx, store.DeleteIncidentUpdateParams{ID: update, IncidentID: inc.ID}); err != nil || n == 0 { + return err + } + return q.RefreshIncidentStatus(ctx, inc.ID) + }); err != nil { + internalError(c, err) + return + } + if n == 0 { + fail(c, http.StatusNotFound, "not_found") + return + } + auditDetail(c, "incident_id", inc.ID.String()) + c.Status(http.StatusNoContent) +} + +// incidentDetailView is the console page of one incident. +func (s *Server) incidentDetailView(c *gin.Context, p *principal, page web.Page, me web.Me) (templ.Component, error) { + c.Set(ctxPrincipal, p) + inc, updates, ok := s.loadIncident(c) + if !ok { + return nil, errAborted + } + ctx := c.Request.Context() + d, err := s.loadMonitorData(ctx, p, web.RangeByKey("")) + if err != nil { + return nil, err + } + t, err := s.loadGroupTree(ctx, p.scope()) + if err != nil { + return nil, err + } + v := web.IncidentDetailView{ + Row: d.incidentRow(incidentOf(inc), inc.MonitorName), + CanWrite: canInGroup(p, authz.IncidentsWrite, t, inc.MonitorGroupID), + } + // Newest first; the monitor's own events among the updates. + type entry struct { + at time.Time + e web.IncidentTimelineEntry + } + entries := []entry{{inc.StartedAt, web.IncidentTimelineEntry{Kind: "started"}}} + if inc.ResolvedAt != nil { + entries = append(entries, entry{*inc.ResolvedAt, web.IncidentTimelineEntry{Kind: "resolved"}}) + } + for _, u := range updates { + html, err := web.RenderMarkdown(u.Message) + if err != nil { + return nil, err + } + entries = append(entries, entry{u.CreatedAt, web.IncidentTimelineEntry{ + Kind: "update", ID: u.ID.String(), Status: u.Status, HTML: html, Author: u.AuthorName, Public: u.Public, + }}) + } + slices.SortStableFunc(entries, func(a, b entry) int { return b.at.Compare(a.at) }) + for _, x := range entries { + x.e.At = x.at.UTC().Format(timeLayout) + v.Timeline = append(v.Timeline, x.e) + } + v.NextStatus = nextIncidentStatus(v.Row.Status) + return web.IncidentDetailPage(page, me, v), nil +} + +// nextIncidentStatus suggests the status after current: usually one step +// further, staying at resolved. +func nextIncidentStatus(current string) string { + i := slices.Index(web.IncidentStatuses, current) + if i < 0 { + return web.IncidentStatuses[0] + } + return web.IncidentStatuses[min(i+1, len(web.IncidentStatuses)-1)] +} diff --git a/internal/api/incident_updates_test.go b/internal/api/incident_updates_test.go new file mode 100644 index 0000000..7e2f324 --- /dev/null +++ b/internal/api/incident_updates_test.go @@ -0,0 +1,121 @@ +package api_test + +import ( + "context" + "net/http" + "strings" + "testing" + "time" + + "github.com/google/uuid" + "github.com/jackc/pgx/v5" + + "git.zb-server.de/ZB-Server/uptimesebi/internal/agentapi" +) + +func TestIncidentUpdates(t *testing.T) { + e := newEnv(t) + ctx := context.Background() + owner := e.browser(t) + owner.signup("o@"+uniq("iu")+".test", uniq("iu-")) + _, m := owner.do("POST", "/api/v1/org/monitors", map[string]any{"name": "Login", "type": "heartbeat", "interval_seconds": 3600}) + monitorID := m["id"].(string) + slug := uniq("iup-") + _, page := owner.do("POST", "/api/v1/org/statuspages", map[string]any{"slug": slug, "title": "Acme"}) + pageID := page["id"].(string) + owner.do("PUT", "/api/v1/org/statuspages/"+pageID, map[string]any{"slug": slug, "title": "Acme", "published": true}) + if st, body := owner.do("PUT", "/api/v1/org/statuspages/"+pageID+"/monitors", map[string]any{"monitors": []map[string]any{{"monitor_id": monitorID}}}); st != http.StatusNoContent && st != http.StatusOK { + t.Fatalf("list monitor on page = %d %v", st, body) + } + var incident uuid.UUID + if err := e.asSystem(t, func(tx pgx.Tx) error { + return tx.QueryRow(ctx, `INSERT INTO incidents (org_id, monitor_id, started_at, cause) + SELECT org_id, id, now() - interval '10 minutes', '{}' FROM monitors WHERE id = $1 RETURNING id`, monitorID).Scan(&incident) + }); err != nil { + t.Fatal(err) + } + base := "/api/v1/org/incidents/" + incident.String() + status := func() string { + _, body := owner.do("GET", base, nil) + s, _ := body["status"].(string) + return s + } + if s := status(); s != "" { + t.Errorf("status before any update = %q", s) + } + + // Updates with a status, public or internal, and a title. + for _, bad := range []map[string]any{ + {"status": "panicking", "message": "x"}, + {"status": "investigating", "message": " "}, + } { + st, body := owner.do("POST", base+"/updates", bad) + expect(t, "invalid update", st, body, http.StatusUnprocessableEntity, "invalid_input") + } + if st, body := owner.do("POST", base+"/updates", map[string]any{"status": "investigating", "message": "We are **looking** into it."}); st != http.StatusCreated { + t.Fatalf("post update = %d %v", st, body) + } + if st, body := owner.do("PATCH", base, map[string]any{"title": "Sign-in is slow"}); st != http.StatusNoContent { + t.Fatalf("set title = %d %v", st, body) + } + _, note := owner.do("POST", base+"/updates", map[string]any{"status": "identified", "message": "DB failover, ask Bob", "public": false}) + if s := status(); s != "identified" { + t.Errorf("status = %q, want the latest update's", s) + } + _, list := owner.do("GET", "/api/v1/org/incidents", nil) + if first := list["incidents"].([]any)[0].(map[string]any); first["title"] != "Sign-in is slow" || first["status"] != "identified" { + t.Errorf("incident list = %v", first) + } + + // Status pages show the title, the status and only public updates. + snap, err := e.statuspageClient(t, nil).Page(ctx, "", slug) + if err != nil { + t.Fatal(err) + } + var shown agentapi.PageIncident + for _, i := range snap.Incidents { + if i.Component == "Login" { + shown = i + } + } + if shown.Title != "Sign-in is slow" || shown.Status != "identified" || len(shown.Updates) != 1 || !strings.Contains(shown.Updates[0].Message, "looking") { + t.Errorf("status page incident = %+v", shown) + } + + // The console page tells the story, internal notes marked. + _, _, html := owner.page("/incidents/" + incident.String()) + for _, want := range []string{"Sign-in is slow", "looking", "DB failover", ">internal<", "Post update", "Outage began"} { + if !strings.Contains(html, want) { + t.Errorf("incident page lacks %q", want) + } + } + + // Readers read, writers write. + viewer := e.joinVia(t, owner.invite("v@"+uniq("iu")+".test", owner.roleID("viewer"))) + if st, _ := viewer.do("GET", base, nil); st != http.StatusOK { + t.Errorf("viewer reads incident = %d", st) + } + st, body := viewer.do("POST", base+"/updates", map[string]any{"status": "monitoring", "message": "x"}) + expect(t, "viewer posts update", st, body, http.StatusForbidden, "forbidden") + if _, _, html := viewer.page("/incidents/" + incident.String()); strings.Contains(html, "Post update") { + t.Error("the viewer is offered the update form") + } + + // Deleting an update falls back to the previous status; the monitor + // recovering resolves the incident whatever was said. + if st, _ := owner.do("DELETE", base+"/updates/"+note["id"].(string), nil); st != http.StatusNoContent || status() != "investigating" { + t.Errorf("after deleting the latest update status = %q", status()) + } + if err := e.asSystem(t, func(tx pgx.Tx) error { + _, err := tx.Exec(ctx, `UPDATE incidents SET resolved_at = $2 WHERE id = $1`, incident, time.Now()) + return err + }); err != nil { + t.Fatal(err) + } + if s := status(); s != "resolved" { + t.Errorf("status after recovery = %q", s) + } + if st, _ := owner.do("GET", "/api/v1/org/incidents/"+uuid.NewString(), nil); st != http.StatusNotFound { + t.Errorf("unknown incident = %d", st) + } +} diff --git a/internal/api/pages.go b/internal/api/pages.go index f2284db..25187fb 100644 --- a/internal/api/pages.go +++ b/internal/api/pages.go @@ -47,6 +47,7 @@ func (s *Server) registerPages(r gin.IRouter) { r.GET("/admin/orgs", s.adminOrgsPage) r.GET("/admin/legal", s.adminLegalPage) r.GET("/settings/legal", s.orgPage("legal.org_title", authz.OrgManage, s.orgLegalView)) + r.GET("/incidents/:id", s.orgPage("incidents.title", authz.IncidentsRead, s.incidentDetailView)) r.GET("/legal/:kind", s.legalPage) r.GET("/consent", s.consentPage) r.GET("/account/suspended", s.suspendedPage) diff --git a/internal/api/server.go b/internal/api/server.go index ae04705..dc836cf 100644 --- a/internal/api/server.go +++ b/internal/api/server.go @@ -223,6 +223,10 @@ func (s *Server) Mount(r gin.IRouter) { page.GET("/export", canPage(authz.StatusPagesRead), s.exportStatusPage) org.GET("/incidents", can(authz.IncidentsRead), s.listIncidents) + org.GET("/incidents/:id", can(authz.IncidentsRead), s.getIncident) + org.PATCH("/incidents/:id", s.setIncidentTitle) + org.POST("/incidents/:id/updates", s.addIncidentUpdate) + org.DELETE("/incidents/:id/updates/:update", s.deleteIncidentUpdate) org.GET("/audit", can(authz.AuditRead), s.listOrgAudit) org.GET("/alert-groups", can(authz.NotificationsRead), s.listAlertGroups) diff --git a/internal/api/statuspages.go b/internal/api/statuspages.go index cf6e665..d608b5b 100644 --- a/internal/api/statuspages.go +++ b/internal/api/statuspages.go @@ -62,6 +62,7 @@ func (s *Server) buildSnapshot(ctx context.Context, page store.StatusPage) (agen hourly []store.HourlyBucketsRow regions []store.Region incidents []store.Incident + updates []store.PublicIncidentUpdatesRow planned map[uuid.UUID][]store.MaintenanceWindow ) now := time.Now() @@ -101,6 +102,13 @@ func (s *Server) buildSnapshot(ctx context.Context, page store.StatusPage) (agen if incidents, err = q.IncidentsForMonitors(ctx, store.IncidentsForMonitorsParams{Ids: ids, Since: ptr(now.Add(-incidentLookback))}); err != nil { return err } + incidentIDs := make([]uuid.UUID, len(incidents)) + for i, inc := range incidents { + incidentIDs[i] = inc.ID + } + if updates, err = q.PublicIncidentUpdates(ctx, incidentIDs); err != nil { + return err + } if planned, err = maintenanceFor(ctx, q, ids); err != nil { return err } @@ -191,8 +199,15 @@ func (s *Server) buildSnapshot(ctx context.Context, page store.StatusPage) (agen snap.Sections = append(snap.Sections, buildPageSections(newPageGroupTree(pageGroups), byGroup)...) snap.Status = agentapi.Summarize(states) snap.Maintenance = pageMaintenance(planned, names, now) + updatesOf := map[uuid.UUID][]agentapi.PageIncidentUpdate{} + for _, u := range updates { + updatesOf[u.IncidentID] = append(updatesOf[u.IncidentID], agentapi.PageIncidentUpdate{Status: u.Status, Message: u.Message, At: u.CreatedAt}) + } for _, i := range incidents { - snap.Incidents = append(snap.Incidents, agentapi.PageIncident{Component: names[i.MonitorID], StartedAt: i.StartedAt, ResolvedAt: i.ResolvedAt}) + snap.Incidents = append(snap.Incidents, agentapi.PageIncident{ + Component: names[i.MonitorID], StartedAt: i.StartedAt, ResolvedAt: i.ResolvedAt, + Title: i.Title, Status: incidentStatus(i), Updates: updatesOf[i.ID], + }) } return snap, nil } diff --git a/internal/i18n/locales/de.json b/internal/i18n/locales/de.json index b0d513a..120c46c 100644 --- a/internal/i18n/locales/de.json +++ b/internal/i18n/locales/de.json @@ -89,6 +89,9 @@ "audit.action.group.create": "Gruppe erstellt", "audit.action.group.delete": "Gruppe gelöscht", "audit.action.group.update": "Gruppe geändert", + "audit.action.incident.title": "Ausfall umbenannt", + "audit.action.incident.update": "Update zu einem Ausfall veröffentlicht", + "audit.action.incident.update_delete": "Update zu einem Ausfall gelöscht", "audit.action.invitation.create": "Einladung verschickt", "audit.action.invitation.delete": "Einladung zurückgezogen", "audit.action.maintenance.create": "Wartung geplant", @@ -718,6 +721,7 @@ "export.field.locale": "Sprache", "export.field.member_since": "Mitglied seit", "export.field.members": "Mitglieder", + "export.field.message": "Nachricht", "export.field.monitor": "Monitor", "export.field.monitor_groups": "Monitorgruppen", "export.field.monitor_id": "Monitor-ID", @@ -734,6 +738,7 @@ "export.field.platform_admin": "Plattform-Admin", "export.field.prefix": "Präfix", "export.field.provider": "Anbieter", + "export.field.public": "Öffentlich", "export.field.published": "Veröffentlicht", "export.field.region": "Region", "export.field.region_ids": "Regionen", @@ -760,6 +765,7 @@ "export.field.total": "Checks", "export.field.totp_enabled_at": "Zwei-Faktor aktiviert", "export.field.type": "Typ", + "export.field.updates": "Updates", "export.field.user_agent": "Browser", "export.field.version": "Version", "export.json_only": "Nur im JSON-Export enthalten.", @@ -804,6 +810,26 @@ "idp.kind_oidc": "OpenID Connect (Google, Microsoft, GitLab, Keycloak, …)", "idp.signup_open": "Registrierung offen", "idp.title": "Anmelde-Anbieter", + "incident.began": "Ausfall begann", + "incident.delete": "Löschen", + "incident.delete_confirm": "Dieses Update löschen? Es verschwindet auch von den Statusseiten.", + "incident.internal": "intern", + "incident.message": "Was ist los", + "incident.post": "Update veröffentlichen", + "incident.post_update": "Update veröffentlichen", + "incident.public": "Auf Statusseiten zeigen", + "incident.public_hint": "Ausgeschaltet bleibt es eine interne Notiz für dein Team.", + "incident.recovered": "Monitor wieder erreichbar", + "incident.status": "Status", + "incident.status.identified": "Ursache gefunden", + "incident.status.investigating": "Untersuchung läuft", + "incident.status.monitoring": "Beobachtung", + "incident.status.resolved": "Behoben", + "incident.timeline": "Verlauf", + "incident.title_heading": "Titel", + "incident.title_hint": "Erscheint auf Statusseiten; leer zeigt den Namen des Monitors.", + "incident.title_label": "Titel", + "incident.title_placeholder": "Anmeldung langsam", "incidents.all": "Alle Vorfälle", "incidents.all_of_monitor": "Alle Vorfälle dieses Monitors", "incidents.none": "Bisher keine Incidents.", diff --git a/internal/i18n/locales/en.json b/internal/i18n/locales/en.json index ddb20ee..f15bb16 100644 --- a/internal/i18n/locales/en.json +++ b/internal/i18n/locales/en.json @@ -89,6 +89,9 @@ "audit.action.group.create": "Group created", "audit.action.group.delete": "Group deleted", "audit.action.group.update": "Group changed", + "audit.action.incident.title": "Incident renamed", + "audit.action.incident.update": "Incident update posted", + "audit.action.incident.update_delete": "Incident update deleted", "audit.action.invitation.create": "Invitation sent", "audit.action.invitation.delete": "Invitation withdrawn", "audit.action.maintenance.create": "Maintenance planned", @@ -718,6 +721,7 @@ "export.field.locale": "Language", "export.field.member_since": "Member since", "export.field.members": "Members", + "export.field.message": "Message", "export.field.monitor": "Monitor", "export.field.monitor_groups": "Monitor groups", "export.field.monitor_id": "Monitor ID", @@ -734,6 +738,7 @@ "export.field.platform_admin": "Platform admin", "export.field.prefix": "Prefix", "export.field.provider": "Provider", + "export.field.public": "Public", "export.field.published": "Published", "export.field.region": "Region", "export.field.region_ids": "Regions", @@ -760,6 +765,7 @@ "export.field.total": "Checks", "export.field.totp_enabled_at": "Two-factor enabled", "export.field.type": "Type", + "export.field.updates": "Updates", "export.field.user_agent": "Browser", "export.field.version": "Version", "export.json_only": "Included in the JSON export only.", @@ -804,6 +810,26 @@ "idp.kind_oidc": "OpenID Connect (Google, Microsoft, GitLab, Keycloak, …)", "idp.signup_open": "sign-up open", "idp.title": "Sign-in providers", + "incident.began": "Outage began", + "incident.delete": "Delete", + "incident.delete_confirm": "Delete this update? It disappears from status pages too.", + "incident.internal": "internal", + "incident.message": "What is going on", + "incident.post": "Post update", + "incident.post_update": "Post an update", + "incident.public": "Show on status pages", + "incident.public_hint": "Off keeps it an internal note for your team.", + "incident.recovered": "Monitor recovered", + "incident.status": "Status", + "incident.status.identified": "Identified", + "incident.status.investigating": "Investigating", + "incident.status.monitoring": "Monitoring", + "incident.status.resolved": "Resolved", + "incident.timeline": "Timeline", + "incident.title_heading": "Title", + "incident.title_hint": "Shown on status pages; empty shows the monitor's name.", + "incident.title_label": "Title", + "incident.title_placeholder": "Sign-in is slow", "incidents.all": "All incidents", "incidents.all_of_monitor": "All incidents of this monitor", "incidents.none": "No incidents so far.", diff --git a/internal/migrations/sql/00048_incident_updates.sql b/internal/migrations/sql/00048_incident_updates.sql new file mode 100644 index 0000000..62b7d88 --- /dev/null +++ b/internal/migrations/sql/00048_incident_updates.sql @@ -0,0 +1,31 @@ +-- +goose Up +-- Incidents open and close with their monitor; people tell what is going +-- on through a title, a status and updates, public on status pages or +-- internal. +ALTER TABLE incidents ADD COLUMN title text NOT NULL DEFAULT '' CHECK (length(title) <= 200); +-- The status of the latest update, NULL before the first. +ALTER TABLE incidents ADD COLUMN status text + CHECK (status IN ('investigating', 'identified', 'monitoring', 'resolved')); + +CREATE TABLE incident_updates ( + id uuid PRIMARY KEY DEFAULT gen_random_uuid(), + org_id uuid NOT NULL REFERENCES orgs (id) ON DELETE CASCADE, + incident_id uuid NOT NULL REFERENCES incidents (id) ON DELETE CASCADE, + status text NOT NULL CHECK (status IN ('investigating', 'identified', 'monitoring', 'resolved')), + message text NOT NULL CHECK (length(message) BETWEEN 1 AND 5000), + public boolean NOT NULL DEFAULT true, + author_id uuid REFERENCES users (id) ON DELETE SET NULL, + created_at timestamptz NOT NULL DEFAULT now() +); +CREATE INDEX incident_updates_incident_idx ON incident_updates (incident_id, created_at); + +ALTER TABLE incident_updates ENABLE ROW LEVEL SECURITY; +ALTER TABLE incident_updates FORCE ROW LEVEL SECURITY; +CREATE POLICY incident_updates_tenant ON incident_updates FOR ALL + USING (app_scope_system() OR org_id = app_org_id()) + WITH CHECK (app_scope_system() OR org_id = app_org_id()); + +-- +goose Down +DROP TABLE incident_updates; +ALTER TABLE incidents DROP COLUMN status; +ALTER TABLE incidents DROP COLUMN title; diff --git a/internal/statuspage/statuspage_test.go b/internal/statuspage/statuspage_test.go index 7667bfe..4bfc726 100644 --- a/internal/statuspage/statuspage_test.go +++ b/internal/statuspage/statuspage_test.go @@ -357,6 +357,13 @@ func TestNestedGroupsAndComponentDetails(t *testing.T) { }, Incidents: []agentapi.PageIncident{ {Component: "Public API", StartedAt: now.Add(-10 * time.Minute)}, + { + Component: "Website", StartedAt: now.Add(-time.Hour), Title: "Anmeldung langsam", Status: "monitoring", + Updates: []agentapi.PageIncidentUpdate{ + {Status: "monitoring", Message: "Fix ist **ausgerollt**.", At: now.Add(-5 * time.Minute)}, + {Status: "investigating", Message: "Wir schauen.\n\n", At: now.Add(-50 * time.Minute)}, + }, + }, }, } @@ -366,6 +373,18 @@ func TestNestedGroupsAndComponentDetails(t *testing.T) { }} h := newHarness(t, src, t.TempDir(), &now) + t.Run("incidents show their title, status and updates", func(t *testing.T) { + _, body := h.get("status.example.test", "/acme") + for _, want := range []string{"Anmeldung langsam", "Beobachtung", "Untersuchung läuft", "ausgerollt", "Wir schauen."} { + if !strings.Contains(body, want) { + t.Errorf("GET /acme missing %q", want) + } + } + if strings.Contains(body, "