Files
uptimesebi/internal/api/statuspages_test.go
T
Sebastian UnterschützandClaude Opus 5.5 4d1db0943e feat(statuspage): obtain tls certificates on demand for custom domains
With UPTIME_STATUSPAGE_TLS the server serves HTTPS with ACME
certificates for its hosts and for verified custom domains of pages it
may serve, shared by all instances through the API. Plain HTTP answers
ACME challenges and health checks and redirects everything else.

Closes #22

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
2026-11-22 08:54:08 +01:00

212 lines
9.0 KiB
Go

package api_test
import (
"context"
"encoding/json"
"errors"
"io"
"log/slog"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"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/api"
"git.zb-server.de/ZB-Server/uptimesebi/internal/i18n"
"git.zb-server.de/ZB-Server/uptimesebi/internal/statuspage"
"git.zb-server.de/ZB-Server/uptimesebi/internal/store"
"git.zb-server.de/ZB-Server/uptimesebi/internal/tenant"
)
// statuspageClient creates a status page agent, platform-wide when org is
// nil, and returns a client for it.
func (e *env) statuspageClient(t *testing.T, org *uuid.UUID) *agentapi.Client {
t.Helper()
ctx := context.Background()
tok, params := api.NewAgentToken(org, "statuspage", "sp-"+uuid.NewString()[:6], nil)
err := tenant.New(e.dbPool).Tx(ctx, tenant.System(), func(q *store.Queries) error {
_, err := q.CreateAgent(ctx, params)
return err
})
if err != nil {
t.Fatal(err)
}
return agentapi.NewClient(e.srv.URL, tok, uuid.New(), "test").WithHTTPClient(e.srv.Client())
}
func TestStatusPages(t *testing.T) {
e := newEnv(t)
ctx, cancel := context.WithCancel(context.Background())
t.Cleanup(cancel)
go e.api.RunScheduler(ctx)
up := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {}))
defer up.Close()
down := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusInternalServerError) }))
defer down.Close()
tok, region := e.platformChecker(t, uniq("eu-"))
e.startChecker(t, tok)
owner := e.browser(t)
owner.signup("o@"+uniq("s")+".test", uniq("sp-"))
newMonitor := func(name, target string) string {
st, body := owner.do("POST", "/api/v1/org/monitors", map[string]any{
"name": name, "type": "http", "target": target, "interval_seconds": 60, "confirmations": 1, "regions": []string{region},
})
if st != http.StatusCreated {
t.Fatalf("create monitor = %d %v", st, body)
}
return body["id"].(string)
}
webID, apiID := newMonitor("web", up.URL), newMonitor("api", down.URL)
slug := uniq("acme-")
st, body := owner.do("POST", "/api/v1/org/statuspages", map[string]any{"slug": slug, "title": "Acme Status", "theme": map[string]any{"accent": "#1f6feb"}})
if st != http.StatusCreated {
t.Fatalf("create page = %d %v", st, body)
}
pageID := body["id"].(string)
st, body = owner.do("PUT", "/api/v1/org/statuspages/"+pageID+"/monitors", map[string]any{"monitors": []map[string]any{
{"monitor_id": webID, "section": "Frontend", "label": "Website"},
{"monitor_id": apiID, "section": "Backend", "label": "Public API"},
}})
expect(t, "set page monitors", st, body, http.StatusNoContent, "")
platform := e.statuspageClient(t, nil)
if _, err := platform.Page(context.Background(), "", slug); !errors.Is(err, agentapi.ErrNotFound) {
t.Errorf("Page(unpublished) error = %v, want not found", err)
}
owner.do("PUT", "/api/v1/org/statuspages/"+pageID, map[string]any{"slug": slug, "title": "Acme Status", "published": true, "theme": map[string]any{"accent": "#1f6feb"}})
waitFor(t, 10*time.Second, "incident for the failing monitor", func() bool {
_, body := owner.do("GET", "/api/v1/org/incidents", nil)
return len(body["incidents"].([]any)) == 1
})
snap, err := platform.Page(context.Background(), "", slug)
if err != nil {
t.Fatalf("Page() failed: %v", err)
}
if snap.Status != agentapi.PageOutage || len(snap.Sections) != 2 || snap.Sections[1].Components[0].Name != "Public API" {
t.Errorf("snapshot = %+v, want outage with Frontend and Backend sections", snap)
}
raw, _ := json.Marshal(snap)
for _, secret := range []string{up.URL, down.URL, "unexpected status"} {
if strings.Contains(string(raw), secret) {
t.Errorf("snapshot leaks %q", secret)
}
}
t.Run("rendered by the status page server", func(t *testing.T) {
cat, _ := i18n.Load()
srv := statuspage.New(platform, cat, slog.New(slog.DiscardHandler), []string{"status.test"})
gin.SetMode(gin.TestMode)
router := gin.New()
srv.Mount(router)
req := httptest.NewRequest(http.MethodGet, "/"+slug, nil)
req.Host = "status.test"
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
if w.Code != http.StatusOK || !strings.Contains(w.Body.String(), "Acme Status") || !strings.Contains(w.Body.String(), "--page-accent:#1f6feb") {
t.Errorf("rendered page = %d %.200s", w.Code, w.Body.String())
}
})
t.Run("other org cannot use or see it", func(t *testing.T) {
other := e.browser(t)
other.signup("x@"+uniq("x")+".test", uniq("sp-other-"))
otherOrg := uuid.MustParse(other.orgID())
if _, err := e.statuspageClient(t, &otherOrg).Page(context.Background(), "", slug); !errors.Is(err, agentapi.ErrNotFound) {
t.Errorf("other org's status page server got the page: %v", err)
}
st, body := other.do("POST", "/api/v1/org/statuspages", map[string]any{"slug": uniq("o-"), "title": "x"})
if st != http.StatusCreated {
t.Fatalf("create page = %d %v", st, body)
}
st, body = other.do("PUT", "/api/v1/org/statuspages/"+body["id"].(string)+"/monitors", map[string]any{"monitors": []map[string]any{{"monitor_id": webID}}})
expect(t, "list foreign monitor", st, body, http.StatusUnprocessableEntity, "invalid_monitor")
st, body = other.do("PUT", "/api/v1/org/statuspages/"+pageID, map[string]any{"slug": slug, "title": "hijack"})
expect(t, "edit foreign page", st, body, http.StatusNotFound, "not_found")
})
t.Run("custom domain after verification", func(t *testing.T) {
domain := uniq("status") + ".example.test"
st, body := owner.do("PUT", "/api/v1/org/statuspages/"+pageID+"/domain", map[string]any{"domain": domain})
if st != http.StatusOK {
t.Fatalf("set domain = %d %v", st, body)
}
record := body["domain_record"].(map[string]any)
if _, err := platform.Page(context.Background(), domain, ""); !errors.Is(err, agentapi.ErrNotFound) {
t.Errorf("Page(unverified domain) error = %v, want not found", err)
}
verifyDomain(t, owner, pageID, record)
if snap, err := platform.Page(context.Background(), domain, ""); err != nil || snap.Title != "Acme Status" {
t.Errorf("Page(verified domain) = %v, %v", snap.Title, err)
}
})
t.Run("export", func(t *testing.T) {
resp, err := owner.hc.Get(owner.base + "/api/v1/org/statuspages/" + pageID + "/export")
if err != nil {
t.Fatal(err)
}
defer func() { _ = resp.Body.Close() }()
html, _ := io.ReadAll(resp.Body)
if resp.StatusCode != http.StatusOK || !strings.Contains(resp.Header.Get("Content-Disposition"), slug+".html") ||
!strings.Contains(string(html), "<style>") || strings.Contains(string(html), `rel="stylesheet"`) {
t.Errorf("export = %d %q, want self-contained HTML", resp.StatusCode, resp.Header.Get("Content-Disposition"))
}
})
t.Run("console pages", func(t *testing.T) {
for path, want := range map[string]string{"/statuspages": "Acme Status", "/statuspages/" + pageID: `data-field="monitor_id"`} {
st, final, html := owner.page(path)
if st != http.StatusOK || final != path || !strings.Contains(html, want) {
t.Errorf("GET %s = %d at %s, contains %q: %t", path, st, final, want, strings.Contains(html, want))
}
}
})
t.Run("permission scoped to one page", func(t *testing.T) {
st, body := owner.do("POST", "/api/v1/org/statuspages", map[string]any{"slug": uniq("second-"), "title": "Second"})
if st != http.StatusCreated {
t.Fatalf("create page = %d %v", st, body)
}
second := body["id"].(string)
owner.do("POST", "/api/v1/org/roles", map[string]any{"name": "Page editor", "permissions": []string{"statuspages.write"}})
editor := e.joinVia(t, owner.invite("pe@"+uniq("pe")+".test", owner.roleID("viewer")))
st, body = owner.do("POST", "/api/v1/org/members/"+owner.userID(editorEmail(editor))+"/roles", map[string]any{
"role_id": owner.roleID("Page editor"), "resource_type": "status_page", "resource_id": pageID,
})
expect(t, "assign scoped role", st, body, http.StatusCreated, "")
st, body = editor.do("PUT", "/api/v1/org/statuspages/"+pageID, map[string]any{"slug": slug, "title": "Acme Status", "published": true})
expect(t, "edit page in scope", st, body, http.StatusOK, "")
st, body = editor.do("PUT", "/api/v1/org/statuspages/"+second, map[string]any{"slug": "x-second", "title": "x"})
expect(t, "edit page out of scope", st, body, http.StatusNotFound, "not_found")
})
}
func editorEmail(b *browser) string {
_, me := b.do("GET", "/api/v1/me", nil)
return me["email"].(string)
}
// verifyDomain answers the TXT lookup with record and verifies the domain.
func verifyDomain(t *testing.T, owner *browser, pageID string, record map[string]any) {
t.Helper()
saved := *api.LookupTXT
t.Cleanup(func() { *api.LookupTXT = saved })
*api.LookupTXT = func(_ context.Context, name string) ([]string, error) {
if name == record["name"] {
return []string{"something else", record["value"].(string)}, nil
}
return nil, errors.New("no such record")
}
st, body := owner.do("POST", "/api/v1/org/statuspages/"+pageID+"/domain/verify", nil)
expect(t, "verify domain", st, body, http.StatusNoContent, "")
}