diff --git a/go.mod b/go.mod index e9df13b..dfa1bcf 100644 --- a/go.mod +++ b/go.mod @@ -16,6 +16,7 @@ require ( github.com/pquerna/otp v1.5.0 github.com/pressly/goose/v3 v3.30.1 github.com/redis/go-redis/v9 v9.23.0 + github.com/yuin/goldmark v1.7.13 go.uber.org/zap v1.28.0 golang.org/x/crypto v0.59.0 golang.org/x/net v0.63.0 diff --git a/go.sum b/go.sum index 4c4b8e9..ab7f07d 100644 --- a/go.sum +++ b/go.sum @@ -146,6 +146,8 @@ github.com/ugorji/go/codec v1.3.1 h1:waO7eEiFDwidsBN6agj1vJQ4AG7lh2yqXyOXqhgQuyY github.com/ugorji/go/codec v1.3.1/go.mod h1:pRBVtBSKl77K30Bv8R2P+cLSGaTtex6fsA2Wjqmfxj4= github.com/xyproto/randomstring v1.0.5 h1:YtlWPoRdgMu3NZtP45drfy1GKoojuR7hmRcnhZqKjWU= github.com/xyproto/randomstring v1.0.5/go.mod h1:rgmS5DeNXLivK7YprL0pY+lTuhNQW3iGxZ18UQApw/E= +github.com/yuin/goldmark v1.7.13 h1:GPddIs617DnBLFFVJFgpo1aBfe/4xcvMc3SB5t/D0pA= +github.com/yuin/goldmark v1.7.13/go.mod h1:ip/1k0VRfGynBgxOz0yCqHrbZXhcjxyuS66Brc7iBKg= github.com/zeebo/assert v1.1.0 h1:hU1L1vLTHsnO8x8c9KAR5GmM5QscxHg5RNU5z5qbUWY= github.com/zeebo/assert v1.1.0/go.mod h1:Pq9JiuJQpG8JLJdtkwrJESF0Foym2/D9XMU5ciN/wJ0= github.com/zeebo/blake3 v0.2.4 h1:KYQPkhpRtcqh0ssGYcKLG1JYvddkEA8QwCM/yBqhaZI= diff --git a/internal/agentapi/pages.go b/internal/agentapi/pages.go index b74ec44..e71cb3e 100644 --- a/internal/agentapi/pages.go +++ b/internal/agentapi/pages.go @@ -63,6 +63,28 @@ type PageSnapshot struct { Sections []Section `json:"sections"` Incidents []PageIncident `json:"incidents"` GeneratedAt time.Time `json:"generated_at"` + // Legal holds the legal notice and privacy policy shown on the page. + // They travel with the snapshot so they stay available during an API + // outage, which some jurisdictions require. + Legal []LegalDoc `json:"legal,omitempty"` +} + +// LegalDoc is a legal notice ("imprint") or privacy policy ("privacy"): +// a link to a page elsewhere or Markdown to render. +type LegalDoc struct { + Kind string `json:"kind"` + URL string `json:"url,omitempty"` + Markdown string `json:"markdown,omitempty"` +} + +// LegalDocByKind returns the document of kind, if any. +func (s PageSnapshot) LegalDocByKind(kind string) (LegalDoc, bool) { + for _, d := range s.Legal { + if d.Kind == kind { + return d, true + } + } + return LegalDoc{}, false } // ErrNotFound means no published page matches. diff --git a/internal/api/legal.go b/internal/api/legal.go new file mode 100644 index 0000000..b637f79 --- /dev/null +++ b/internal/api/legal.go @@ -0,0 +1,228 @@ +package api + +import ( + "context" + "net/http" + "net/url" + "slices" + "strings" + "sync" + "time" + + "github.com/a-h/templ" + "github.com/gin-gonic/gin" + "github.com/google/uuid" + + "git.zb-server.de/ZB-Server/uptimesebi/internal/agentapi" + "git.zb-server.de/ZB-Server/uptimesebi/internal/store" + "git.zb-server.de/ZB-Server/uptimesebi/internal/tenant" + "git.zb-server.de/ZB-Server/uptimesebi/internal/web" +) + +// mergeLegal picks one document per kind, the organization's over the +// platform's. rows come organization first. +func mergeLegal(rows []store.LegalDocument) []agentapi.LegalDoc { + out := []agentapi.LegalDoc{} + seen := map[string]bool{} + for _, r := range rows { + if seen[r.Kind] || (r.Url == "" && r.Markdown == "") { + continue + } + seen[r.Kind] = true + out = append(out, agentapi.LegalDoc{Kind: r.Kind, URL: r.Url, Markdown: r.Markdown}) + } + return out +} + +// platformLegal caches the platform's documents, which every console page +// links in its footer. +type platformLegal struct { + mu sync.Mutex + docs []agentapi.LegalDoc + fetched time.Time +} + +const legalCacheTTL = 30 * time.Second + +func (s *Server) platformLegalDocs(ctx context.Context) []agentapi.LegalDoc { + s.legal.mu.Lock() + defer s.legal.mu.Unlock() + if time.Since(s.legal.fetched) < legalCacheTTL { + return s.legal.docs + } + var rows []store.LegalDocument + err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error { + var err error + rows, err = q.LegalDocuments(ctx, nil) + return err + }) + if err != nil { + s.log.WarnContext(ctx, "loading legal documents failed", "error", err) + return s.legal.docs + } + s.legal.docs, s.legal.fetched = mergeLegal(rows), time.Now() + return s.legal.docs +} + +func (s *Server) forgetPlatformLegal() { + s.legal.mu.Lock() + s.legal.fetched = time.Time{} + s.legal.mu.Unlock() +} + +func validLegalKind(kind string) bool { return slices.Contains(web.LegalKinds, kind) } + +type legalRequest struct { + URL string `json:"url" binding:"max=2000"` + Markdown string `json:"markdown" binding:"max=100000"` +} + +// validLegalURL accepts absolute http and https URLs only, so a stored link +// cannot run script when clicked. +func validLegalURL(raw string) bool { + u, err := url.Parse(raw) + return err == nil && (u.Scheme == "https" || u.Scheme == "http") && u.Host != "" +} + +// saveLegal stores or, with both fields empty, removes a document of org, +// nil for the platform. +func (s *Server) saveLegal(c *gin.Context, scope tenant.Scope, org *uuid.UUID) bool { + kind := c.Param("kind") + if !validLegalKind(kind) { + fail(c, http.StatusNotFound, "not_found") + return false + } + var req legalRequest + if !bind(c, &req) { + return false + } + req.URL, req.Markdown = strings.TrimSpace(req.URL), strings.TrimSpace(req.Markdown) + if req.URL != "" && !validLegalURL(req.URL) { + fail(c, http.StatusUnprocessableEntity, "invalid_legal_url") + return false + } + auditDetail(c, "kind", kind) + ctx := c.Request.Context() + err := s.db.Tx(ctx, scope, func(q *store.Queries) error { + if req.URL == "" && req.Markdown == "" { + return q.DeleteLegalDocument(ctx, store.DeleteLegalDocumentParams{OrgID: org, Kind: kind}) + } + return q.UpsertLegalDocument(ctx, store.UpsertLegalDocumentParams{OrgID: org, Kind: kind, Url: req.URL, Markdown: req.Markdown}) + }) + if err != nil { + internalError(c, err) + return false + } + c.Status(http.StatusNoContent) + return true +} + +func (s *Server) adminSaveLegal(c *gin.Context) { + if s.saveLegal(c, tenant.System(), nil) { + s.forgetPlatformLegal() + } +} + +func (s *Server) orgSaveLegal(c *gin.Context) { + p := current(c) + s.saveLegal(c, p.scope(), &p.Org.ID) +} + +type legalView struct { + Kind string `json:"kind"` + URL string `json:"url"` + Markdown string `json:"markdown"` +} + +// ownLegal returns the documents stored for org (nil: the platform), +// without fallbacks. +func (s *Server) ownLegal(ctx context.Context, scope tenant.Scope, org *uuid.UUID) ([]legalView, error) { + var rows []store.LegalDocument + err := s.db.Tx(ctx, scope, func(q *store.Queries) error { + var err error + rows, err = q.LegalDocuments(ctx, org) + return err + }) + out := make([]legalView, 0, len(web.LegalKinds)) + for _, kind := range web.LegalKinds { + v := legalView{Kind: kind} + for _, r := range rows { + if r.Kind == kind && (r.OrgID == nil) == (org == nil) { + v.URL, v.Markdown = r.Url, r.Markdown + } + } + out = append(out, v) + } + return out, err +} + +func (s *Server) adminListLegal(c *gin.Context) { + docs, err := s.ownLegal(c.Request.Context(), tenant.System(), nil) + if err != nil { + internalError(c, err) + return + } + c.JSON(http.StatusOK, gin.H{"documents": docs}) +} + +func (s *Server) orgListLegal(c *gin.Context) { + p := current(c) + docs, err := s.ownLegal(c.Request.Context(), p.scope(), &p.Org.ID) + if err != nil { + internalError(c, err) + return + } + c.JSON(http.StatusOK, gin.H{"documents": docs}) +} + +// legalPage serves a platform document to anyone: Markdown rendered here, +// links redirected. +func (s *Server) legalPage(c *gin.Context) { + kind := c.Param("kind") + for _, d := range s.platformLegalDocs(c.Request.Context()) { + if d.Kind != kind { + continue + } + if d.URL != "" { + c.Redirect(http.StatusFound, d.URL) + return + } + html, err := web.RenderMarkdown(d.Markdown) + if err != nil { + internalError(c, err) + return + } + web.Render(c, http.StatusOK, web.LegalPage(s.pageFor(c, web.LegalTitleID(kind)), html)) + return + } + c.Status(http.StatusNotFound) +} + +func toLegalForms(docs []legalView) []web.LegalForm { + out := make([]web.LegalForm, len(docs)) + for i, d := range docs { + out[i] = web.LegalForm{Kind: d.Kind, URL: d.URL, Markdown: d.Markdown} + } + return out +} + +func (s *Server) orgLegalView(c *gin.Context, p *principal, page web.Page, me web.Me) (templ.Component, error) { + docs, err := s.ownLegal(c.Request.Context(), p.scope(), &p.Org.ID) + if err != nil { + return nil, err + } + return web.LegalSettingsPage(page, me, "legal.org_title", "legal.org_intro", "/org/legal/", "/settings/legal", toLegalForms(docs)), nil +} + +func (s *Server) adminLegalPage(c *gin.Context) { + me, ok := s.adminMe(c) + if !ok { + return + } + docs, err := s.ownLegal(c.Request.Context(), tenant.System(), nil) + if err != nil { + internalError(c, err) + return + } + web.Render(c, http.StatusOK, web.LegalSettingsPage(s.pageFor(c, "legal.platform_title"), me, "legal.platform_title", "legal.platform_intro", "/admin/legal/", "/admin/legal", toLegalForms(docs))) +} diff --git a/internal/api/legal_test.go b/internal/api/legal_test.go new file mode 100644 index 0000000..10c24c8 --- /dev/null +++ b/internal/api/legal_test.go @@ -0,0 +1,103 @@ +package api_test + +import ( + "context" + "net/http" + "strings" + "testing" + + "git.zb-server.de/ZB-Server/uptimesebi/internal/agentapi" + "git.zb-server.de/ZB-Server/uptimesebi/internal/store" + "git.zb-server.de/ZB-Server/uptimesebi/internal/tenant" +) + +func TestLegalDocuments(t *testing.T) { + e := newEnv(t) + admin := e.browser(t) + admin.signup("a@"+uniq("lg")+".test", uniq("lg-")) + err := tenant.New(e.dbPool).Tx(context.Background(), tenant.Global(), func(q *store.Queries) error { + return q.MakeAdmin(context.Background(), admin.userIDSelf()) + }) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { + for _, kind := range []string{"imprint", "privacy"} { + admin.do("PUT", "/api/v1/admin/legal/"+kind, map[string]any{}) + } + }) + + imprint := "# Impressum\n\nBetreiber GmbH " + st, body := admin.do("PUT", "/api/v1/admin/legal/imprint", map[string]any{"markdown": imprint}) + expect(t, "admin sets imprint", st, body, http.StatusNoContent, "") + st, body = admin.do("PUT", "/api/v1/admin/legal/privacy", map[string]any{"url": "javascript:alert(1)"}) + expect(t, "javascript link", st, body, http.StatusUnprocessableEntity, "invalid_legal_url") + st, body = admin.do("PUT", "/api/v1/admin/legal/privacy", map[string]any{"url": "https://operator.example/privacy"}) + expect(t, "admin sets privacy link", st, body, http.StatusNoContent, "") + st, body = admin.do("PUT", "/api/v1/admin/legal/terms", map[string]any{"markdown": "x"}) + expect(t, "unknown kind", st, body, http.StatusNotFound, "not_found") + + // The console footer links them, also before signing in. + _, _, login := e.browser(t).page("/login") + if !strings.Contains(login, `href="/legal/imprint"`) || !strings.Contains(login, `href="https://operator.example/privacy"`) { + t.Error("login page footer lacks the legal links") + } + st, _, html := e.browser(t).page("/legal/imprint") + if st != http.StatusOK || !strings.Contains(html, "