diff --git a/.env.example b/.env.example index 1b6ae8a..fdf6210 100644 --- a/.env.example +++ b/.env.example @@ -49,6 +49,15 @@ UPTIME_TEST_REDIS_URL=redis://localhost:6379/15 # regions) get an email; 0 switches it off. # UPTIME_REGION_ALERT_AFTER=5m +# Status page servers ask before ordering a certificate for a custom domain. +# New orders (not renewals) are limited per organization and day, per hour +# for all servers sharing an ACME account (the platform's, or one +# organization's), and per domain and day. Let's Encrypt allows 300 new +# orders per account in 3 hours. +# UPTIME_CERTS_PER_ORG_PER_DAY=20 +# UPTIME_CERTS_PER_HOUR=30 +# UPTIME_CERTS_PER_NAME_PER_DAY=5 + # Data retention (0 keeps forever). Raw results feed charts up to 24h, the # hourly aggregate 7d and 30d, the daily aggregate up to a year; resolved # incidents follow the daily aggregate. diff --git a/cmd/api/main.go b/cmd/api/main.go index f178a84..f7cc2ed 100644 --- a/cmd/api/main.go +++ b/cmd/api/main.go @@ -93,6 +93,7 @@ func run(log *slog.Logger, level *slog.LevelVar, args []string) error { go srv.RunNotifier(ctx) go srv.RunHousekeeping(ctx) go srv.RunRegionWatch(ctx) + go srv.RunDomainWatch(ctx) go srv.RunHeartbeats(ctx) return platform.Serve(ctx, log, platform.NewHTTPServer(cfg.Listen, r), health, 5*time.Second, cfg.ShutdownTimeout) diff --git a/cmd/statuspage/main.go b/cmd/statuspage/main.go index 7e3140f..c45ce0b 100644 --- a/cmd/statuspage/main.go +++ b/cmd/statuspage/main.go @@ -119,6 +119,7 @@ func certificates(ctx context.Context, cfg config.StatusPage, client *agentapi.C magic = certmagic.New(cache, certmagic.Config{ Storage: statuspage.NewCertStorage(client, certDir), OnDemand: &certmagic.OnDemandConfig{DecisionFunc: pages.AllowCertificate}, + OnEvent: pages.OnCertEvent, Logger: zap.NewNop(), }) issuer := certmagic.NewACMEIssuer(magic, certmagic.ACMEIssuer{CA: cfg.ACMECA, Email: cfg.ACMEEmail, Agreed: true}) diff --git a/internal/agentapi/agentapi.go b/internal/agentapi/agentapi.go index 83ed4f1..eba6435 100644 --- a/internal/agentapi/agentapi.go +++ b/internal/agentapi/agentapi.go @@ -162,6 +162,8 @@ func (c *Client) doWith(ctx context.Context, method, path string, header http.He return ErrNotFound case resp.StatusCode == http.StatusNotModified: return ErrNotModified + case resp.StatusCode == http.StatusTooManyRequests: + return ErrRateLimited case resp.StatusCode >= 300: msg, _ := io.ReadAll(io.LimitReader(resp.Body, 1024)) return fmt.Errorf("agentapi: %s %s: %d %s", method, path, resp.StatusCode, bytes.TrimSpace(msg)) diff --git a/internal/agentapi/storage.go b/internal/agentapi/storage.go index a759276..9e3623d 100644 --- a/internal/agentapi/storage.go +++ b/internal/agentapi/storage.go @@ -106,3 +106,13 @@ func (c *Client) StorageUnlock(ctx context.Context, name string) error { _, err := c.raw(ctx, http.MethodDelete, "/storage/lock"+keyQuery("name", name), nil) return err } + +// ErrRateLimited means the API refused because a limit was reached. +var ErrRateLimited = errors.New("agentapi: rate limited") + +// AllowCertificate asks whether this server may order a new certificate +// for name. ErrNotFound means it serves no page there, ErrRateLimited that +// a limit on orders was reached. +func (c *Client) AllowCertificate(ctx context.Context, name string) error { + return c.do(ctx, http.MethodPost, "/certificates", map[string]string{"name": name}, nil) +} diff --git a/internal/api/agent.go b/internal/api/agent.go index 952df2d..66bcb24 100644 --- a/internal/api/agent.go +++ b/internal/api/agent.go @@ -49,6 +49,7 @@ func (s *Server) mountAgentAPI(r gin.IRouter) { sp.GET("/storage/list", s.storageList) sp.POST("/storage/lock", s.storageLock) sp.DELETE("/storage/lock", s.storageUnlock) + sp.POST("/certificates", s.agentCertificate) checker := g.Group("", requireAgentKind("checker")) checker.POST("/jobs", s.agentJobs) checker.POST("/results", s.agentResults) diff --git a/internal/api/certificates.go b/internal/api/certificates.go new file mode 100644 index 0000000..12d8a1b --- /dev/null +++ b/internal/api/certificates.go @@ -0,0 +1,47 @@ +package api + +import ( + "net/http" + "strings" + "time" + + "github.com/gin-gonic/gin" +) + +// A status page server obtains certificates for custom domains on demand, +// on the first visit over HTTPS. Before it orders a new one from its CA it +// asks here: only for a verified domain of a page it serves, and within the +// limits of UPTIME_CERTS_*. The limits count across all instances and keep +// one organization, or a flood of handshakes for many names, from using up +// the CA's rate limits that the other organizations share. + +type certificateRequest struct { + Name string `json:"name" binding:"required,max=253"` +} + +func (s *Server) agentCertificate(c *gin.Context) { + var req certificateRequest + if !bind(c, &req) { + return + } + name := strings.TrimSuffix(strings.ToLower(strings.TrimSpace(req.Name)), ".") + ctx := c.Request.Context() + page, ok, err := s.agentServes(ctx, agentOf(c), &name, nil) + if err != nil { + internalError(c, err) + return + } + if !ok { + fail(c, http.StatusNotFound, "not_found") + return + } + lim := s.cfg.Certificates + if !s.limit(c, "acme:name:"+name, lim.PerNamePerDay, 24*time.Hour) || + !s.limit(c, "acme:org:"+page.OrgID.String(), lim.PerOrgPerDay, 24*time.Hour) || + !s.limit(c, "acme:owner:"+storageOwner(c), lim.PerOwnerPerHour, time.Hour) { + s.log.WarnContext(ctx, "certificate order refused by limit", "domain", name, "org", page.OrgID, "agent", agentOf(c).ID) + return + } + s.log.InfoContext(ctx, "certificate order allowed", "domain", name, "org", page.OrgID, "agent", agentOf(c).ID) + c.Status(http.StatusNoContent) +} diff --git a/internal/api/certificates_test.go b/internal/api/certificates_test.go new file mode 100644 index 0000000..afa9ff5 --- /dev/null +++ b/internal/api/certificates_test.go @@ -0,0 +1,108 @@ +package api_test + +import ( + "context" + "errors" + "net/http" + "strings" + "testing" + + "github.com/google/uuid" + + "git.zb-server.de/ZB-Server/uptimesebi/internal/agentapi" + "git.zb-server.de/ZB-Server/uptimesebi/internal/config" +) + +func TestCertificateOrdersAreLimited(t *testing.T) { + e := newEnvWith(t, func(c *config.API) { + c.StatusPageURL = "https://status.platform.test" + c.Certificates = config.Certificates{PerOrgPerDay: 3, PerOwnerPerHour: 100, PerNamePerDay: 2} + }) + ctx := context.Background() + owner := e.browser(t) + owner.signup("o@"+uniq("cert")+".test", uniq("cert-")) + platform := e.statuspageClient(t, nil) + + page := func(domain string) (string, map[string]any) { + t.Helper() + slug := uniq("cert-") + _, p := owner.do("POST", "/api/v1/org/statuspages", map[string]any{"slug": slug, "title": "Status"}) + id := p["id"].(string) + owner.do("PUT", "/api/v1/org/statuspages/"+id, map[string]any{"slug": slug, "title": "Status", "published": true}) + st, body := owner.do("PUT", "/api/v1/org/statuspages/"+id+"/domain", map[string]any{"domain": domain}) + if st != http.StatusOK { + t.Fatalf("set domain = %d %v", st, body) + } + return id, body["domain_record"].(map[string]any) + } + + // An unverified domain gets no certificate, nor does a made-up name. + d1 := uniq("a") + ".example.test" + id1, rec1 := page(d1) + if err := platform.AllowCertificate(ctx, d1); !errors.Is(err, agentapi.ErrNotFound) { + t.Errorf("unverified domain: %v, want not found", err) + } + if err := platform.AllowCertificate(ctx, uniq("random")+".example.test"); !errors.Is(err, agentapi.ErrNotFound) { + t.Errorf("unknown name: %v, want not found", err) + } + + // The editor explains the records, with the platform's servers as the + // CNAME target. + _, _, html := owner.page("/statuspages/" + id1) + for _, want := range []string{"Create this CNAME record", ".status.platform.test.", "Prove the domain with this TXT record", "ALIAS or ANAME", "at most 10 times a day"} { + if !strings.Contains(html, want) { + t.Errorf("the editor lacks %q", want) + } + } + + verifyDomain(t, owner, id1, rec1) + if err := platform.AllowCertificate(ctx, strings.ToUpper(d1)+"."); err != nil { + t.Fatalf("verified domain: %v", err) + } + // A domain whose orders keep failing stops at its own limit. + _ = platform.AllowCertificate(ctx, d1) + if err := platform.AllowCertificate(ctx, d1); !errors.Is(err, agentapi.ErrRateLimited) { + t.Errorf("third order for one domain: %v, want rate limited", err) + } + + // The organization's limit covers all its domains. + d2 := uniq("b") + ".example.test" + id2, rec2 := page(d2) + verifyDomain(t, owner, id2, rec2) + if err := platform.AllowCertificate(ctx, d2); err != nil { + t.Fatalf("second domain: %v", err) + } + if err := platform.AllowCertificate(ctx, d2); !errors.Is(err, agentapi.ErrRateLimited) { + t.Errorf("order beyond the organization's limit: %v, want rate limited", err) + } + + // Another organization's server is not allowed the domain at all. + other := e.browser(t) + other.signup("x@"+uniq("cert")+".test", uniq("cert-")) + otherOrg := uuid.MustParse(other.orgID()) + if err := e.statuspageClient(t, &otherOrg).AllowCertificate(ctx, d2); !errors.Is(err, agentapi.ErrNotFound) { + t.Errorf("another organization's server: %v, want not found", err) + } +} + +func TestDomainChangesAreLimited(t *testing.T) { + e := newEnv(t) + owner := e.browser(t) + owner.signup("o@"+uniq("dom")+".test", uniq("dom-")) + _, p := owner.do("POST", "/api/v1/org/statuspages", map[string]any{"slug": uniq("dom-"), "title": "Status"}) + id := p["id"].(string) + base := uniq("d") + for i := range 10 { + st, body := owner.do("PUT", "/api/v1/org/statuspages/"+id+"/domain", map[string]any{"domain": base + string(rune('a'+i)) + ".example.test"}) + if st != http.StatusOK { + t.Fatalf("change %d = %d %v", i+1, st, body) + } + // Saving the same domain again does not count. + owner.do("PUT", "/api/v1/org/statuspages/"+id+"/domain", map[string]any{"domain": base + string(rune('a'+i)) + ".example.test"}) + } + st, body := owner.do("PUT", "/api/v1/org/statuspages/"+id+"/domain", map[string]any{"domain": base + "z.example.test"}) + expect(t, "eleventh change", st, body, http.StatusTooManyRequests, "domain_changes_exceeded") + // Removing the domain is always possible. + st, body = owner.do("PUT", "/api/v1/org/statuspages/"+id+"/domain", map[string]any{"domain": ""}) + expect(t, "remove domain", st, body, http.StatusOK, "") +} diff --git a/internal/api/console.go b/internal/api/console.go index 6e245ba..aefd208 100644 --- a/internal/api/console.go +++ b/internal/api/console.go @@ -6,6 +6,7 @@ import ( "encoding/json" "errors" "fmt" + "net" "net/http" "net/url" "slices" @@ -1044,6 +1045,20 @@ func (s *Server) channelsView(c *gin.Context, p *principal, page web.Page, me we return web.ChannelsPage(page, me, v), nil } +// cnameTarget is the host custom domains point at to reach the platform's +// status page servers, unless that is not known. +func (s *Server) cnameTarget() string { + u, err := url.Parse(s.cfg.StatusPageURL) + if err != nil { + return "" + } + h := u.Hostname() + if h == "" || h == "localhost" || net.ParseIP(h) != nil || !strings.Contains(h, ".") { + return "" + } + return h +} + // pageURL is where p is reachable, or empty when only the organization's // own status page servers serve it, at an address the platform does not // know. @@ -1127,7 +1142,7 @@ func (s *Server) statusPageEditor(c *gin.Context, p *principal, page web.Page, m if err != nil { return nil, err } - v := viewStatusPage(row) + v := s.viewStatusPage(row) e := web.PageEditor{ ID: row.ID.String(), Title: row.Title, Slug: row.Slug, Description: row.Description, Published: row.Published, ShowDetails: row.ShowComponentDetails, @@ -1139,6 +1154,15 @@ func (s *Server) statusPageEditor(c *gin.Context, p *principal, page web.Page, m if v.DomainRecord != nil { e.RecordName, e.RecordValue = v.DomainRecord.Name, v.DomainRecord.Value } + e.DomainChangesPerDay = domainChangesPerDay + if v.CNAMERecord != nil { + e.CNAMEValue = v.CNAMERecord.Value + } + e.VerifiedBy = deref(row.DomainVerifyMethod) + if f := row.DomainFailingSince; f != nil { + e.MissingSince = f.Local().Format("2006-01-02 15:04") + e.SwitchOffAt = f.Add(domainGrace).Local().Format("2006-01-02 15:04") + } newPageGroupTree(pageGroups).walk(func(g store.StatusPageGroup, depth int) { var parentID string if g.ParentID != nil { diff --git a/internal/api/domains.go b/internal/api/domains.go new file mode 100644 index 0000000..47f213d --- /dev/null +++ b/internal/api/domains.go @@ -0,0 +1,176 @@ +package api + +import ( + "context" + "crypto/sha256" + "encoding/base32" + "net" + "slices" + "strings" + "time" + + "github.com/google/uuid" + + "git.zb-server.de/ZB-Server/uptimesebi/internal/notify" + "git.zb-server.de/ZB-Server/uptimesebi/internal/store" + "git.zb-server.de/ZB-Server/uptimesebi/internal/tenant" +) + +// A custom domain proves it belongs to its page in one of two ways: +// +// - a CNAME to