Compare commits

..
12 Commits
Author SHA1 Message Date
Sebi ebfada4b2c Merge pull request 'feat: custom domains by a unique CNAME, limited certificate orders' (#156) from feat/custom-domain-abuse into main
release / release (push) In progress
ci / test (push) Successful in 15m27s
ci / lint (push) Successful in 10m33s
ci / image (push) Waiting for needed jobs
ci / build (push) In progress
2026-11-25 22:02:50 +00:00
Sebastian UnterschützandClaude Opus 5.5 5934bd74e8 feat: verify custom domains by a CNAME unique to the page
ci / image (pull_request) In progress
ci / test (push) Skipped
ci / test (pull_request) Successful in 12m52s
ci / lint (push) Skipped
ci / lint (pull_request) Successful in 7m28s
ci / build (push) Skipped
ci / image (push) Skipped
ci / build (pull_request) Successful in 11m21s
A custom domain now needs a single record: a CNAME to
<label>.<status page host>, where the label is derived from the page's
domain token. The wildcard record of the status page host routes it, and
since the target belongs to one page alone it also proves who set it up;
a CNAME to the shared host would not, as any organization could then
claim a domain pointing at the platform. The TXT record stays for domains
whose CNAME cannot be seen, behind a proxy or without a subdomain.

- The domain watch looks for the records of a new domain every minute for
  a quarter of an hour, then every ten minutes for two days, and verifies
  it on its own; "Check now" still works.
- Verified domains are checked daily. When the record is gone the owners
  are told, and a week later the domain is switched off, so a record left
  behind cannot be taken over. Domains verified before keep working
  without checks.
- The editor shows the CNAME record first, the TXT way for proxies and
  apex domains, how the domain was verified and when a missing record will
  switch it off. The API returns cname_record and domain_missing_since.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
2026-11-25 22:58:54 +01:00
Sebastian UnterschützandClaude Opus 5.5 66537f4e65 fix: keep Redis timeouts below a second exact
A checker's long poll ends with BLPOP waiting the rest of it, often below
a second, which go-redis rounded up to one second with a warning in the
log; the poll then ran up to a second too long. Such waits now pass BLPOP
a fraction of a second, which Redis takes since 6.0. A session's sliding
expiry, which can be below a second near its absolute end, uses PEXPIRE.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
2026-11-25 22:58:54 +01:00
Sebastian UnterschützandClaude Opus 5.5 db36d918fe feat: guard certificate orders for custom domains and explain the setup
ci / lint (push) Skipped
ci / test (push) Skipped
ci / build (push) Skipped
ci / image (push) Skipped
ci / test (pull_request) Successful in 8m21s
ci / lint (pull_request) Successful in 11m0s
ci / build (pull_request) Canceled after 8m49s
ci / image (pull_request) Canceled after 0s
Status page servers order certificates on demand. Verified domains were
already the only ones they would order for, but nothing bounded how many:
an organization switching domains, or many organizations at once, could use
up the CA's rate limits that all servers sharing an ACME account depend on,
and every handshake or request for a made-up name was passed on to the API.

- Before a new order (not a renewal) the server asks the API
  (POST /agent/v1/certificates). It allows verified domains of pages that
  server serves, within limits per domain and day, per organization and
  day, and per ACME account owner and hour (UPTIME_CERTS_*), counted
  across all instances.
- An organization can set a new custom domain at most 10 times a day.
- The server remembers names without a page for a minute and passes at
  most 20 unknown names a second on to the API; pages the sync cached are
  not affected. Only real pages are recorded as visited.
- The page editor explains the three steps: the TXT record, the CNAME
  record with the platform's status page host as its target (or the
  organization's own servers), apex domains, and when HTTPS follows.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
2026-11-25 22:39:01 +01:00
Sebi 7509b8c429 Merge pull request 'fix(release): publish the Helm chart only once the images exist' (#155) from fix/release-wait-for-images into main
ci / test (push) Successful in 15m18s
ci / lint (push) Successful in 6m41s
ci / build (push) Successful in 19m56s
ci / image (push) Successful in 5m40s
2026-11-25 19:08:31 +00:00
Sebastian UnterschützandClaude Opus 5.5 8cc5c0266a fix(release): publish the Helm chart only once the images exist
ci / test (pull_request) Successful in 9m11s
ci / lint (push) Skipped
ci / test (push) Skipped
ci / build (push) Skipped
ci / image (push) Skipped
ci / build (pull_request) Canceled after 0s
ci / lint (pull_request) Successful in 12m40s
ci / image (pull_request) Canceled after 0s
The release job finished about 20 minutes before the ci workflow had
pushed the tag's images. Clusters following the chart repository then
rolled out a release whose image did not exist yet: the migrate hook
sat in ImagePullBackOff until its deadline and the upgrade failed
(0.2.1, 0.3.0 and 0.4.0 on app.uptimesebi.net).

Wait up to 90 minutes for the API, checker and status page images of
the tag before publishing the chart.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 19:59:29 +01:00
Sebi 87ab065e24 Merge pull request 'feat(helm): redirect plain HTTP to HTTPS on the ingresses' (#154) from feat/helm-https-redirect into main
ci / test (push) Successful in 16m57s
release / release (push) Successful in 16m55s
ci / lint (push) Successful in 8m9s
ci / build (push) Successful in 16m27s
ci / image (push) Successful in 5m2s
2026-11-25 18:52:46 +00:00
Sebastian UnterschützandClaude Opus 5.5 25829671a5 feat(helm): redirect plain HTTP to HTTPS on the ingresses
ci / lint (push) Skipped
ci / test (push) Skipped
ci / build (push) Skipped
ci / image (push) Skipped
ci / test (pull_request) Successful in 12m11s
ci / lint (pull_request) Successful in 11m42s
ci / build (pull_request) Successful in 16m4s
ci / image (pull_request) Successful in 3m19s
With TLS on, the console's and the status pages' ingresses now send HTTP to
HTTPS: through a redirectScheme middleware the chart creates for Traefik,
which is chained before any middlewares already annotated, and by
annotation for ingress-nginx and HAProxy. ingress.tls.redirect and
statuspage.ingress.tls.redirect turn it off.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
2026-11-25 19:43:37 +01:00
Sebi 673e93f4bb Merge pull request 'fix(evaluate): a region without results no longer keeps a monitor up' (#153) from fix/silent-region-no-block into main
release / release (push) Successful in 16m37s
ci / image (push) Successful in 3m36s
ci / test (push) Successful in 14m47s
ci / build (push) Successful in 16m50s
ci / lint (push) Successful in 10m4s
2026-11-24 22:43:33 +00:00
Sebastian UnterschützandClaude Opus 5.5 2054660625 fix(evaluate): a region without results no longer keeps a monitor up
ci / image (pull_request) Successful in 3m16s
ci / test (pull_request) Successful in 9m3s
ci / lint (pull_request) Successful in 10m9s
ci / build (pull_request) Successful in 9m54s
ci / lint (push) Skipped
ci / build (push) Skipped
ci / test (push) Skipped
ci / image (push) Skipped
A monitor went down only when every assigned region had failed and
reported recently, so one region whose checkers were gone kept a monitor
up for good, even while all other regions reported its target failing.
Regions without recent results are now left out: a monitor goes down
when every region that reported recently has failed. One region failing
while another succeeds still does not alert, and with every region
silent nothing is judged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
2026-11-24 23:43:02 +01:00
Sebi 4d03a86614 Merge pull request 'feat: show unchecked monitors and tell about regions without checkers' (#152) from feat/unchecked-monitors into main
ci / lint (push) Canceled after 6m57s
ci / test (push) Canceled after 6m57s
ci / build (push) Canceled after 0s
ci / image (push) Canceled after 0s
2026-11-24 22:36:18 +00:00
Sebastian UnterschützandClaude Opus 5.5 dc2e21f964 feat: show unchecked monitors and tell about regions without checkers
ci / build (pull_request) Successful in 19m34s
ci / image (pull_request) Successful in 3m15s
ci / test (push) Skipped
ci / build (push) Skipped
ci / image (push) Skipped
ci / lint (push) Skipped
ci / lint (pull_request) Successful in 6m17s
ci / test (pull_request) Successful in 12m7s
A region whose checkers had all gone left its monitors looking up: the
console and status pages took the last result, however old, and nobody
was told.

- A region's last result counts only while it is younger than the
  evaluator's staleness (3 intervals, at least 2 minutes); older ones
  show as "no data since …" in the console and leave status page
  components unknown instead of operational.
- A monitor no region has reported for recently is marked "not being
  checked", counted on the dashboard with an explanation, and noted on
  its page.
- A region watch on every API replica emails the platform's admins
  (platform regions) or the organization's owners (own regions) once a
  region with checkers and enabled monitors has had no live checker for
  UPTIME_REGION_ALERT_AFTER (default 5m), and again when one is back.
  The dashboard names such regions at once.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
2026-11-24 23:35:43 +01:00
44 changed files with 5132 additions and 2920 deletions

No files matched your search

+14
View File
@@ -44,6 +44,20 @@ UPTIME_TEST_REDIS_URL=redis://localhost:6379/15
# Reverse proxies allowed to set X-Forwarded-For (comma-separated IPs/CIDRs).
# UPTIME_TRUSTED_PROXIES=10.0.0.0/8
# How long a region with monitors may have no live checker before the
# platform's admins (platform regions) or the organization's owners (own
# 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.
+35
View File
@@ -83,6 +83,41 @@ jobs:
curl -fsS -o /dev/null -X POST -H "Authorization: token $TOKEN" \
-F "attachment=@$f" "$api/releases/$id/assets?name=$(basename "$f")"
done
# The ci workflow builds the images of this tag after lint and tests,
# which takes longer than this job. A chart published before them makes
# clusters that follow the chart repository roll out a release whose
# images do not exist yet (ImagePullBackOff in the migrate hook).
- name: Wait for the images
env:
PACKAGE_TOKEN: ${{ secrets.PACKAGE_TOKEN }}
run: |
set -eu
if [ -z "$PACKAGE_TOKEN" ]; then
echo "::warning::PACKAGE_TOKEN is not set; not waiting for the images."
exit 0
fi
host="${GITHUB_SERVER_URL#*://}"
owner="$(printf '%s' "${GITHUB_REPOSITORY%/*}" | tr 'A-Z' 'a-z')"
tag="${GITHUB_REF_NAME#v}"
accept="application/vnd.oci.image.index.v1+json,application/vnd.oci.image.manifest.v1+json,application/vnd.docker.distribution.manifest.list.v2+json,application/vnd.docker.distribution.manifest.v2+json"
deadline=$(( $(date +%s) + 90 * 60 ))
for repo in uptimesebi uptimesebi-checker uptimesebi-statuspage; do
until
token="$(curl -fsS --user "$GITHUB_ACTOR:$PACKAGE_TOKEN" \
"$GITHUB_SERVER_URL/v2/token?service=container_registry&scope=repository:$owner/$repo:pull" \
| sed -n 's/.*"token":"\([^"]*\)".*/\1/p')"
curl -fsS -o /dev/null -I -H "Authorization: Bearer $token" -H "Accept: $accept" \
"$GITHUB_SERVER_URL/v2/$owner/$repo/manifests/$tag"
do
if [ "$(date +%s)" -ge "$deadline" ]; then
echo "::error::$host/$owner/$repo:$tag did not appear within 90 minutes; the chart is not published."
exit 1
fi
echo "waiting for $host/$owner/$repo:$tag"
sleep 30
done
echo "$host/$owner/$repo:$tag is there"
done
# helm repo add uptimesebi <server>/api/packages/<owner>/helm
- name: Publish Helm chart
env:
+1 -1
View File
@@ -4,7 +4,7 @@
[![ci](https://git.zb-server.de/ZB-Server/uptimesebi/actions/workflows/ci.yaml/badge.svg?branch=main)](https://git.zb-server.de/ZB-Server/uptimesebi/actions?workflow=ci.yaml) · License: AGPL-3.0-only
UptimeSebi monitors websites, APIs and services from several regions and tells you when they are down, without false alarms from a single checker losing its network: a monitor only counts as down when **every** region it is checked from fails. It publishes status pages that stay online even while UptimeSebi itself is not, and it can run entirely on your own infrastructure.
UptimeSebi monitors websites, APIs and services from several regions and tells you when they are down, without false alarms from a single checker losing its network: a monitor only counts as down when **every** region it is checked from fails. A region whose checkers are gone is left out rather than holding the monitor up, and its admins are told. It publishes status pages that stay online even while UptimeSebi itself is not, and it can run entirely on your own infrastructure.
It is built for teams and hosting providers: organizations with members, roles and SSO, run either as a shared cloud service or self-hosted.
+2
View File
@@ -92,6 +92,8 @@ func run(log *slog.Logger, level *slog.LevelVar, args []string) error {
go srv.RunScheduler(ctx)
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)
+1
View File
@@ -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})
@@ -170,3 +170,53 @@ $secret being the chart secret to read values from.
medium: Memory
sizeLimit: 64Mi
{{- end -}}
{{/*
HTTPS redirect of an ingress: include with (dict "root" . "ingress" <values>
"name" <ingress name>). Traefik needs a redirectScheme middleware, other
controllers an annotation. */}}
{{- define "uptimesebi.redirects" -}}
{{- $i := .ingress -}}
{{- if and $i.tls.enabled $i.tls.redirect }}true{{ end -}}
{{- end -}}
{{- define "uptimesebi.traefik" -}}
{{- $i := .ingress -}}
{{- if contains "traefik" ($i.className | default "") -}}true
{{- else if and (not $i.className) (.root.Capabilities.APIVersions.Has "traefik.io/v1alpha1/Middleware") -}}true
{{- end -}}
{{- end -}}
{{/* the ingress's annotations, with those the redirect needs. */}}
{{- define "uptimesebi.ingressAnnotations" -}}
{{- $a := deepCopy (.ingress.annotations | default dict) -}}
{{- if include "uptimesebi.redirects" . -}}
{{- if include "uptimesebi.traefik" . -}}
{{- $key := "traefik.ingress.kubernetes.io/router.middlewares" -}}
{{- $mw := printf "%s-%s-https@kubernetescrd" .root.Release.Namespace .name -}}
{{- with get $a $key }}{{ $mw = printf "%s,%s" $mw . }}{{ end -}}
{{- $_ := set $a $key $mw -}}
{{- else -}}
{{- $_ := set $a "nginx.ingress.kubernetes.io/ssl-redirect" "true" -}}
{{- $_ := set $a "haproxy.org/ssl-redirect" "true" -}}
{{- end -}}
{{- end -}}
{{- with $a }}{{ toYaml . }}{{ end -}}
{{- end -}}
{{/* the Traefik middleware the redirect uses, if it needs one. */}}
{{- define "uptimesebi.redirectMiddleware" -}}
{{- if and (include "uptimesebi.redirects" .) (include "uptimesebi.traefik" .) }}
---
apiVersion: traefik.io/v1alpha1
kind: Middleware
metadata:
name: {{ .name }}-https
labels:
{{- include "uptimesebi.labels" .root | nindent 4 }}
spec:
redirectScheme:
scheme: https
permanent: true
{{- end }}
{{- end -}}
@@ -1,13 +1,14 @@
{{- if .Values.ingress.enabled }}
{{- $ing := dict "root" . "ingress" .Values.ingress "name" (include "uptimesebi.fullname" .) }}
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: {{ include "uptimesebi.fullname" . }}
labels:
{{- include "uptimesebi.labels" . | nindent 4 }}
{{- with .Values.ingress.annotations }}
{{- with include "uptimesebi.ingressAnnotations" $ing }}
annotations:
{{- toYaml . | nindent 4 }}
{{- . | nindent 4 }}
{{- end }}
spec:
{{- with .Values.ingress.className }}
@@ -29,4 +30,5 @@ spec:
name: {{ include "uptimesebi.fullname" . }}-api
port:
name: http
{{- include "uptimesebi.redirectMiddleware" $ing }}
{{- end }}
@@ -118,6 +118,7 @@ spec:
{{- include "uptimesebi.selector" (list . "statuspage") | nindent 6 }}
{{- end }}
{{- if .Values.statuspage.ingress.enabled }}
{{- $ing := dict "root" . "ingress" .Values.statuspage.ingress "name" $name }}
---
apiVersion: networking.k8s.io/v1
kind: Ingress
@@ -125,9 +126,9 @@ metadata:
name: {{ $name }}
labels:
{{- include "uptimesebi.labels" . | nindent 4 }}
{{- with .Values.statuspage.ingress.annotations }}
{{- with include "uptimesebi.ingressAnnotations" $ing }}
annotations:
{{- toYaml . | nindent 4 }}
{{- . | nindent 4 }}
{{- end }}
spec:
{{- with .Values.statuspage.ingress.className }}
@@ -152,5 +153,6 @@ spec:
port:
name: http
{{- end }}
{{- include "uptimesebi.redirectMiddleware" $ing }}
{{- end }}
{{- end }}
+5
View File
@@ -144,6 +144,9 @@ ingress:
enabled: false
# Secret with the certificate, e.g. made by cert-manager.
secretName: ""
# Send plain HTTP to HTTPS: through a redirectScheme middleware with
# Traefik, by annotation with ingress-nginx and HAProxy.
redirect: true
# -- Checker --
# A checker in the cluster, for checks from the cluster's region. Create
@@ -197,6 +200,8 @@ statuspage:
tls:
enabled: false
secretName: ""
# Send plain HTTP to HTTPS, as for the console.
redirect: true
resources:
requests:
cpu: 50m
+2
View File
@@ -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))
+10
View File
@@ -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)
}
+1
View File
@@ -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)
+47
View File
@@ -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)
}
+108
View File
@@ -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, "")
}
+54 -2
View File
@@ -6,6 +6,7 @@ import (
"encoding/json"
"errors"
"fmt"
"net"
"net/http"
"net/url"
"slices"
@@ -21,6 +22,7 @@ import (
"git.zb-server.de/ZB-Server/uptimesebi/internal/auth"
"git.zb-server.de/ZB-Server/uptimesebi/internal/authz"
"git.zb-server.de/ZB-Server/uptimesebi/internal/check"
"git.zb-server.de/ZB-Server/uptimesebi/internal/evaluate"
"git.zb-server.de/ZB-Server/uptimesebi/internal/i18n"
"git.zb-server.de/ZB-Server/uptimesebi/internal/maintenance"
"git.zb-server.de/ZB-Server/uptimesebi/internal/notify"
@@ -91,7 +93,14 @@ func (s *Server) dashboard(c *gin.Context) {
v.Ranges = rangeOptions(c, data.rng, earliest, data.now)
for _, m := range data.rows {
v.Counts[m.Status]++
if m.Unchecked {
v.Unchecked++
}
}
for id, since := range s.regionsWithoutChecker(c.Request.Context(), data.usedRegions) {
v.DeadRegions = append(v.DeadRegions, web.DeadRegion{Name: data.regionOf[id].Name, Since: since.Local().Format("2006-01-02 15:04")})
}
slices.SortFunc(v.DeadRegions, func(a, b web.DeadRegion) int { return strings.Compare(a.Name, b.Name) })
}
web.Render(c, http.StatusOK, web.Dashboard(s.pageFor(c, "console.monitors.title"), me, v))
}
@@ -214,6 +223,8 @@ type monitorData struct {
firstRegion map[uuid.UUID]map[string]time.Time
// statuses are the organization's own incident statuses.
statuses customStatuses
// usedRegions are the regions the enabled monitors are checked from.
usedRegions []uuid.UUID
}
// loadFirstData finds when monitors and their regions first reported. The
@@ -366,6 +377,13 @@ func (s *Server) loadMonitorData(ctx context.Context, p *principal, rng web.Time
for _, a := range assigned {
regionsOf[a.MonitorID] = append(regionsOf[a.MonitorID], a.RegionID)
}
for _, m := range monitors {
if m.Enabled {
d.usedRegions = append(d.usedRegions, regionsOf[m.ID]...)
}
}
slices.SortFunc(d.usedRegions, func(a, b uuid.UUID) int { return strings.Compare(a.String(), b.String()) })
d.usedRegions = slices.Compact(d.usedRegions)
latestOf := map[uuid.UUID]map[string]store.LatestResultsRow{}
for _, l := range latest {
if latestOf[l.MonitorID] == nil {
@@ -393,9 +411,18 @@ func (s *Server) loadMonitorData(ctx context.Context, p *principal, rng web.Time
}
var latencies []int32
failing, reported := 0, 0
// A region that has not reported for longer than the evaluator
// waits is unknown, whatever its last result said; passive monitors
// judge their own lateness.
staleBefore := now.Add(-evaluate.StaleAfter(time.Duration(m.IntervalSeconds) * time.Second))
for _, key := range keys {
rs := web.RegionStatus{Name: d.regionNameString(key), Status: web.StatusUnknown, Detail: "–"}
if l, ok := latestOf[m.ID][key]; ok {
l, ok := latestOf[m.ID][key]
if ok && !check.Passive(check.Type(m.Type)) && l.Time.Before(staleBefore) {
rs.Detail = i18n.T(ctx, "monitors.no_data_since", "Time", l.Time.Format("15:04"))
ok = false
}
if ok {
reported++
rs.Detail = l.Time.Format("15:04:05")
if l.Ok {
@@ -421,6 +448,8 @@ func (s *Server) loadMonitorData(ctx context.Context, p *principal, rng web.Time
row.Status = web.StatusDown
case reported == 0:
row.Status = web.StatusUnknown
// Nobody is checking it, unless it is too new to have results.
row.Unchecked = !check.Passive(check.Type(m.Type)) && m.CreatedAt.Before(staleBefore)
case failing > 0:
row.Status = web.StatusDegraded
default:
@@ -1016,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.
@@ -1099,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,
@@ -1111,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 {
+176
View File
@@ -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 <label>.<status page host>, where the label is unique to
// the page. The platform's status page host has a wildcard record, so
// the CNAME also routes the domain; one record does both. A CNAME to
// the shared host alone would not do: it proves the domain points at
// the platform, not which organization put it there.
// - the TXT record _uptimesebi.<domain>, for domains whose CNAME cannot be
// seen: behind a proxy such as Cloudflare's, or a domain without a
// subdomain using ALIAS or CNAME flattening.
//
// The domain watch looks for them on its own after a domain is set, and
// checks verified domains daily. One whose record has been missing for
// domainGrace is switched off, so a record left behind after a page is
// gone or moved cannot be claimed by anybody else.
const (
domainWatchEvery = time.Minute
domainGrace = 7 * 24 * time.Hour
keyDomainWatch = "domainwatch:lock"
)
// lookupCNAME is replaced in tests.
var lookupCNAME = net.DefaultResolver.LookupCNAME
var labelEncoding = base32.NewEncoding("abcdefghijklmnopqrstuvwxyz234567").WithPadding(base32.NoPadding)
// cnameLabel is the page's label below the status page host, derived from
// its domain token.
func cnameLabel(token string) string {
sum := sha256.Sum256([]byte("cname\x00" + token))
return "p" + labelEncoding.EncodeToString(sum[:10])
}
// cnameFor is the CNAME target of the page with token, or empty when the
// platform's status page host is not known.
func (s *Server) cnameFor(token string) string {
host := s.cnameTarget()
if host == "" {
return ""
}
return cnameLabel(token) + "." + host
}
// checkDomain looks for the records proving domain belongs to the page
// with token and returns "cname", "txt" or "" for neither.
func (s *Server) checkDomain(ctx context.Context, domain, token string) string {
if target := s.cnameFor(token); target != "" {
if c, err := lookupCNAME(ctx, domain); err == nil && strings.EqualFold(strings.TrimSuffix(c, "."), target) {
return "cname"
}
}
if records, err := lookupTXT(ctx, verifyPrefix+domain); err == nil && slices.Contains(records, token) {
return "txt"
}
return ""
}
// RunDomainWatch checks custom domains until ctx ends. Replicas take
// turns through a lock in Redis.
func (s *Server) RunDomainWatch(ctx context.Context) {
tick := time.NewTicker(domainWatchEvery)
defer tick.Stop()
for {
if ok, err := s.rdb.SetNX(ctx, keyDomainWatch, 1, domainWatchEvery-5*time.Second).Result(); err == nil && ok {
if err := s.WatchDomains(ctx, time.Now()); err != nil && ctx.Err() == nil {
s.log.WarnContext(ctx, "checking custom domains failed", "error", err)
}
}
select {
case <-ctx.Done():
return
case <-tick.C:
}
}
}
// WatchDomains checks the domains that are due once.
func (s *Server) WatchDomains(ctx context.Context, now time.Time) error {
return s.watchDomains(ctx, now, nil)
}
// watchDomains is WatchDomains limited to the page only, unless it is nil.
func (s *Server) watchDomains(ctx context.Context, now time.Time, only *uuid.UUID) error {
var due []store.DomainsToCheckRow
if err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
var err error
due, err = q.DomainsToCheck(ctx, store.DomainsToCheckParams{Now: now, PageID: only})
return err
}); err != nil {
return err
}
for _, d := range due {
if err := s.watchDomain(ctx, d, now); err != nil {
return err
}
}
return nil
}
func (s *Server) watchDomain(ctx context.Context, d store.DomainsToCheckRow, now time.Time) error {
method := s.checkDomain(ctx, d.Domain, d.DomainToken)
var (
failing *time.Time
off bool
)
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
if method != "" {
return q.MarkDomainVerified(ctx, store.MarkDomainVerifiedParams{ID: d.ID, Now: now, Method: method})
}
var err error
if failing, err = q.MarkDomainUnconfirmed(ctx, store.MarkDomainUnconfirmedParams{ID: d.ID, Now: now}); err != nil || failing == nil {
return err
}
if now.Sub(*failing) >= domainGrace {
off = true
return q.UnverifyDomain(ctx, d.ID)
}
return nil
})
if err != nil {
return err
}
switch {
case method != "" && d.DomainVerifiedAt == nil:
s.log.InfoContext(ctx, "custom domain verified", "page", d.ID, "domain", d.Domain, "method", method)
case off:
s.log.InfoContext(ctx, "custom domain switched off: its record is gone", "page", d.ID, "domain", d.Domain)
s.mailDomain(ctx, d, "email.domain_off", now)
case failing != nil && d.DomainFailingSince == nil:
s.log.InfoContext(ctx, "custom domain record missing", "page", d.ID, "domain", d.Domain)
s.mailDomain(ctx, d, "email.domain_missing", now.Add(domainGrace))
}
return nil
}
// mailDomain tells the organization's owners about d.
func (s *Server) mailDomain(ctx context.Context, d store.DomainsToCheckRow, kind string, at time.Time) {
if s.smtp == nil {
return
}
var to []string
if err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
var err error
to, err = q.OrgOwnerEmails(ctx, d.OrgID)
return err
}); err != nil || len(to) == 0 {
return
}
l := s.catalog.Match("")
data := map[string]any{
"Domain": d.Domain, "Page": d.Title, "Link": s.ticketLink("/statuspages/" + d.ID.String()),
"Date": at.UTC().Format("2006-01-02 15:04 MST"),
}
if err := s.smtp.Send(ctx, notify.Mail{To: to, Subject: l.T(kind+".subject", data), Body: l.T(kind+".body", data)}); err != nil {
s.log.WarnContext(ctx, "mail about a custom domain failed", "page", d.ID, "error", err)
}
}
+205
View File
@@ -0,0 +1,205 @@
package api_test
import (
"context"
"errors"
"net/http"
"strings"
"sync"
"testing"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"git.zb-server.de/ZB-Server/uptimesebi/internal/api"
"git.zb-server.de/ZB-Server/uptimesebi/internal/config"
"git.zb-server.de/ZB-Server/uptimesebi/internal/notify/notifytest"
)
// fakeDNS answers CNAME lookups from a map, and TXT lookups with nothing.
type fakeDNS struct {
mu sync.Mutex
cname map[string]string
}
func (d *fakeDNS) set(name, target string) {
d.mu.Lock()
defer d.mu.Unlock()
if target == "" {
delete(d.cname, name)
} else {
d.cname[name] = target
}
}
func useFakeDNS(t *testing.T) *fakeDNS {
d := &fakeDNS{cname: map[string]string{}}
savedC, savedT := *api.LookupCNAME, *api.LookupTXT
t.Cleanup(func() { *api.LookupCNAME, *api.LookupTXT = savedC, savedT })
*api.LookupCNAME = func(_ context.Context, name string) (string, error) {
d.mu.Lock()
defer d.mu.Unlock()
if c, ok := d.cname[name]; ok {
return c, nil
}
return "", errors.New("no such host")
}
*api.LookupTXT = func(context.Context, string) ([]string, error) { return nil, errors.New("no such record") }
return d
}
func TestCustomDomainByCNAME(t *testing.T) {
mail := notifytest.NewSMTP(t)
e := newEnvWith(t, func(c *config.API) {
c.SMTPURL, c.SignupVerify = mail.URL(), "off"
c.StatusPageURL = "https://status.platform.test"
})
ctx := context.Background()
dns := useFakeDNS(t)
platform := e.statuspageClient(t, nil)
newPage := func(b *browser) uuid.UUID {
slug := uniq("cn-")
_, p := b.do("POST", "/api/v1/org/statuspages", map[string]any{"slug": slug, "title": "Shop status"})
b.do("PUT", "/api/v1/org/statuspages/"+p["id"].(string), map[string]any{"slug": slug, "title": "Shop status", "published": true})
return uuid.MustParse(p["id"].(string))
}
setDomain := func(b *browser, id uuid.UUID, domain string) string {
t.Helper()
st, body := b.do("PUT", "/api/v1/org/statuspages/"+id.String()+"/domain", map[string]any{"domain": domain})
if st != http.StatusOK {
t.Fatalf("set domain = %d %v", st, body)
}
rec, _ := body["cname_record"].(map[string]any)
if rec == nil || rec["name"] != domain {
t.Fatalf("cname_record = %v", body["cname_record"])
}
return rec["value"].(string)
}
served := func(domain string) bool {
_, err := platform.Page(ctx, domain, "")
return err == nil
}
a := e.browser(t)
aEmail := "a@" + uniq("cn") + ".test"
a.signup(aEmail, uniq("cn-"))
pageA := newPage(a)
domain := uniq("status") + ".shop.test"
target := setDomain(a, pageA, domain)
if !strings.HasSuffix(target, ".status.platform.test") || len(target) < 30 {
t.Errorf("CNAME target %q is not unique to the page below the status host", target)
}
if _, _, html := a.page("/statuspages/" + pageA.String()); !strings.Contains(html, target+".") || !strings.Contains(html, "Check now") {
t.Error("the editor does not show the page's CNAME record")
}
// A CNAME to the shared host alone proves nothing.
now := time.Now()
dns.set(domain, "status.platform.test.")
if err := e.api.WatchDomainOf(ctx, now, pageA); err != nil {
t.Fatal(err)
}
if served(domain) {
t.Fatal("a CNAME to the shared host verified the domain")
}
// The page's own target verifies it, without anybody pressing a button.
dns.set(domain, strings.ToUpper(target)+".")
if err := e.api.WatchDomainOf(ctx, now.Add(time.Minute), pageA); err != nil {
t.Fatal(err)
}
if !served(domain) {
t.Fatal("the watch did not verify the domain by its CNAME")
}
if _, _, html := a.page("/statuspages/" + pageA.String()); !strings.Contains(html, "verified by its CNAME record") {
t.Error("the editor does not say how the domain was verified")
}
// Another organization taking the domain over, while the CNAME still
// points at the first page, gets nowhere.
a.do("PUT", "/api/v1/org/statuspages/"+pageA.String()+"/domain", map[string]any{"domain": ""})
b := e.browser(t)
b.signup("b@"+uniq("cn")+".test", uniq("cn-"))
pageB := newPage(b)
setDomain(b, pageB, domain)
if err := e.api.WatchDomainOf(ctx, now.Add(2*time.Minute), pageB); err != nil {
t.Fatal(err)
}
if st, _ := b.do("POST", "/api/v1/org/statuspages/"+pageB.String()+"/domain/verify", nil); st != http.StatusUnprocessableEntity || served(domain) {
t.Fatalf("a record left by another page verified the domain (verify = %d)", st)
}
b.do("PUT", "/api/v1/org/statuspages/"+pageB.String()+"/domain", map[string]any{"domain": ""})
// Once verified, the record is checked daily. Gone, the owners are told
// and, a week later, the domain is switched off.
setDomain(a, pageA, domain)
if st, body := a.do("POST", "/api/v1/org/statuspages/"+pageA.String()+"/domain/verify", nil); st != http.StatusNoContent {
t.Fatalf("verify = %d %v", st, body)
}
dns.set(domain, "")
day := now.Add(25 * time.Hour)
if err := e.api.WatchDomainOf(ctx, day, pageA); err != nil {
t.Fatal(err)
}
waitFor(t, 5*time.Second, "a mail that the record is gone", func() bool {
return mailedTo(mail, aEmail, "is gone", domain)
})
if !served(domain) {
t.Error("the domain was switched off at once")
}
if _, _, html := a.page("/statuspages/" + pageA.String()); !strings.Contains(html, "has not been found since") {
t.Error("the editor does not warn about the missing record")
}
if err := e.api.WatchDomainOf(ctx, day.Add(8*24*time.Hour), pageA); err != nil {
t.Fatal(err)
}
if served(domain) {
t.Error("the domain is still served a week after its record went")
}
waitFor(t, 5*time.Second, "a mail that the domain was switched off", func() bool {
return mailedTo(mail, aEmail, "switched off", domain)
})
}
func TestDomainsVerifiedBeforeAreNotCheckedAgain(t *testing.T) {
e := newEnvWith(t, func(c *config.API) { c.StatusPageURL = "https://status.platform.test" })
ctx := context.Background()
useFakeDNS(t)
owner := e.browser(t)
owner.signup("o@"+uniq("old")+".test", uniq("old-"))
slug := uniq("old-")
_, 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})
domain := uniq("old") + ".example.test"
owner.do("PUT", "/api/v1/org/statuspages/"+id+"/domain", map[string]any{"domain": domain})
if err := e.asSystem(t, func(tx pgx.Tx) error {
_, err := tx.Exec(ctx, `UPDATE status_pages SET domain_verified_at = now() - interval '1 year', domain_set_at = now() - interval '1 year' WHERE id = $1`, id)
return err
}); err != nil {
t.Fatal(err)
}
if err := e.api.WatchDomainOf(ctx, time.Now().Add(30*24*time.Hour), uuid.MustParse(id)); err != nil {
t.Fatal(err)
}
if _, err := e.statuspageClient(t, nil).Page(ctx, domain, ""); err != nil {
t.Errorf("a domain verified before the checks was switched off: %v", err)
}
}
func mailedTo(mail *notifytest.SMTP, to string, want ...string) bool {
for _, m := range mail.Messages() {
if !strings.Contains(strings.Join(m.To, ","), to) {
continue
}
ok := true
for _, w := range want {
ok = ok && strings.Contains(m.Data, w)
}
if ok {
return true
}
}
return false
}
+21
View File
@@ -1,5 +1,12 @@
package api
import (
"context"
"time"
"github.com/google/uuid"
)
// LookupTXT lets tests replace DNS lookups for domain verification.
var LookupTXT = &lookupTXT
@@ -17,3 +24,17 @@ func DocumentedRoutes() []string {
// OpenAPI builds the OpenAPI document.
func OpenAPI() map[string]any { return buildOpenAPI("https://uptime.example") }
// WatchRegionsOf runs the region watch for the regions given only, so
// tests are not slowed down by the regions other tests left behind.
func (s *Server) WatchRegionsOf(ctx context.Context, now time.Time, ids ...uuid.UUID) error {
return s.watchRegions(ctx, now, ids)
}
// LookupCNAME lets tests replace DNS lookups for domain verification.
var LookupCNAME = &lookupCNAME
// WatchDomainOf runs the domain watch for one page only.
func (s *Server) WatchDomainOf(ctx context.Context, now time.Time, page uuid.UUID) error {
return s.watchDomains(ctx, now, &page)
}
+164
View File
@@ -0,0 +1,164 @@
package api
import (
"context"
"errors"
"slices"
"time"
"github.com/google/uuid"
"github.com/redis/go-redis/v9"
"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 region whose checkers have all gone leaves its monitors unchecked:
// they neither go down nor alert. The region watch tells those who run the
// region, the platform's admins for platform regions and the owners for an
// organization's own, once it has had no live checker for
// UPTIME_REGION_ALERT_AFTER, and again when one is back. Every replica runs
// it; Redis decides which one sends.
const (
regionWatchEvery = 30 * time.Second
// regionWatchTTL bounds the state of a region; one dead for longer is
// announced again.
regionWatchTTL = 30 * 24 * time.Hour
)
func keyRegionDeadSince(id uuid.UUID) string { return "regionwatch:since:" + id.String() }
func keyRegionAlerted(id uuid.UUID) string { return "regionwatch:alerted:" + id.String() }
// RunRegionWatch watches the regions until ctx ends.
func (s *Server) RunRegionWatch(ctx context.Context) {
if s.cfg.RegionAlertAfter <= 0 {
return
}
tick := time.NewTicker(regionWatchEvery)
defer tick.Stop()
for {
if err := s.WatchRegions(ctx, time.Now()); err != nil && ctx.Err() == nil {
s.log.WarnContext(ctx, "watching regions failed", "error", err)
}
select {
case <-ctx.Done():
return
case <-tick.C:
}
}
}
// WatchRegions checks every region with checkers and enabled monitors once.
func (s *Server) WatchRegions(ctx context.Context, now time.Time) error {
return s.watchRegions(ctx, now, nil)
}
// watchRegions is WatchRegions limited to only, unless only is nil.
func (s *Server) watchRegions(ctx context.Context, now time.Time, only []uuid.UUID) error {
var regions []store.RegionsToWatchRow
if err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
var err error
regions, err = q.RegionsToWatch(ctx)
return err
}); err != nil {
return err
}
for _, r := range regions {
if only != nil && !slices.Contains(only, r.ID) {
continue
}
live, err := s.sched.Instances(ctx, r.ID.String())
if err != nil {
return err
}
if live > 0 {
since, _ := s.rdb.GetDel(ctx, keyRegionDeadSince(r.ID)).Time()
// Only the replica that clears the alert announces the return.
if n, err := s.rdb.Del(ctx, keyRegionAlerted(r.ID)).Result(); err == nil && n > 0 {
s.mailRegion(ctx, r, since, now, false)
}
continue
}
if err := s.rdb.SetNX(ctx, keyRegionDeadSince(r.ID), now, regionWatchTTL).Err(); err != nil {
return err
}
since, err := s.rdb.Get(ctx, keyRegionDeadSince(r.ID)).Time()
if err != nil {
return err
}
if now.Sub(since) < s.cfg.RegionAlertAfter {
continue
}
if first, err := s.rdb.SetNX(ctx, keyRegionAlerted(r.ID), 1, regionWatchTTL).Result(); err == nil && first {
if !s.mailRegion(ctx, r, since, now, true) {
// Tried again on the next round.
s.rdb.Del(ctx, keyRegionAlerted(r.ID))
}
}
}
return nil
}
// regionsWithoutChecker returns since when each of ids has had no live
// checker, for those the watch found without one.
func (s *Server) regionsWithoutChecker(ctx context.Context, ids []uuid.UUID) map[uuid.UUID]time.Time {
out := map[uuid.UUID]time.Time{}
for _, id := range ids {
since, err := s.rdb.Get(ctx, keyRegionDeadSince(id)).Time()
if err == nil {
out[id] = since
} else if !errors.Is(err, redis.Nil) {
s.log.WarnContext(ctx, "reading region watch failed", "region", id, "error", err)
}
}
return out
}
// mailRegion tells the admins or the owners that r has no live checker
// since since, or, when down is false, that it has one again. It reports
// false if the mail could not be sent and should be tried again.
func (s *Server) mailRegion(ctx context.Context, r store.RegionsToWatchRow, since, now time.Time, down bool) bool {
if s.smtp == nil {
return true
}
var to []string
link := "/admin"
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
var err error
if r.OrgID == nil {
to, err = q.AdminEmails(ctx)
} else {
link = "/settings/regions"
to, err = q.OrgOwnerEmails(ctx, *r.OrgID)
}
return err
})
if err != nil || len(to) == 0 {
if err != nil {
s.log.WarnContext(ctx, "finding whom to tell about a region failed", "region", r.ID, "error", err)
return false
}
return true
}
l := s.catalog.Match("")
data := map[string]any{
"Region": r.Name, "Org": deref(r.OrgName), "Link": s.ticketLink(link),
"Since": since.UTC().Format("2006-01-02 15:04 MST"),
"Minutes": int(now.Sub(since).Minutes()),
}
kind := "email.region_back"
if down {
kind = "email.region_down"
}
if since.IsZero() {
data["Since"], data["Minutes"] = "–", 0
}
if err := s.smtp.Send(ctx, notify.Mail{To: to, Subject: l.T(kind+".subject", data), Body: l.T(kind+".body", data)}); err != nil {
s.log.WarnContext(ctx, "mail about a region failed", "region", r.ID, "error", err)
return false
}
s.log.InfoContext(ctx, "told about a region", "region", r.ID, "down", down, "recipients", len(to))
return true
}
+130
View File
@@ -0,0 +1,130 @@
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"
"git.zb-server.de/ZB-Server/uptimesebi/internal/config"
"git.zb-server.de/ZB-Server/uptimesebi/internal/notify/notifytest"
)
func TestUncheckedMonitorsAndRegionsWithoutChecker(t *testing.T) {
mail := notifytest.NewSMTP(t)
e := newEnvWith(t, func(c *config.API) {
c.SMTPURL, c.SignupVerify, c.RegionAlertAfter = mail.URL(), "off", 3*time.Minute
})
ctx := context.Background()
owner := e.browser(t)
ownerEmail := "o@" + uniq("rw") + ".test"
owner.signup(ownerEmail, uniq("rw-"))
// An organization's own region: its owners hear about it.
regionName := uniq("Office ")
_, reg := owner.do("POST", "/api/v1/org/regions", map[string]any{"key": uniq("office-"), "name": regionName})
region := reg["id"].(string)
regionID := uuid.MustParse(region)
st, agent := owner.do("POST", "/api/v1/org/agents", map[string]any{"kind": "checker", "name": "office-1", "region_id": region})
if st != http.StatusCreated {
t.Fatalf("create agent = %d %v", st, agent)
}
tok := agent["token"].(string)
mailed := func(to, want string) {
t.Helper()
waitFor(t, 5*time.Second, "a mail saying "+want, func() bool {
for _, m := range mail.Messages() {
if strings.Contains(strings.Join(m.To, ","), to) && strings.Contains(m.Data, want) && strings.Contains(m.Data, regionName) {
return true
}
}
return false
})
}
// A monitor whose only region last reported ten minutes ago is not
// up: nobody is checking it.
_, mon := owner.do("POST", "/api/v1/org/monitors", map[string]any{"name": "Shop", "type": "http", "target": "https://example.test", "interval_seconds": 60, "regions": []string{region}})
id := mon["id"].(string)
org := uuid.MustParse(owner.orgID())
if err := e.asSystem(t, func(tx pgx.Tx) error {
if _, err := tx.Exec(ctx, `UPDATE monitors SET created_at = now() - interval '1 hour' WHERE id = $1`, id); err != nil {
return err
}
_, err := tx.Exec(ctx, `INSERT INTO check_results (time, org_id, monitor_id, region, checker_id, ok, latency_ms) VALUES (now() - interval '10 minutes', $1, $2, $3, $4, true, 10)`,
org, id, region, uuid.New())
return err
}); err != nil {
t.Fatal(err)
}
_, _, dash := owner.page("/")
for _, want := range []string{"not being checked", "1 monitor is not being checked"} {
if !strings.Contains(dash, want) {
t.Errorf("dashboard lacks %q", want)
}
}
if _, _, detail := owner.page("/monitors/" + id); !strings.Contains(detail, "no data since") || !strings.Contains(detail, "1 monitor is not being checked") {
t.Error("the monitor page does not say the region has no recent data")
}
// On a status page it shows as unknown, not as operational.
slug := uniq("rw-")
_, page := owner.do("POST", "/api/v1/org/statuspages", map[string]any{"slug": slug, "title": "Shop status"})
owner.do("PUT", "/api/v1/org/statuspages/"+page["id"].(string)+"/monitors", map[string]any{"monitors": []map[string]any{{"monitor_id": id}}})
owner.do("PUT", "/api/v1/org/statuspages/"+page["id"].(string), map[string]any{"slug": slug, "title": "Shop status", "published": true})
snap, err := e.statuspageClient(t, &org).Page(ctx, "", slug)
if err != nil || len(snap.Sections) != 1 || snap.Sections[0].Components[0].Status != agentapi.PageUnknown {
t.Errorf("status page = %+v, %v; want the component unknown", snap.Sections, err)
}
// The region has a checker but no live instance: the watch notes it at
// once and tells the owners once it has lasted.
now := time.Now()
if err := e.api.WatchRegionsOf(ctx, now, regionID); err != nil {
t.Fatal(err)
}
if _, _, dash := owner.page("/"); !strings.Contains(dash, "Region "+regionName+" has had no active checker since") {
t.Error("the dashboard does not name the region without a checker")
}
if err := e.api.WatchRegionsOf(ctx, now.Add(5*time.Minute), regionID); err != nil {
t.Fatal(err)
}
mailed(ownerEmail, "has no active checker")
sent := len(mail.Messages())
if err := e.api.WatchRegionsOf(ctx, now.Add(10*time.Minute), regionID); err != nil {
t.Fatal(err)
}
time.Sleep(200 * time.Millisecond)
if n := countMails(mail.Messages()[sent:], regionName); n != 0 {
t.Errorf("the region was announced %d more times", n)
}
// A checker coming back is announced too.
e.startChecker(t, tok)
waitFor(t, 15*time.Second, "the checker to count as live", func() bool {
_ = e.api.WatchRegionsOf(ctx, time.Now(), regionID)
for _, m := range mail.Messages() {
if strings.Contains(m.Data, "is checking again") && strings.Contains(m.Data, regionName) {
return true
}
}
return false
})
if _, _, dash := owner.page("/"); strings.Contains(dash, "Region "+regionName+" has had no active checker") {
t.Error("the dashboard still names the region")
}
}
func countMails(ms []notifytest.Message, about string) int {
n := 0
for _, m := range ms {
if strings.Contains(m.Data, about) {
n++
}
}
return n
}
+88 -29
View File
@@ -22,6 +22,8 @@ import (
"git.zb-server.de/ZB-Server/uptimesebi/internal/agentapi"
"git.zb-server.de/ZB-Server/uptimesebi/internal/authz"
"git.zb-server.de/ZB-Server/uptimesebi/internal/check"
"git.zb-server.de/ZB-Server/uptimesebi/internal/evaluate"
"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"
@@ -33,6 +35,9 @@ const (
// verifyPrefix is the label under which customers publish the TXT record
// proving control of a custom domain.
verifyPrefix = "_uptimesebi."
// domainChangesPerDay bounds how often an organization may set a new
// custom domain.
domainChangesPerDay = 10
)
var (
@@ -127,7 +132,18 @@ func (s *Server) buildSnapshot(ctx context.Context, page store.StatusPage) (agen
failing := map[uuid.UUID]int{}
reported := map[uuid.UUID]int{}
latestByMonitor := map[uuid.UUID][]store.LatestResultsRow{}
// A region that has not reported for longer than the evaluator waits
// is unknown, whatever its last result said.
staleBefore := map[uuid.UUID]time.Time{}
for _, m := range listed {
if !check.Passive(check.Type(m.MonitorType)) {
staleBefore[m.MonitorID] = now.Add(-evaluate.StaleAfter(time.Duration(m.IntervalSeconds) * time.Second))
}
}
for _, l := range latest {
if cut, ok := staleBefore[l.MonitorID]; ok && l.Time.Before(cut) {
continue
}
reported[l.MonitorID]++
if !l.Ok {
failing[l.MonitorID]++
@@ -346,29 +362,15 @@ func (s *Server) agentPage(c *gin.Context) {
fail(c, http.StatusBadRequest, "invalid_input")
return
}
var (
page store.StatusPage
own bool
)
a := agentOf(c)
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
var err error
if page, err = q.FindPublishedPage(ctx, store.FindPublishedPageParams{Host: host, Slug: slug}); err != nil || a.OrgID != nil {
return err
}
own, err = q.OrgServesOwnPages(ctx, &page.OrgID)
return err
})
// The platform's servers leave the pages of organizations that serve
// them on their own servers to those.
if errors.Is(err, pgx.ErrNoRows) || (err == nil && (own || a.OrgID != nil && *a.OrgID != page.OrgID)) {
fail(c, http.StatusNotFound, "not_found")
return
}
page, ok, err := s.agentServes(ctx, agentOf(c), host, slug)
if err != nil {
internalError(c, err)
return
}
if !ok {
fail(c, http.StatusNotFound, "not_found")
return
}
snap, err := s.buildSnapshot(ctx, page)
if err != nil {
internalError(c, err)
@@ -385,6 +387,32 @@ func (s *Server) agentPage(c *gin.Context) {
c.JSON(http.StatusOK, snap)
}
// agentServes finds the published page a status page agent serves at host
// or slug. The platform's servers leave the pages of organizations that
// serve them on their own servers to those, which receive only their own
// organization's pages.
func (s *Server) agentServes(ctx context.Context, a store.GetAgentByHashRow, host, slug *string) (store.StatusPage, bool, error) {
var (
page store.StatusPage
own bool
)
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
var err error
if page, err = q.FindPublishedPage(ctx, store.FindPublishedPageParams{Host: host, Slug: slug}); err != nil || a.OrgID != nil {
return err
}
own, err = q.OrgServesOwnPages(ctx, &page.OrgID)
return err
})
switch {
case errors.Is(err, pgx.ErrNoRows):
return page, false, nil
case err != nil:
return page, false, err
}
return page, !own && (a.OrgID == nil || *a.OrgID == page.OrgID), nil
}
// agentPageIndex lists the pages the status page server serves.
func (s *Server) agentPageIndex(c *gin.Context) {
ctx := c.Request.Context()
@@ -452,6 +480,13 @@ type statusPageView struct {
DomainVerified bool `json:"domain_verified"`
// DomainRecord is the TXT record that proves control of CustomDomain.
DomainRecord *dnsRecord `json:"domain_record,omitempty"`
// CNAMERecord points CustomDomain at the platform's status page
// servers and proves control of it in one, where the platform knows
// their host.
CNAMERecord *dnsRecord `json:"cname_record,omitempty"`
// DomainMissingSince is set when the record of a verified domain has
// not been found since then; it is switched off a week later.
DomainMissingSince *time.Time `json:"domain_missing_since,omitempty"`
// Suspended is set when platform admins took the page offline; it is
// not served whatever Published says.
Suspended bool `json:"suspended,omitempty"`
@@ -464,7 +499,7 @@ type dnsRecord struct {
Value string `json:"value"`
}
func viewStatusPage(p store.StatusPage) statusPageView {
func (s *Server) viewStatusPage(p store.StatusPage) statusPageView {
v := statusPageView{
ID: p.ID, Slug: p.Slug, Title: p.Title, Description: p.Description,
Published: p.Published, ShowComponentDetails: p.ShowComponentDetails,
@@ -474,6 +509,10 @@ func viewStatusPage(p store.StatusPage) statusPageView {
_ = json.Unmarshal(p.Theme, &v.Theme)
if p.CustomDomain != nil {
v.DomainRecord = &dnsRecord{Name: verifyPrefix + *p.CustomDomain, Type: "TXT", Value: p.DomainToken}
if target := s.cnameFor(p.DomainToken); target != "" {
v.CNAMERecord = &dnsRecord{Name: *p.CustomDomain, Type: "CNAME", Value: target}
}
v.DomainMissingSince = p.DomainFailingSince
}
return v
}
@@ -512,7 +551,7 @@ func (s *Server) listStatusPages(c *gin.Context) {
out := []statusPageView{}
for _, r := range rows {
if p.Grants.Can(authz.StatusPagesRead, pageResource(r.ID)) {
out = append(out, viewStatusPage(r))
out = append(out, s.viewStatusPage(r))
}
}
c.JSON(http.StatusOK, gin.H{"pages": out})
@@ -554,7 +593,7 @@ func (s *Server) createStatusPage(c *gin.Context) {
internalError(c, err)
return
}
c.JSON(http.StatusCreated, viewStatusPage(row))
c.JSON(http.StatusCreated, s.viewStatusPage(row))
}
func newDomainToken() string {
@@ -593,7 +632,7 @@ func (s *Server) updateStatusPage(c *gin.Context) {
case err != nil:
internalError(c, err)
default:
c.JSON(http.StatusOK, viewStatusPage(row))
c.JSON(http.StatusOK, s.viewStatusPage(row))
}
}
@@ -711,12 +750,30 @@ func (s *Server) setPageDomain(c *gin.Context) {
p := current(c)
ctx := c.Request.Context()
var row store.StatusPage
limited := false
err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
var err error
cur, err := q.GetStatusPage(ctx, id)
if err != nil {
return err
}
// Every new domain may end in a certificate order; switching domains
// over and over would use up the CA's limits for everyone.
if domain != "" && domain != deref(cur.CustomDomain) {
ok, err := s.limiter.Allow(ctx, "domain_change:"+p.Org.ID.String(), domainChangesPerDay, 24*time.Hour)
if err != nil {
return err
}
if !ok {
limited = true
return nil
}
}
row, err = q.SetStatusPageDomain(ctx, store.SetStatusPageDomainParams{ID: id, CustomDomain: nonEmpty(domain)})
return err
})
switch {
case limited:
fail(c, http.StatusTooManyRequests, "domain_changes_exceeded", "Count", domainChangesPerDay)
case isUniqueViolation(err, "status_pages_custom_domain_key"):
fail(c, http.StatusConflict, "domain_taken")
case errors.Is(err, pgx.ErrNoRows):
@@ -724,14 +781,14 @@ func (s *Server) setPageDomain(c *gin.Context) {
case err != nil:
internalError(c, err)
default:
c.JSON(http.StatusOK, viewStatusPage(row))
c.JSON(http.StatusOK, s.viewStatusPage(row))
}
}
// lookupTXT is replaced in tests.
var lookupTXT = net.DefaultResolver.LookupTXT
// verifyPageDomain checks the TXT record. Only verified domains are served,
// verifyPageDomain looks for the CNAME or the TXT record now. Only verified domains are served,
// so nobody can claim a domain they do not control.
func (s *Server) verifyPageDomain(c *gin.Context) {
id := uuid.MustParse(c.Param("id"))
@@ -758,12 +815,14 @@ func (s *Server) verifyPageDomain(c *gin.Context) {
fail(c, http.StatusConflict, "no_domain")
return
}
records, err := lookupTXT(ctx, verifyPrefix+*row.CustomDomain)
if err != nil || !slices.Contains(records, row.DomainToken) {
method := s.checkDomain(ctx, *row.CustomDomain, row.DomainToken)
if method == "" {
fail(c, http.StatusUnprocessableEntity, "domain_not_verified")
return
}
err = s.db.Tx(ctx, p.scope(), func(q *store.Queries) error { return q.MarkDomainVerified(ctx, id) })
err = s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
return q.MarkDomainVerified(ctx, store.MarkDomainVerifiedParams{ID: id, Now: time.Now(), Method: method})
})
if err != nil {
internalError(c, err)
return
+6
View File
@@ -119,6 +119,12 @@ func TestAllowCertificate(t *testing.T) {
t.Error("AllowCertificate(unknown name) = nil, want refusal")
}
verifyDomain(t, owner, pageID, record)
// A name just found without a page is not asked about again for a
// while; the sync picks the newly verified domain up.
if err := srv.AllowCertificate(ctx, domain); err == nil {
t.Error("AllowCertificate(domain just found missing) = nil, want the miss remembered")
}
srv.Sync(ctx)
if err := srv.AllowCertificate(ctx, domain); err != nil {
t.Errorf("AllowCertificate(verified domain) = %v", err)
}
+2 -1
View File
@@ -152,7 +152,8 @@ func (s *Sessions) Get(ctx context.Context, token string) (*Session, error) {
}
// Sliding expiry, but never beyond the absolute lifetime.
remaining := s.absolute - s.now().Sub(sess.CreatedAt)
if err := s.rdb.Expire(ctx, k, min(s.idle, remaining)).Err(); err != nil {
// PEXPIRE: the rest of the lifetime may be below a second.
if err := s.rdb.PExpire(ctx, k, min(s.idle, remaining)).Err(); err != nil {
return nil, fmt.Errorf("auth: touch session: %w", err)
}
return sess, nil
+22 -1
View File
@@ -101,7 +101,28 @@ type API struct {
// AgentImage is the image name agents are installed and updated from;
// "-checker" or "-statuspage" is appended. Change it for a mirror.
AgentImage string `env:"UPTIME_AGENT_IMAGE" envDefault:"git.zb-server.de/zb-server/uptimesebi"`
Retention Retention
// RegionAlertAfter is how long a region with monitors may have no live
// checker before its admins or owners are told; 0 disables it.
RegionAlertAfter time.Duration `env:"UPTIME_REGION_ALERT_AFTER" envDefault:"5m"`
// Certificates bounds the certificates status page servers may order
// for custom domains.
Certificates Certificates
Retention Retention
}
// Certificates limits new ACME orders for custom domains, so neither one
// organization nor a flood of names uses up the CA's rate limits, which
// apply per ACME account and so to all servers of an owner together.
// Renewals are not counted.
type Certificates struct {
// PerOrgPerDay is for the domains of one organization.
PerOrgPerDay int `env:"UPTIME_CERTS_PER_ORG_PER_DAY" envDefault:"20"`
// PerOwnerPerHour is for all servers of the platform, or of one
// organization, together.
PerOwnerPerHour int `env:"UPTIME_CERTS_PER_HOUR" envDefault:"30"`
// PerNamePerDay stops a domain whose orders keep failing from using
// up the rest.
PerNamePerDay int `env:"UPTIME_CERTS_PER_NAME_PER_DAY" envDefault:"5"`
}
// Retention sets how long data is kept. Zero keeps it forever.
+16 -9
View File
@@ -1,9 +1,11 @@
// Package evaluate turns per-region check results into a monitor state.
//
// A monitor goes down only when every region it is assigned to has failed
// the configured number of times in a row and reported recently. A region
// without recent results counts as unknown and keeps the monitor up: one
// checker losing its network must not page anyone. Any successful region
// A monitor goes down when every region it is assigned to that reported
// recently has failed the configured number of times in a row: one region
// failing while another succeeds is the checker's problem, not the
// target's. A region without recent results counts as unknown and is left
// out, so a dead region neither keeps a monitor up nor takes it down; with
// every region unknown nothing is judged at all. Any successful region
// brings the monitor back up.
//
// The state lives in Redis and each observation is applied by one Lua
@@ -53,9 +55,9 @@ type Observation struct {
Regions []string
}
// staleAfter is how old a region's last result may be before the region
// StaleAfter is how old a region's last result may be before the region
// counts as unknown.
func staleAfter(interval time.Duration) time.Duration {
func StaleAfter(interval time.Duration) time.Duration {
return max(3*interval, 2*time.Minute)
}
@@ -86,12 +88,17 @@ if state == 'down' then
end
return 'none'
end
local reporting = 0
for i = 7, #ARGV do
local r = ARGV[i]
local fails = tonumber(redis.call('HGET', key, 'f:' .. r) or '0')
local seen = tonumber(redis.call('HGET', key, 'a:' .. r) or '0')
if fails < need or seen < stale then return 'none' end
if seen >= stale then
local fails = tonumber(redis.call('HGET', key, 'f:' .. r) or '0')
if fails < need then return 'none' end
reporting = reporting + 1
end
end
if reporting == 0 then return 'none' end
redis.call('HSET', key, 'state', 'down')
return 'down'
`)
@@ -113,7 +120,7 @@ func (e *Evaluator) Observe(ctx context.Context, o Observation) (Transition, err
if o.OK {
ok = "1"
}
stale := e.now().Add(-staleAfter(o.Interval)).UnixMilli()
stale := e.now().Add(-StaleAfter(o.Interval)).UnixMilli()
args := []any{o.Region, ok, o.At.UnixMilli(), max(o.Confirmations, 1), stale, int(stateTTL.Seconds())}
for _, r := range o.Regions {
args = append(args, r)
+22 -7
View File
@@ -55,9 +55,9 @@ func play(t *testing.T, e *Evaluator, now *time.Time, regions []string, confirma
func TestDownOnlyWhenAllRegionsFail(t *testing.T) {
e, now := newTest(t)
play(t, e, now, []string{"eu", "us"}, 2, []step{
{"eu", false, None},
{"eu", false, None}, // eu confirmed down, us has not reported
{"us", true, None},
{"eu", false, None},
{"eu", false, None}, // eu confirmed down, us still fine
{"us", false, None},
{"eu", false, None},
{"us", false, Down}, // both regions failed twice in a row
@@ -79,7 +79,7 @@ func TestSingleRegionWithConfirmations(t *testing.T) {
})
}
func TestSilentRegionBlocksAlert(t *testing.T) {
func TestSilentRegionIsLeftOut(t *testing.T) {
e, now := newTest(t)
id := uuid.New()
obs := func(region string, ok bool) Transition {
@@ -92,12 +92,27 @@ func TestSilentRegionBlocksAlert(t *testing.T) {
}
return got
}
obs("us", false)
// us stops reporting for longer than three intervals.
obs("us", true)
// us stops reporting for longer than three intervals: the failures of
// eu alone decide.
*now = now.Add(5 * time.Minute)
if got := obs("eu", false); got != None {
t.Errorf("eu failure with us silent = %v, want none", got)
if got := obs("eu", false); got != Down {
t.Errorf("eu failure with us silent = %v, want down", got)
}
// us reporting a success again brings the monitor back up.
*now = now.Add(time.Second)
if got := obs("us", true); got != Up {
t.Errorf("us success after the outage = %v, want up", got)
}
}
func TestReportingRegionStillVetoes(t *testing.T) {
e, now := newTest(t)
play(t, e, now, []string{"eu", "us"}, 1, []step{
{"us", true, None},
{"eu", false, None}, // us reported recently and was fine
{"eu", false, None},
})
}
func TestOutOfOrderResultIgnored(t *testing.T) {
+32 -3
View File
@@ -514,8 +514,16 @@
"console.sso_required_action": "Mit SSO anmelden",
"console.suspended_reason": "Grund: {{.Reason}}",
"console.totp_missing_action": "Jetzt einrichten",
"email.domain_missing.body": "Die Statusseite {{.Page}} wird unter {{.Domain}} ausgeliefert, aber der DNS-Eintrag, der nachweist, dass die Domain zu ihr gehört, ist nicht mehr zu finden.\n\nIst er bis {{.Date}} nicht zurück, wird die Domain abgeschaltet und die Seite dort nicht mehr ausgeliefert. Den Eintrag, der wiederhergestellt werden muss, findest du hier:\n{{.Link}}",
"email.domain_missing.subject": "Der DNS-Eintrag von {{.Domain}} fehlt",
"email.domain_off.body": "Der DNS-Eintrag von {{.Domain}} fehlt seit einer Woche, deshalb wird die Statusseite {{.Page}} dort nicht mehr ausgeliefert.\n\nStelle den Eintrag wieder her und prüfe die Domain erneut:\n{{.Link}}",
"email.domain_off.subject": "{{.Domain}} wurde abgeschaltet",
"email.opened.body": "{{.Monitor}} ({{.Target}}) ist in allen Regionen nicht erreichbar seit {{.Since}}.\n\nLetzte Fehler:\n{{.Cause}}\n\nDu erhältst diese Nachricht, weil ein Benachrichtigungskanal deiner Organisation diese Adresse nutzt.",
"email.opened.subject": "[DOWN] {{.Monitor}}",
"email.region_back.body": "Region {{.Region}} hat wieder einen aktiven Checker; seit {{.Since}} hatte sie keinen. Überfällige Prüfungen laufen sofort.\n\n{{.Link}}",
"email.region_back.subject": "Region {{.Region}} prüft wieder",
"email.region_down.body": "Region {{.Region}} hat seit {{.Minutes}} Minuten keinen aktiven Checker, seit {{.Since}}.\n\nMonitore, die nur von dort geprüft werden, werden gerade nicht geprüft: Sie fallen weder aus noch alarmieren sie. Monitore mit weiteren Regionen werden nur nach diesen beurteilt, bis diese Region wieder meldet.\n\nStarte einen Checker der Region oder sieh dir seine Logs an:\n{{.Link}}",
"email.region_down.subject": "Region {{.Region}} hat keinen aktiven Checker",
"email.resolved.body": "{{.Monitor}} ({{.Target}}) ist nach {{.Duration}} wieder erreichbar.",
"email.resolved.subject": "[UP] {{.Monitor}}",
"email.support_admin.body": "Hallo,\n\nein Support-Ticket wartet auf eine Antwort:\n\n{{.Subject}}\n\n{{.Link}}",
@@ -539,7 +547,8 @@
"error.confirmation_failed": "Die Bestätigung stimmt nicht.",
"error.consent_outdated": "Die Dokumente haben sich inzwischen geändert. Lade die Seite neu und stimme der aktuellen Fassung zu.",
"error.consent_required": "Bitte stimme zuerst Datenschutz und AGB zu.",
"error.domain_not_verified": "Der TXT-Eintrag wurde noch nicht gefunden. DNS-Änderungen brauchen manchmal etwas Zeit.",
"error.domain_changes_exceeded": "Die eigene Domain wurde heute schon {{.Count}}-mal geändert. Versuch es morgen wieder.",
"error.domain_not_verified": "Weder der CNAME- noch der TXT-Eintrag wurde bisher gefunden. DNS-Änderungen brauchen manchmal etwas, bis sie sichtbar sind.",
"error.domain_taken": "Diese Domain nutzt bereits eine andere Statuspage.",
"error.email_not_configured": "E-Mail ist auf diesem Server nicht verfügbar.",
"error.email_taken": "Diese E-Mail-Adresse ist bereits registriert.",
@@ -1045,6 +1054,7 @@
"monitors.db_tls_verify": "TLS mit geprüftem Zertifikat",
"monitors.db_user": "Benutzer",
"monitors.db_user_redis": "Benutzer (ACL, optional)",
"monitors.dead_region": "Region {{.Region}} hat seit {{.Since}} keinen aktiven Checker.",
"monitors.delete": "Monitor löschen",
"monitors.delete_confirm": "Diesen Monitor samt Verlauf löschen?",
"monitors.dns_expect": "Erwartete Antwort (optional)",
@@ -1081,6 +1091,7 @@
"monitors.minecraft_hint": "Ziel ist host:port (Java meist 25565, Bedrock 19132). Pingt den Server wie die Serverliste im Spiel.",
"monitors.minecraft_java": "Java Edition",
"monitors.new": "Neuer Monitor",
"monitors.no_data_since": "keine Daten seit {{.Time}}",
"monitors.no_match": "Kein Monitor gefunden.",
"monitors.no_results": "Noch keine Ergebnisse.",
"monitors.op_absent": "fehlt",
@@ -1167,6 +1178,11 @@
"monitors.type_steam": "Steam-Spieleserver",
"monitors.type_tcp": "TCP-Port",
"monitors.type_tls": "TLS-Zertifikat",
"monitors.unchecked": "wird nicht geprüft",
"monitors.unchecked_banner": {
"one": "1 Monitor wird gerade nicht geprüft: Keine Region hat für ihn in letzter Zeit gemeldet. Er fällt weder aus noch alarmiert er, bis wieder ein Checker meldet.",
"other": "{{.Count}} Monitore werden gerade nicht geprüft: Keine Region hat für sie in letzter Zeit gemeldet. Sie fallen weder aus noch alarmieren sie, bis wieder ein Checker meldet."
},
"monitors.ungrouped": "Ohne Gruppe",
"monitors.uptime_chart": "Uptime pro Zeitraum",
"monitors.verify_tls": "TLS-Zertifikat prüfen",
@@ -1238,10 +1254,22 @@
"pages.delete_confirm": "Diese Statuspage löschen?",
"pages.description": "Beschreibung",
"pages.domain": "Eigene Domain",
"pages.domain_cname": "Richte die Domain (CNAME oder A-Record) auf deinen Statuspage-Server; er holt sich automatisch ein Zertifikat, wenn TLS aktiviert ist.",
"pages.domain_instructions": "Lege diesen DNS-Eintrag an und prüfe ihn dann. Nur geprüfte Domains werden ausgeliefert.",
"pages.domain_alt": "Dann ist der CNAME von außen nicht zu sehen. Weise die Domain stattdessen mit diesem TXT-Eintrag nach und lass die Domain oder den Origin deines Proxys auf {{.Target}} zeigen; für eine Domain ohne Subdomain nutze einen ALIAS- oder ANAME-Eintrag oder CNAME-Flattening.",
"pages.domain_alt_summary": "Hinter einem Proxy wie Cloudflare oder eine Domain ohne Subdomain?",
"pages.domain_apex": "Eine Domain ohne Subdomain (example.com) kann keinen CNAME-Eintrag haben. Nutze stattdessen den ALIAS- oder ANAME-Eintrag deines DNS-Anbieters oder A/AAAA-Einträge.",
"pages.domain_cname_step": "Lege diesen CNAME-Eintrag an. Er lässt die Domain auf die Statusseiten-Server zeigen und weist zugleich nach, dass sie dir gehört, denn sein Ziel gehört nur zu dieser Seite. Wir sehen alle paar Minuten nach und prüfen die Domain von selbst; DNS-Änderungen brauchen manchmal etwas, bis sie sichtbar sind.",
"pages.domain_intro": "Liefere diese Seite unter einer eigenen Domain aus, z. B. status.example.com. Meist reicht ein einziger DNS-Eintrag; HTTPS kommt von selbst.",
"pages.domain_keep": "Lass den Eintrag bestehen: Er wird täglich geprüft, und eine Domain, deren Eintrag eine Woche lang fehlt, wird abgeschaltet, damit niemand anderes sie übernehmen kann.",
"pages.domain_missing": "Der Eintrag dieser Domain ist seit {{.Since}} nicht mehr zu finden. Kommt er nicht zurück, wird die Domain am {{.Date}} abgeschaltet.",
"pages.domain_name": "Domain",
"pages.domain_step_cname_own": "Lass die Domain dann auf die eigenen Statusseiten-Server deiner Organisation zeigen: per CNAME-Eintrag auf deren Hostnamen oder per A/AAAA-Eintrag auf deren Adressen.",
"pages.domain_step_cname_unknown": "Lass die Domain dann per CNAME-Eintrag auf die Statusseiten-Server der Plattform zeigen; das Ziel nennt dir der Betreiber dieser Installation.",
"pages.domain_step_tls": "HTTPS: Das Zertifikat wird beim ersten Aufruf über HTTPS automatisch geholt, das kann bis zu einer Minute dauern. Zum Schutz der Limits der Zertifizierungsstelle, die sich alle Organisationen teilen, sind neue Zertifikate pro Tag begrenzt, und die Domain lässt sich höchstens {{.Count}}-mal am Tag ändern.",
"pages.domain_step_verified": "1. Domain geprüft.",
"pages.domain_step_verify": "Weise mit diesem TXT-Eintrag nach, dass die Domain dir gehört, und prüfe ihn dann. Bis dahin wird die Domain weder ausgeliefert noch bekommt sie ein Zertifikat.",
"pages.domain_verified": "Domain geprüft.",
"pages.domain_verified_by_cname": "Domain über ihren CNAME-Eintrag geprüft.",
"pages.domain_verified_by_txt": "Domain über ihren TXT-Eintrag geprüft.",
"pages.draft": "Entwurf",
"pages.export": "Als HTML exportieren",
"pages.group": "Gruppe",
@@ -1271,6 +1299,7 @@
"pages.title": "Statuspages",
"pages.value": "Wert",
"pages.verify": "Prüfen",
"pages.verify_now": "Jetzt prüfen",
"perm.audit.read": "Audit-Log einsehen",
"perm.incidents.read": "Incidents sehen",
"perm.incidents.write": "Incidents verwalten",
+32 -3
View File
@@ -514,8 +514,16 @@
"console.sso_required_action": "Sign in with SSO",
"console.suspended_reason": "Reason: {{.Reason}}",
"console.totp_missing_action": "Set up now",
"email.domain_missing.body": "The status page {{.Page}} is served at {{.Domain}}, but the DNS record proving that the domain belongs to it can no longer be found.\n\nUnless it is back by {{.Date}}, the domain is switched off and the page is no longer served there. The record to restore is shown here:\n{{.Link}}",
"email.domain_missing.subject": "The DNS record of {{.Domain}} is gone",
"email.domain_off.body": "The DNS record of {{.Domain}} has been missing for a week, so the status page {{.Page}} is no longer served there.\n\nRestore the record and verify the domain again:\n{{.Link}}",
"email.domain_off.subject": "{{.Domain}} has been switched off",
"email.opened.body": "{{.Monitor}} ({{.Target}}) is down in all of its regions since {{.Since}}.\n\nLast errors:\n{{.Cause}}\n\nYou receive this because a notification channel of your organization is set up for this address.",
"email.opened.subject": "[DOWN] {{.Monitor}}",
"email.region_back.body": "Region {{.Region}} has an active checker again; it had none since {{.Since}}. Overdue checks run right away.\n\n{{.Link}}",
"email.region_back.subject": "Region {{.Region}} is checking again",
"email.region_down.body": "Region {{.Region}} has had no active checker for {{.Minutes}} minutes, since {{.Since}}.\n\nMonitors checked only from there are not being checked right now: they neither go down nor alert. Monitors with other regions as well are judged by those alone until this one reports again.\n\nStart a checker of the region or look at its logs:\n{{.Link}}",
"email.region_down.subject": "Region {{.Region}} has no active checker",
"email.resolved.body": "{{.Monitor}} ({{.Target}}) is reachable again after {{.Duration}}.",
"email.resolved.subject": "[UP] {{.Monitor}}",
"email.support_admin.body": "Hello,\n\na support ticket waits for an answer:\n\n{{.Subject}}\n\n{{.Link}}",
@@ -539,7 +547,8 @@
"error.confirmation_failed": "The confirmation does not match.",
"error.consent_outdated": "The documents changed in the meantime. Reload the page and accept the current version.",
"error.consent_required": "Please accept the privacy policy and terms first.",
"error.domain_not_verified": "The TXT record was not found yet. DNS changes can take a while to appear.",
"error.domain_changes_exceeded": "The custom domain was changed {{.Count}} times today already. Try again tomorrow.",
"error.domain_not_verified": "Neither the CNAME nor the TXT record was found yet. DNS changes can take a while to appear.",
"error.domain_taken": "This domain is already used by another status page.",
"error.email_not_configured": "Email is not available on this server.",
"error.email_taken": "This email address is already registered.",
@@ -1045,6 +1054,7 @@
"monitors.db_tls_verify": "TLS with verified certificate",
"monitors.db_user": "User",
"monitors.db_user_redis": "User (ACL, optional)",
"monitors.dead_region": "Region {{.Region}} has had no active checker since {{.Since}}.",
"monitors.delete": "Delete monitor",
"monitors.delete_confirm": "Delete this monitor and its history?",
"monitors.dns_expect": "Expected answer (optional)",
@@ -1081,6 +1091,7 @@
"monitors.minecraft_hint": "Target is host:port (Java usually 25565, Bedrock 19132). Pings the server like the in-game server list.",
"monitors.minecraft_java": "Java Edition",
"monitors.new": "New monitor",
"monitors.no_data_since": "no data since {{.Time}}",
"monitors.no_match": "No monitor matches.",
"monitors.no_results": "No results yet.",
"monitors.op_absent": "is absent",
@@ -1167,6 +1178,11 @@
"monitors.type_steam": "Steam game server",
"monitors.type_tcp": "TCP port",
"monitors.type_tls": "TLS certificate",
"monitors.unchecked": "not being checked",
"monitors.unchecked_banner": {
"one": "1 monitor is not being checked: no region has reported for it recently. It neither goes down nor alerts until a checker reports again.",
"other": "{{.Count}} monitors are not being checked: no region has reported for them recently. They neither go down nor alert until a checker reports again."
},
"monitors.ungrouped": "Without group",
"monitors.uptime_chart": "Uptime per period",
"monitors.verify_tls": "Verify TLS certificate",
@@ -1238,10 +1254,22 @@
"pages.delete_confirm": "Delete this status page?",
"pages.description": "Description",
"pages.domain": "Custom domain",
"pages.domain_cname": "Point the domain (CNAME or A record) at your status page server; it obtains a certificate automatically when TLS is enabled.",
"pages.domain_instructions": "Create this DNS record, then verify. Only verified domains are served.",
"pages.domain_alt": "Then the CNAME cannot be seen from outside. Prove the domain with this TXT record instead, and point the domain, or your proxy's origin, at {{.Target}}; for a domain without a subdomain use an ALIAS or ANAME record or CNAME flattening.",
"pages.domain_alt_summary": "Behind a proxy such as Cloudflare, or a domain without a subdomain?",
"pages.domain_apex": "A domain without a subdomain (example.com) cannot have a CNAME record. Use your DNS provider's ALIAS or ANAME record, or A/AAAA records, instead.",
"pages.domain_cname_step": "Create this CNAME record. It points the domain at the status page servers and proves that the domain is yours, because its target belongs to this page alone. We look for it every few minutes and verify the domain on our own; DNS changes can take a while to appear.",
"pages.domain_intro": "Serve this page under a domain of your own, e.g. status.example.com. One DNS record is usually all it takes; HTTPS follows by itself.",
"pages.domain_keep": "Keep the record in place: it is checked daily, and a domain whose record has been gone for a week is switched off, so nobody else can take it over.",
"pages.domain_missing": "The record of this domain has not been found since {{.Since}}. Unless it is back, the domain is switched off on {{.Date}}.",
"pages.domain_name": "Domain",
"pages.domain_step_cname_own": "Then point the domain at your organization's own status page servers: a CNAME record to their host name, or A/AAAA records to their addresses.",
"pages.domain_step_cname_unknown": "Then point the domain at the platform's status page servers with a CNAME record; the operator of this installation tells you its target.",
"pages.domain_step_tls": "HTTPS: the certificate is obtained automatically on the first visit over HTTPS, which can take up to a minute. To protect the certificate authority's limits that all organizations share, new certificates are limited per day, and the domain can be changed at most {{.Count}} times a day.",
"pages.domain_step_verified": "1. Domain verified.",
"pages.domain_step_verify": "Prove the domain is yours with this TXT record, then verify. Until then the domain is neither served nor given a certificate.",
"pages.domain_verified": "Domain verified.",
"pages.domain_verified_by_cname": "Domain verified by its CNAME record.",
"pages.domain_verified_by_txt": "Domain verified by its TXT record.",
"pages.draft": "draft",
"pages.export": "Export as HTML",
"pages.group": "Group",
@@ -1271,6 +1299,7 @@
"pages.title": "Status pages",
"pages.value": "Value",
"pages.verify": "Verify",
"pages.verify_now": "Check now",
"perm.audit.read": "View the audit log",
"perm.incidents.read": "View incidents",
"perm.incidents.write": "Manage incidents",
@@ -0,0 +1,19 @@
-- +goose Up
-- Custom domains are verified by a CNAME to a target unique to the page, or
-- by the TXT record, and checked again while they are in use: a domain that
-- no longer points at the page is switched off after a grace period, so a
-- record left behind cannot be taken over. Domains verified before this
-- have no method and are not checked again.
ALTER TABLE status_pages
ADD COLUMN domain_set_at timestamptz,
ADD COLUMN domain_checked_at timestamptz,
ADD COLUMN domain_failing_since timestamptz,
ADD COLUMN domain_verify_method text CHECK (domain_verify_method IN ('cname', 'txt'));
UPDATE status_pages SET domain_set_at = updated_at WHERE custom_domain IS NOT NULL;
-- +goose Down
ALTER TABLE status_pages
DROP COLUMN domain_verify_method,
DROP COLUMN domain_failing_since,
DROP COLUMN domain_checked_at,
DROP COLUMN domain_set_at;
+10 -1
View File
@@ -281,7 +281,7 @@ func (s *Scheduler) Take(ctx context.Context, instance uuid.UUID, max int, wait
return nil, nil
}
// BLPOP blocks server side and ignores ctx, so wait in slices.
first, err := s.rdb.BLPop(ctx, min(left, time.Second), q).Result()
first, err := s.blpop(ctx, min(left, time.Second), q)
if errors.Is(err, redis.Nil) {
continue
}
@@ -306,6 +306,15 @@ func (s *Scheduler) Take(ctx context.Context, instance uuid.UUID, max int, wait
return out, nil
}
// blpop is BLPOP with a timeout below a second, which go-redis would round
// up to one (Redis takes fractions of seconds since 6.0).
func (s *Scheduler) blpop(ctx context.Context, timeout time.Duration, key string) ([]string, error) {
if timeout >= time.Second {
return s.rdb.BLPop(ctx, timeout, key).Result()
}
return s.rdb.Do(ctx, "BLPOP", key, strconv.FormatFloat(timeout.Seconds(), 'f', 3, 64)).StringSlice()
}
// Release returns instance's queued runs to its region and forgets it.
func (s *Scheduler) Release(ctx context.Context, region string, instance uuid.UUID) error {
// Marking the instance stale lets the dispatch script do the handover,
+16 -1
View File
@@ -188,11 +188,26 @@ func TestTakeWaits(t *testing.T) {
if err != nil || len(got) != 0 {
t.Fatalf("Take() on empty queue = %v, %v", got, err)
}
if waited := time.Since(start); waited < 250*time.Millisecond {
// Not rounded up to the second that BLPOP counts in.
if waited := time.Since(start); waited < 250*time.Millisecond || waited > 800*time.Millisecond {
t.Errorf("Take() returned after %v, want it to wait about 300ms", waited)
}
}
func TestTakeGetsAJobDuringAShortWait(t *testing.T) {
s, _ := newTest(t)
ctx := context.Background()
in, monitor := uuid.New(), uuid.New()
go func() {
time.Sleep(100 * time.Millisecond)
s.rdb.RPush(ctx, jobsPrefix+in.String(), monitor.String()+"|1800000000000")
}()
got, err := s.Take(ctx, in, 10, 600*time.Millisecond)
if err != nil || len(got) != 1 || got[0].MonitorID != monitor {
t.Fatalf("Take() = %v, %v; want the job pushed while waiting", got, err)
}
}
func TestTakeReturnsWhenCancelled(t *testing.T) {
s, _ := newTest(t)
ctx, cancel := context.WithCancel(context.Background())
+55 -3
View File
@@ -45,6 +45,15 @@ const (
// staleNoticeAfter is when visitors are told the state may be outdated;
// a page nobody visited is up to syncInterval old.
staleNoticeAfter = 2 * syncInterval
// missFor is how long a host or slug without a page is answered
// without asking the API again.
missFor = time.Minute
maxMissing = 10_000
// unknownPerSecond bounds the lookups of hosts and slugs that are
// neither cached nor known to be missing, so a flood of made-up names
// is not passed on to the API. Every page the API lists is cached by
// the sync, so known pages are not affected.
unknownPerSecond = 20
)
// Source fetches snapshots; *agentapi.Client implements it.
@@ -70,8 +79,14 @@ type Server struct {
mu sync.Mutex
cache map[string]entry
refreshing map[string]bool
// visited holds when each page was last visited.
// visited holds when each cached page was last visited.
visited map[string]time.Time
// missing holds when a key was last found to have no page.
missing map[string]time.Time
// unknownSecond and unknownCount count lookups passed on to the API in
// the current second.
unknownSecond int64
unknownCount int
// background tracks refreshes started by visits.
background sync.WaitGroup
}
@@ -104,6 +119,7 @@ func New(src Source, catalog *i18n.Catalog, log *slog.Logger, o Options) (*Serve
s := &Server{
src: src, catalog: catalog, log: log, ownHosts: map[string]bool{}, dir: o.CacheDir,
now: time.Now, cache: map[string]entry{}, refreshing: map[string]bool{}, visited: map[string]time.Time{},
missing: map[string]time.Time{},
}
for _, h := range o.Hosts {
s.ownHosts[strings.ToLower(h)] = true
@@ -167,6 +183,7 @@ func (s *Server) persist(e entry) {
func (s *Server) forget(key string) {
s.mu.Lock()
delete(s.cache, key)
delete(s.visited, key)
s.mu.Unlock()
if s.dir != "" {
_ = os.Remove(s.fileFor(key))
@@ -321,9 +338,15 @@ func (s *Server) localizeRequest(c *gin.Context) {
// lookup answers from the cache whenever possible and refreshes in the
// background; only unknown pages wait for the API.
func (s *Server) lookup(ctx context.Context, key, host, slug string) (entry, bool) {
now := s.now()
s.mu.Lock()
e, cached := s.cache[key]
s.visited[key] = s.now()
if cached {
s.visited[key] = now
} else if !s.mayAsk(key, now) {
s.mu.Unlock()
return entry{}, false
}
s.mu.Unlock()
if cached {
if s.now().Sub(e.Fetched) >= freshFor {
@@ -331,7 +354,29 @@ func (s *Server) lookup(ctx context.Context, key, host, slug string) (entry, boo
}
return e, true
}
return s.fetch(ctx, key, host, slug)
e, ok := s.fetch(ctx, key, host, slug)
if ok {
s.mu.Lock()
s.visited[key] = now
s.mu.Unlock()
}
return e, ok
}
// mayAsk reports whether an uncached key may be looked up at the API: not
// when it was just found missing, nor beyond unknownPerSecond. s.mu is held.
func (s *Server) mayAsk(key string, now time.Time) bool {
if t, ok := s.missing[key]; ok && now.Sub(t) < missFor {
return false
}
if sec := now.Unix(); sec != s.unknownSecond {
s.unknownSecond, s.unknownCount = sec, 0
}
if s.unknownCount >= unknownPerSecond {
return false
}
s.unknownCount++
return true
}
func (s *Server) fetch(ctx context.Context, key, host, slug string) (entry, bool) {
@@ -351,6 +396,12 @@ func (s *Server) fetch(ctx context.Context, key, host, slug string) (entry, bool
return old, true
case errors.Is(err, agentapi.ErrNotFound):
s.forget(key)
s.mu.Lock()
if len(s.missing) >= maxMissing {
clear(s.missing)
}
s.missing[key] = s.now()
s.mu.Unlock()
return entry{}, false
case err != nil:
s.log.WarnContext(ctx, "fetching status page failed", "page", key, "error", err)
@@ -362,6 +413,7 @@ func (s *Server) fetch(ctx context.Context, key, host, slug string) (entry, bool
e := entry{Key: key, Host: host, Slug: slug, Snap: snap, Fetched: s.now(), Checksum: snap.Checksum()}
s.mu.Lock()
s.cache[key] = e
delete(s.missing, key)
s.mu.Unlock()
s.persist(e)
return e, true
+34
View File
@@ -151,6 +151,40 @@ func (s CertStorage) Unlock(ctx context.Context, name string) error {
return s.c.StorageUnlock(ctx, name)
}
// CertificateGate is asked before a new certificate is ordered;
// *agentapi.Client implements it.
type CertificateGate interface {
AllowCertificate(ctx context.Context, name string) error
}
// OnCertEvent is certmagic's event hook. Before a new certificate for a
// custom domain is ordered it asks the API, which allows verified domains
// of pages this server serves within limits shared by all servers; that
// keeps the CA's rate limits from being used up. Renewals and the default
// hosts are not asked about.
func (s *Server) OnCertEvent(ctx context.Context, event string, data map[string]any) error {
if event != "cert_obtaining" || data["renewal"] == true {
return nil
}
name, _ := data["identifier"].(string)
host := hostOnly(name)
gate, ok := s.src.(CertificateGate)
if s.ownHosts[host] || !ok {
return nil
}
switch err := gate.AllowCertificate(ctx, host); {
case err == nil:
return nil
case errors.Is(err, agentapi.ErrRateLimited):
s.log.WarnContext(ctx, "certificate order refused: limit reached", "domain", host)
return fmt.Errorf("limit on new certificates reached for %s", host)
case errors.Is(err, agentapi.ErrNotFound):
return fmt.Errorf("no status page for %s", host)
default:
return fmt.Errorf("asking whether to order a certificate for %s: %w", host, err)
}
}
// AllowCertificate decides whether to obtain a certificate for name on
// demand: only for the default hosts and for verified custom domains of
// pages this server may serve. Anything else would let strangers make us
+115
View File
@@ -0,0 +1,115 @@
package statuspage
import (
"context"
"errors"
"fmt"
"net/http"
"testing"
"time"
"git.zb-server.de/ZB-Server/uptimesebi/internal/agentapi"
)
func (f *fakeSource) callCount() int {
f.mu.Lock()
defer f.mu.Unlock()
return f.calls
}
func TestUnknownNamesAreNotAskedAgainAtOnce(t *testing.T) {
now := time.Now()
src := newSource()
h := newHarness(t, src, "", &now)
for range 3 {
if code, _ := h.get("nope.example.test", "/"); code != http.StatusNotFound {
t.Fatalf("unknown host = %d, want 404", code)
}
}
if n := src.callCount(); n != 1 {
t.Errorf("the API was asked %d times about one unknown host, want 1", n)
}
now = now.Add(missFor)
h.get("nope.example.test", "/")
if n := src.callCount(); n != 2 {
t.Errorf("after %v the API was asked %d times in all, want 2", missFor, n)
}
h.srv.mu.Lock()
visited := len(h.srv.visited)
h.srv.mu.Unlock()
if visited != 0 {
t.Errorf("unknown hosts were recorded as visited pages: %d", visited)
}
}
func TestFloodOfMadeUpNamesIsThrottled(t *testing.T) {
now := time.Now()
src := newSource()
h := newHarness(t, src, "", &now)
h.srv.Sync(context.Background())
before := src.callCount()
for i := range 200 {
h.get(fmt.Sprintf("x%d.example.test", i), "/")
}
if n := src.callCount() - before; n > unknownPerSecond {
t.Errorf("a flood of made-up hosts reached the API %d times in one second, want at most %d", n, unknownPerSecond)
}
// Pages the sync cached are still served during the flood.
if code, _ := h.get("status.acme.test", "/"); code != http.StatusOK {
t.Errorf("a known page during the flood = %d, want 200", code)
}
now = now.Add(time.Second)
if err := h.srv.AllowCertificate(context.Background(), "status.acme.test"); err != nil {
t.Errorf("a known custom domain after the flood: %v", err)
}
}
type gatedSource struct {
*fakeSource
asked []string
err error
}
func (g *gatedSource) AllowCertificate(_ context.Context, name string) error {
g.asked = append(g.asked, name)
return g.err
}
func TestNewCertificatesAreOrderedOnlyWhenTheAPIAllows(t *testing.T) {
now := time.Now()
g := &gatedSource{fakeSource: newSource()}
h := newHarness(t, g.fakeSource, "", &now)
h.srv.src = g
ctx := context.Background()
obtain := func(name string, renewal bool) error {
data := map[string]any{"identifier": name}
if renewal {
data["renewal"] = true
}
return h.srv.OnCertEvent(ctx, "cert_obtaining", data)
}
if err := obtain("status.acme.test", false); err != nil {
t.Errorf("allowed order: %v", err)
}
// Renewals, the default hosts and other events are not asked about.
if err := obtain("status.acme.test", true); err != nil {
t.Errorf("renewal: %v", err)
}
if err := obtain("status.example.test", false); err != nil {
t.Errorf("default host: %v", err)
}
if err := h.srv.OnCertEvent(ctx, "cert_obtained", map[string]any{"identifier": "status.acme.test"}); err != nil {
t.Errorf("other event: %v", err)
}
if len(g.asked) != 1 || g.asked[0] != "status.acme.test" {
t.Errorf("asked about %v, want only the new order", g.asked)
}
for _, refuse := range []error{agentapi.ErrRateLimited, agentapi.ErrNotFound, errors.New("api down")} {
g.err = refuse
if err := obtain("status.acme.test", false); err == nil {
t.Errorf("order went ahead although the API answered %v", refuse)
}
}
}
+70
View File
@@ -318,6 +318,32 @@ func (q *Queries) ListVisibleRegions(ctx context.Context) ([]Region, error) {
return items, nil
}
const orgOwnerEmails = `-- name: OrgOwnerEmails :many
SELECT u.email FROM memberships m JOIN users u ON u.id = m.user_id
WHERE m.org_id = $1 AND m.is_owner AND u.disabled_at IS NULL
`
// System scope.
func (q *Queries) OrgOwnerEmails(ctx context.Context, orgID uuid.UUID) ([]string, error) {
rows, err := q.db.Query(ctx, orgOwnerEmails, orgID)
if err != nil {
return nil, err
}
defer rows.Close()
items := []string{}
for rows.Next() {
var email string
if err := rows.Scan(&email); err != nil {
return nil, err
}
items = append(items, email)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const orgServesOwnPages = `-- name: OrgServesOwnPages :one
SELECT EXISTS (
SELECT 1 FROM agents
@@ -334,6 +360,50 @@ func (q *Queries) OrgServesOwnPages(ctx context.Context, orgID *uuid.UUID) (bool
return exists, err
}
const regionsToWatch = `-- name: RegionsToWatch :many
SELECT r.id, r.name, r.org_id, o.name AS org_name
FROM regions r
LEFT JOIN orgs o ON o.id = r.org_id
WHERE EXISTS (SELECT 1 FROM agents a WHERE a.kind = 'checker' AND a.region_id = r.id)
AND EXISTS (SELECT 1 FROM monitor_regions mr JOIN monitors m ON m.id = mr.monitor_id
WHERE mr.region_id = r.id AND m.enabled)
ORDER BY r.name
`
type RegionsToWatchRow struct {
ID uuid.UUID
Name string
OrgID *uuid.UUID
OrgName *string
}
// System scope: regions that have checkers and enabled monitors, so a
// region without a live checker leaves monitors unchecked.
func (q *Queries) RegionsToWatch(ctx context.Context) ([]RegionsToWatchRow, error) {
rows, err := q.db.Query(ctx, regionsToWatch)
if err != nil {
return nil, err
}
defer rows.Close()
items := []RegionsToWatchRow{}
for rows.Next() {
var i RegionsToWatchRow
if err := rows.Scan(
&i.ID,
&i.Name,
&i.OrgID,
&i.OrgName,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const setAgentAllowPrivate = `-- name: SetAgentAllowPrivate :execrows
UPDATE agents SET allow_private = $1
WHERE id = $2 AND kind = 'checker' AND org_id = $3
+4
View File
@@ -418,6 +418,10 @@ type StatusPage struct {
ShowComponentDetails bool
SuspendedAt *time.Time
SuspendedReason string
DomainSetAt *time.Time
DomainCheckedAt *time.Time
DomainFailingSince *time.Time
DomainVerifyMethod *string
}
type StatusPageGroup struct {
+18 -2
View File
@@ -118,6 +118,11 @@ type Querier interface {
DeleteSuccessEvidence(ctx context.Context, arg DeleteSuccessEvidenceParams) error
DeleteUser(ctx context.Context, id uuid.UUID) (int64, error)
DisableTOTP(ctx context.Context, id uuid.UUID) error
// System scope: domains due for a look at their DNS records. A new one is
// looked at every minute for a quarter of an hour, then every ten minutes
// for two days, after which only the verify button tries again. A verified
// one is checked daily, hourly once its record went missing.
DomainsToCheck(ctx context.Context, arg DomainsToCheckParams) ([]DomainsToCheckRow, error)
EmailKeyTaken(ctx context.Context, emailKey *string) (bool, error)
EnableTOTP(ctx context.Context, arg EnableTOTPParams) error
EnqueueNotification(ctx context.Context, arg EnqueueNotificationParams) error
@@ -261,7 +266,11 @@ type Querier interface {
// their group or one of its ancestors.
MaintenanceForMonitors(ctx context.Context, ids []uuid.UUID) ([]MaintenanceForMonitorsRow, error)
MakeAdmin(ctx context.Context, id uuid.UUID) error
MarkDomainVerified(ctx context.Context, id uuid.UUID) error
// The record of a domain was not found. Returns since when it has not
// been, for a verified domain.
MarkDomainUnconfirmed(ctx context.Context, arg MarkDomainUnconfirmedParams) (*time.Time, error)
// The domain's record was found: verified, or still in place.
MarkDomainVerified(ctx context.Context, arg MarkDomainVerifiedParams) error
MarkEmailVerified(ctx context.Context, id uuid.UUID) (User, error)
MarkInvitationAccepted(ctx context.Context, id uuid.UUID) (int64, error)
MarkNotificationFailed(ctx context.Context, arg MarkNotificationFailedParams) error
@@ -289,6 +298,8 @@ type Querier interface {
OrgIncidentUpdatesExport(ctx context.Context, orgID uuid.UUID) ([]OrgIncidentUpdatesExportRow, error)
OrgIncidentsExport(ctx context.Context, orgID uuid.UUID) ([]OrgIncidentsExportRow, error)
OrgMembersExport(ctx context.Context, orgID uuid.UUID) ([]OrgMembersExportRow, error)
// System scope.
OrgOwnerEmails(ctx context.Context, orgID uuid.UUID) ([]string, error)
// An organization serves its status pages itself once one of its own
// status page servers has connected.
OrgServesOwnPages(ctx context.Context, orgID *uuid.UUID) (bool, error)
@@ -321,6 +332,9 @@ type Querier interface {
RegionBuckets(ctx context.Context, arg RegionBucketsParams) ([]RegionBucketsRow, error)
RegionBucketsDaily(ctx context.Context, arg RegionBucketsDailyParams) ([]RegionBucketsDailyRow, error)
RegionBucketsHourly(ctx context.Context, arg RegionBucketsHourlyParams) ([]RegionBucketsHourlyRow, error)
// System scope: regions that have checkers and enabled monitors, so a
// region without a live checker leaves monitors unchecked.
RegionsToWatch(ctx context.Context) ([]RegionsToWatchRow, error)
RegroupMonitors(ctx context.Context, arg RegroupMonitorsParams) error
RemoveMembership(ctx context.Context, arg RemoveMembershipParams) (int64, error)
// Moves the subgroups of a group that is about to be deleted.
@@ -348,7 +362,7 @@ type Querier interface {
SetOwner(ctx context.Context, arg SetOwnerParams) (int64, error)
SetPasswordHash(ctx context.Context, arg SetPasswordHashParams) error
SetPlatformSetting(ctx context.Context, arg SetPlatformSettingParams) error
// Changing the domain drops a previous verification.
// Changing the domain drops a previous verification and its checks.
SetStatusPageDomain(ctx context.Context, arg SetStatusPageDomainParams) (StatusPage, error)
SetStatusPageMonitorGroup(ctx context.Context, arg SetStatusPageMonitorGroupParams) error
SetSupportTicketStatus(ctx context.Context, arg SetSupportTicketStatusParams) (int64, error)
@@ -386,6 +400,8 @@ type Querier interface {
TouchAgentInstance(ctx context.Context, arg TouchAgentInstanceParams) error
TouchIdentity(ctx context.Context, arg TouchIdentityParams) error
TouchPlatformIdentity(ctx context.Context, arg TouchPlatformIdentityParams) error
// A verified domain whose record stayed missing past the grace period.
UnverifyDomain(ctx context.Context, id uuid.UUID) error
UpdateAlertGroup(ctx context.Context, arg UpdateAlertGroupParams) (AlertGroup, error)
UpdateChannel(ctx context.Context, arg UpdateChannelParams) (NotificationChannel, error)
UpdateGroup(ctx context.Context, arg UpdateGroupParams) (MonitorGroup, error)
+16
View File
@@ -62,3 +62,19 @@ SELECT EXISTS (
SELECT 1 FROM agents
WHERE org_id = $1 AND kind = 'statuspage' AND last_seen_at IS NOT NULL
);
-- name: RegionsToWatch :many
-- System scope: regions that have checkers and enabled monitors, so a
-- region without a live checker leaves monitors unchecked.
SELECT r.id, r.name, r.org_id, o.name AS org_name
FROM regions r
LEFT JOIN orgs o ON o.id = r.org_id
WHERE EXISTS (SELECT 1 FROM agents a WHERE a.kind = 'checker' AND a.region_id = r.id)
AND EXISTS (SELECT 1 FROM monitor_regions mr JOIN monitors m ON m.id = mr.monitor_id
WHERE mr.region_id = r.id AND m.enabled)
ORDER BY r.name;
-- name: OrgOwnerEmails :many
-- System scope.
SELECT u.email FROM memberships m JOIN users u ON u.id = m.user_id
WHERE m.org_id = $1 AND m.is_owner AND u.disabled_at IS NULL;
+52 -4
View File
@@ -16,16 +16,63 @@ WHERE id = $1
RETURNING *;
-- name: SetStatusPageDomain :one
-- Changing the domain drops a previous verification.
-- Changing the domain drops a previous verification and its checks.
UPDATE status_pages SET
custom_domain = sqlc.narg(custom_domain),
domain_verified_at = CASE WHEN custom_domain IS NOT DISTINCT FROM sqlc.narg(custom_domain) THEN domain_verified_at END,
domain_verify_method = CASE WHEN custom_domain IS NOT DISTINCT FROM sqlc.narg(custom_domain) THEN domain_verify_method END,
domain_failing_since = CASE WHEN custom_domain IS NOT DISTINCT FROM sqlc.narg(custom_domain) THEN domain_failing_since END,
domain_checked_at = CASE WHEN custom_domain IS NOT DISTINCT FROM sqlc.narg(custom_domain) THEN domain_checked_at END,
domain_set_at = CASE WHEN custom_domain IS NOT DISTINCT FROM sqlc.narg(custom_domain) THEN domain_set_at ELSE now() END,
custom_domain = sqlc.narg(custom_domain),
updated_at = now()
WHERE id = sqlc.arg(id)
RETURNING *;
-- name: MarkDomainVerified :exec
UPDATE status_pages SET domain_verified_at = now() WHERE id = $1;
-- The domain's record was found: verified, or still in place.
UPDATE status_pages SET
domain_verified_at = coalesce(domain_verified_at, sqlc.arg(now)::timestamptz),
domain_verify_method = sqlc.arg(method)::text,
domain_checked_at = sqlc.arg(now)::timestamptz,
domain_failing_since = NULL
WHERE id = sqlc.arg(id);
-- name: MarkDomainUnconfirmed :one
-- The record of a domain was not found. Returns since when it has not
-- been, for a verified domain.
UPDATE status_pages SET
domain_checked_at = sqlc.arg(now)::timestamptz,
domain_failing_since = CASE WHEN domain_verified_at IS NULL THEN NULL
ELSE coalesce(domain_failing_since, sqlc.arg(now)::timestamptz) END
WHERE id = sqlc.arg(id)
RETURNING domain_failing_since;
-- name: UnverifyDomain :exec
-- A verified domain whose record stayed missing past the grace period.
UPDATE status_pages SET
domain_verified_at = NULL, domain_verify_method = NULL, domain_failing_since = NULL
WHERE id = $1;
-- name: DomainsToCheck :many
-- System scope: domains due for a look at their DNS records. A new one is
-- looked at every minute for a quarter of an hour, then every ten minutes
-- for two days, after which only the verify button tries again. A verified
-- one is checked daily, hourly once its record went missing.
SELECT id, org_id, title, custom_domain::text AS domain, domain_token,
domain_verified_at, domain_failing_since
FROM status_pages
WHERE custom_domain IS NOT NULL
AND (sqlc.narg(page_id)::uuid IS NULL OR id = sqlc.narg(page_id))
AND (
(domain_verified_at IS NULL AND domain_set_at > sqlc.arg(now)::timestamptz - interval '48 hours'
AND (domain_checked_at IS NULL OR domain_checked_at <= sqlc.arg(now)::timestamptz - CASE
WHEN domain_set_at > sqlc.arg(now)::timestamptz - interval '15 minutes' THEN interval '50 seconds'
ELSE interval '10 minutes' END))
OR (domain_verified_at IS NOT NULL AND domain_verify_method IS NOT NULL
AND (domain_checked_at IS NULL OR domain_checked_at <= sqlc.arg(now)::timestamptz - CASE
WHEN domain_failing_since IS NULL THEN interval '24 hours' ELSE interval '1 hour' END)))
ORDER BY domain_checked_at NULLS FIRST
LIMIT 500;
-- name: GetStatusPage :one
SELECT * FROM status_pages WHERE id = $1;
@@ -38,7 +85,8 @@ DELETE FROM status_pages WHERE id = $1;
-- name: StatusPageMonitors :many
SELECT spm.monitor_id, spm.section, spm.group_id, spm.label, spm.position,
m.name AS monitor_name, m.enabled, m.group_id AS monitor_group_id
m.name AS monitor_name, m.enabled, m.group_id AS monitor_group_id,
m.type AS monitor_type, m.interval_seconds
FROM status_page_monitors spm
JOIN monitors m ON m.id = spm.monitor_id
WHERE spm.page_id = $1
+167 -21
View File
@@ -7,6 +7,7 @@ package store
import (
"context"
"time"
"github.com/google/uuid"
)
@@ -60,7 +61,7 @@ func (q *Queries) ClearStatusPageMonitors(ctx context.Context, pageID uuid.UUID)
const createStatusPage = `-- name: CreateStatusPage :one
INSERT INTO status_pages (org_id, slug, title, description, published, show_component_details, domain_token, theme)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
RETURNING id, org_id, slug, title, description, published, custom_domain, domain_token, domain_verified_at, theme, created_at, updated_at, show_component_details, suspended_at, suspended_reason
RETURNING id, org_id, slug, title, description, published, custom_domain, domain_token, domain_verified_at, theme, created_at, updated_at, show_component_details, suspended_at, suspended_reason, domain_set_at, domain_checked_at, domain_failing_since, domain_verify_method
`
type CreateStatusPageParams struct {
@@ -102,6 +103,10 @@ func (q *Queries) CreateStatusPage(ctx context.Context, arg CreateStatusPagePara
&i.ShowComponentDetails,
&i.SuspendedAt,
&i.SuspendedReason,
&i.DomainSetAt,
&i.DomainCheckedAt,
&i.DomainFailingSince,
&i.DomainVerifyMethod,
)
return i, err
}
@@ -171,8 +176,73 @@ func (q *Queries) DeleteStatusPageGroup(ctx context.Context, arg DeleteStatusPag
return result.RowsAffected(), nil
}
const domainsToCheck = `-- name: DomainsToCheck :many
SELECT id, org_id, title, custom_domain::text AS domain, domain_token,
domain_verified_at, domain_failing_since
FROM status_pages
WHERE custom_domain IS NOT NULL
AND ($1::uuid IS NULL OR id = $1)
AND (
(domain_verified_at IS NULL AND domain_set_at > $2::timestamptz - interval '48 hours'
AND (domain_checked_at IS NULL OR domain_checked_at <= $2::timestamptz - CASE
WHEN domain_set_at > $2::timestamptz - interval '15 minutes' THEN interval '50 seconds'
ELSE interval '10 minutes' END))
OR (domain_verified_at IS NOT NULL AND domain_verify_method IS NOT NULL
AND (domain_checked_at IS NULL OR domain_checked_at <= $2::timestamptz - CASE
WHEN domain_failing_since IS NULL THEN interval '24 hours' ELSE interval '1 hour' END)))
ORDER BY domain_checked_at NULLS FIRST
LIMIT 500
`
type DomainsToCheckParams struct {
PageID *uuid.UUID
Now time.Time
}
type DomainsToCheckRow struct {
ID uuid.UUID
OrgID uuid.UUID
Title string
Domain string
DomainToken string
DomainVerifiedAt *time.Time
DomainFailingSince *time.Time
}
// System scope: domains due for a look at their DNS records. A new one is
// looked at every minute for a quarter of an hour, then every ten minutes
// for two days, after which only the verify button tries again. A verified
// one is checked daily, hourly once its record went missing.
func (q *Queries) DomainsToCheck(ctx context.Context, arg DomainsToCheckParams) ([]DomainsToCheckRow, error) {
rows, err := q.db.Query(ctx, domainsToCheck, arg.PageID, arg.Now)
if err != nil {
return nil, err
}
defer rows.Close()
items := []DomainsToCheckRow{}
for rows.Next() {
var i DomainsToCheckRow
if err := rows.Scan(
&i.ID,
&i.OrgID,
&i.Title,
&i.Domain,
&i.DomainToken,
&i.DomainVerifiedAt,
&i.DomainFailingSince,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const findPublishedPage = `-- name: FindPublishedPage :one
SELECT id, org_id, slug, title, description, published, custom_domain, domain_token, domain_verified_at, theme, created_at, updated_at, show_component_details, suspended_at, suspended_reason FROM status_pages
SELECT id, org_id, slug, title, description, published, custom_domain, domain_token, domain_verified_at, theme, created_at, updated_at, show_component_details, suspended_at, suspended_reason, domain_set_at, domain_checked_at, domain_failing_since, domain_verify_method FROM status_pages
WHERE published AND suspended_at IS NULL
AND NOT EXISTS (SELECT 1 FROM orgs o WHERE o.id = status_pages.org_id AND o.suspended_at IS NOT NULL)
AND (($1::citext IS NOT NULL AND custom_domain = $1 AND domain_verified_at IS NOT NULL)
@@ -205,12 +275,16 @@ func (q *Queries) FindPublishedPage(ctx context.Context, arg FindPublishedPagePa
&i.ShowComponentDetails,
&i.SuspendedAt,
&i.SuspendedReason,
&i.DomainSetAt,
&i.DomainCheckedAt,
&i.DomainFailingSince,
&i.DomainVerifyMethod,
)
return i, err
}
const getStatusPage = `-- name: GetStatusPage :one
SELECT id, org_id, slug, title, description, published, custom_domain, domain_token, domain_verified_at, theme, created_at, updated_at, show_component_details, suspended_at, suspended_reason FROM status_pages WHERE id = $1
SELECT id, org_id, slug, title, description, published, custom_domain, domain_token, domain_verified_at, theme, created_at, updated_at, show_component_details, suspended_at, suspended_reason, domain_set_at, domain_checked_at, domain_failing_since, domain_verify_method FROM status_pages WHERE id = $1
`
func (q *Queries) GetStatusPage(ctx context.Context, id uuid.UUID) (StatusPage, error) {
@@ -232,6 +306,10 @@ func (q *Queries) GetStatusPage(ctx context.Context, id uuid.UUID) (StatusPage,
&i.ShowComponentDetails,
&i.SuspendedAt,
&i.SuspendedReason,
&i.DomainSetAt,
&i.DomainCheckedAt,
&i.DomainFailingSince,
&i.DomainVerifyMethod,
)
return i, err
}
@@ -272,7 +350,7 @@ func (q *Queries) ListStatusPageGroups(ctx context.Context, pageID uuid.UUID) ([
}
const listStatusPages = `-- name: ListStatusPages :many
SELECT id, org_id, slug, title, description, published, custom_domain, domain_token, domain_verified_at, theme, created_at, updated_at, show_component_details, suspended_at, suspended_reason FROM status_pages ORDER BY title
SELECT id, org_id, slug, title, description, published, custom_domain, domain_token, domain_verified_at, theme, created_at, updated_at, show_component_details, suspended_at, suspended_reason, domain_set_at, domain_checked_at, domain_failing_since, domain_verify_method FROM status_pages ORDER BY title
`
func (q *Queries) ListStatusPages(ctx context.Context) ([]StatusPage, error) {
@@ -300,6 +378,10 @@ func (q *Queries) ListStatusPages(ctx context.Context) ([]StatusPage, error) {
&i.ShowComponentDetails,
&i.SuspendedAt,
&i.SuspendedReason,
&i.DomainSetAt,
&i.DomainCheckedAt,
&i.DomainFailingSince,
&i.DomainVerifyMethod,
); err != nil {
return nil, err
}
@@ -311,12 +393,47 @@ func (q *Queries) ListStatusPages(ctx context.Context) ([]StatusPage, error) {
return items, nil
}
const markDomainVerified = `-- name: MarkDomainVerified :exec
UPDATE status_pages SET domain_verified_at = now() WHERE id = $1
const markDomainUnconfirmed = `-- name: MarkDomainUnconfirmed :one
UPDATE status_pages SET
domain_checked_at = $1::timestamptz,
domain_failing_since = CASE WHEN domain_verified_at IS NULL THEN NULL
ELSE coalesce(domain_failing_since, $1::timestamptz) END
WHERE id = $2
RETURNING domain_failing_since
`
func (q *Queries) MarkDomainVerified(ctx context.Context, id uuid.UUID) error {
_, err := q.db.Exec(ctx, markDomainVerified, id)
type MarkDomainUnconfirmedParams struct {
Now time.Time
ID uuid.UUID
}
// The record of a domain was not found. Returns since when it has not
// been, for a verified domain.
func (q *Queries) MarkDomainUnconfirmed(ctx context.Context, arg MarkDomainUnconfirmedParams) (*time.Time, error) {
row := q.db.QueryRow(ctx, markDomainUnconfirmed, arg.Now, arg.ID)
var domain_failing_since *time.Time
err := row.Scan(&domain_failing_since)
return domain_failing_since, err
}
const markDomainVerified = `-- name: MarkDomainVerified :exec
UPDATE status_pages SET
domain_verified_at = coalesce(domain_verified_at, $1::timestamptz),
domain_verify_method = $2::text,
domain_checked_at = $1::timestamptz,
domain_failing_since = NULL
WHERE id = $3
`
type MarkDomainVerifiedParams struct {
Now time.Time
Method string
ID uuid.UUID
}
// The domain's record was found: verified, or still in place.
func (q *Queries) MarkDomainVerified(ctx context.Context, arg MarkDomainVerifiedParams) error {
_, err := q.db.Exec(ctx, markDomainVerified, arg.Now, arg.Method, arg.ID)
return err
}
@@ -394,11 +511,15 @@ func (q *Queries) ServablePages(ctx context.Context, agentOrg *uuid.UUID) ([]Ser
const setStatusPageDomain = `-- name: SetStatusPageDomain :one
UPDATE status_pages SET
custom_domain = $1,
domain_verified_at = CASE WHEN custom_domain IS NOT DISTINCT FROM $1 THEN domain_verified_at END,
domain_verify_method = CASE WHEN custom_domain IS NOT DISTINCT FROM $1 THEN domain_verify_method END,
domain_failing_since = CASE WHEN custom_domain IS NOT DISTINCT FROM $1 THEN domain_failing_since END,
domain_checked_at = CASE WHEN custom_domain IS NOT DISTINCT FROM $1 THEN domain_checked_at END,
domain_set_at = CASE WHEN custom_domain IS NOT DISTINCT FROM $1 THEN domain_set_at ELSE now() END,
custom_domain = $1,
updated_at = now()
WHERE id = $2
RETURNING id, org_id, slug, title, description, published, custom_domain, domain_token, domain_verified_at, theme, created_at, updated_at, show_component_details, suspended_at, suspended_reason
RETURNING id, org_id, slug, title, description, published, custom_domain, domain_token, domain_verified_at, theme, created_at, updated_at, show_component_details, suspended_at, suspended_reason, domain_set_at, domain_checked_at, domain_failing_since, domain_verify_method
`
type SetStatusPageDomainParams struct {
@@ -406,7 +527,7 @@ type SetStatusPageDomainParams struct {
ID uuid.UUID
}
// Changing the domain drops a previous verification.
// Changing the domain drops a previous verification and its checks.
func (q *Queries) SetStatusPageDomain(ctx context.Context, arg SetStatusPageDomainParams) (StatusPage, error) {
row := q.db.QueryRow(ctx, setStatusPageDomain, arg.CustomDomain, arg.ID)
var i StatusPage
@@ -426,6 +547,10 @@ func (q *Queries) SetStatusPageDomain(ctx context.Context, arg SetStatusPageDoma
&i.ShowComponentDetails,
&i.SuspendedAt,
&i.SuspendedReason,
&i.DomainSetAt,
&i.DomainCheckedAt,
&i.DomainFailingSince,
&i.DomainVerifyMethod,
)
return i, err
}
@@ -454,7 +579,8 @@ func (q *Queries) SetStatusPageMonitorGroup(ctx context.Context, arg SetStatusPa
const statusPageMonitors = `-- name: StatusPageMonitors :many
SELECT spm.monitor_id, spm.section, spm.group_id, spm.label, spm.position,
m.name AS monitor_name, m.enabled, m.group_id AS monitor_group_id
m.name AS monitor_name, m.enabled, m.group_id AS monitor_group_id,
m.type AS monitor_type, m.interval_seconds
FROM status_page_monitors spm
JOIN monitors m ON m.id = spm.monitor_id
WHERE spm.page_id = $1
@@ -462,14 +588,16 @@ ORDER BY spm.position, m.name
`
type StatusPageMonitorsRow struct {
MonitorID uuid.UUID
Section string
GroupID *uuid.UUID
Label string
Position int32
MonitorName string
Enabled bool
MonitorGroupID *uuid.UUID
MonitorID uuid.UUID
Section string
GroupID *uuid.UUID
Label string
Position int32
MonitorName string
Enabled bool
MonitorGroupID *uuid.UUID
MonitorType string
IntervalSeconds int32
}
func (q *Queries) StatusPageMonitors(ctx context.Context, pageID uuid.UUID) ([]StatusPageMonitorsRow, error) {
@@ -490,6 +618,8 @@ func (q *Queries) StatusPageMonitors(ctx context.Context, pageID uuid.UUID) ([]S
&i.MonitorName,
&i.Enabled,
&i.MonitorGroupID,
&i.MonitorType,
&i.IntervalSeconds,
); err != nil {
return nil, err
}
@@ -501,6 +631,18 @@ func (q *Queries) StatusPageMonitors(ctx context.Context, pageID uuid.UUID) ([]S
return items, nil
}
const unverifyDomain = `-- name: UnverifyDomain :exec
UPDATE status_pages SET
domain_verified_at = NULL, domain_verify_method = NULL, domain_failing_since = NULL
WHERE id = $1
`
// A verified domain whose record stayed missing past the grace period.
func (q *Queries) UnverifyDomain(ctx context.Context, id uuid.UUID) error {
_, err := q.db.Exec(ctx, unverifyDomain, id)
return err
}
const updateStatusPage = `-- name: UpdateStatusPage :one
UPDATE status_pages
SET slug = $2,
@@ -511,7 +653,7 @@ SET slug = $2,
theme = $7,
updated_at = now()
WHERE id = $1
RETURNING id, org_id, slug, title, description, published, custom_domain, domain_token, domain_verified_at, theme, created_at, updated_at, show_component_details, suspended_at, suspended_reason
RETURNING id, org_id, slug, title, description, published, custom_domain, domain_token, domain_verified_at, theme, created_at, updated_at, show_component_details, suspended_at, suspended_reason, domain_set_at, domain_checked_at, domain_failing_since, domain_verify_method
`
type UpdateStatusPageParams struct {
@@ -551,6 +693,10 @@ func (q *Queries) UpdateStatusPage(ctx context.Context, arg UpdateStatusPagePara
&i.ShowComponentDetails,
&i.SuspendedAt,
&i.SuspendedReason,
&i.DomainSetAt,
&i.DomainCheckedAt,
&i.DomainFailingSince,
&i.DomainVerifyMethod,
)
return i, err
}
+31 -2
View File
@@ -28,6 +28,9 @@ type MonitorRow struct {
Latency string
Uptime string
Bars []Bar
// Unchecked is set when no region has reported recently: nobody is
// checking the monitor.
Unchecked bool
}
// GroupNode is a monitor group with its monitors and subgroups.
@@ -64,6 +67,15 @@ type DashboardView struct {
Counts map[Status]int
Range string
Ranges []RangeOption
// Unchecked counts the monitors no region has reported for recently.
Unchecked int
// DeadRegions are regions of the monitors without a live checker.
DeadRegions []DeadRegion
}
// DeadRegion is a region without a live checker since Since.
type DeadRegion struct {
Name, Since string
}
// RangeOption is an entry of the range switcher. Disabled ranges are not
@@ -151,7 +163,7 @@ templ Dashboard(p Page, me Me, v DashboardView) {
<h1 class="text-lg font-semibold">{ i18n.T(ctx, "console.monitors.title") }</h1>
<div class="flex flex-wrap items-center gap-x-5 gap-y-3 font-mono text-xs text-muted">
@rangeSwitch(v.Ranges)
for _, s := range []Status{StatusUp, StatusDegraded, StatusDown, StatusMaintenance, StatusPaused} {
for _, s := range []Status{StatusUp, StatusDegraded, StatusDown, StatusUnknown, StatusMaintenance, StatusPaused} {
if v.Counts[s] > 0 {
<span class="flex items-center gap-1.5">
@statusDot(s)
@@ -164,6 +176,16 @@ templ Dashboard(p Page, me Me, v DashboardView) {
}
</div>
</div>
if v.Unchecked > 0 || len(v.DeadRegions) > 0 {
<div class="mb-6 border-l-2 border-unknown pl-3 text-sm" role="status">
for _, r := range v.DeadRegions {
<p>{ i18n.T(ctx, "monitors.dead_region", "Region", r.Name, "Since", r.Since) }</p>
}
if v.Unchecked > 0 {
<p>{ i18n.T(ctx, "monitors.unchecked_banner", "Count", v.Unchecked) }</p>
}
</div>
}
if !v.Empty {
<form method="get" action="/" class="mb-4 flex max-w-md gap-2">
if v.Range != "" {
@@ -229,7 +251,11 @@ templ monitorList(ms []MonitorRow) {
</span>
</span>
<span class="col-span-2 md:col-span-1">@bars(m.Bars, 18)</span>
<span class="hidden text-right font-mono text-xs text-muted md:block">{ m.Latency }</span>
if m.Unchecked {
<span class="hidden text-right font-mono text-xs text-unknown md:block">{ i18n.T(ctx, "monitors.unchecked") }</span>
} else {
<span class="hidden text-right font-mono text-xs text-muted md:block">{ m.Latency }</span>
}
<span class="col-start-2 row-start-1 text-right font-mono text-sm md:col-auto md:row-auto">{ m.Uptime }</span>
</a>
</li>
@@ -350,6 +376,9 @@ templ MonitorDetail(p Page, me Me, v MonitorDetailView) {
<a href={ templ.SafeURL("/monitors/" + v.Row.ID + "/edit") } class="border border-ink px-3 py-1.5 text-sm hover:bg-ink hover:text-paper">{ i18n.T(ctx, "sso.action.edit") }</a>
}
</div>
if v.Row.Unchecked {
<p class="mb-8 border-l-2 border-unknown pl-3 text-sm" role="status">{ i18n.T(ctx, "monitors.unchecked_banner", "Count", 1) }</p>
}
<section class="mb-10">
<div class="mb-3 flex flex-wrap items-center justify-between gap-x-4 gap-y-2">
<h2 class="text-xs font-medium uppercase tracking-wider text-muted">{ i18n.T(ctx, "monitors.history", "Range", v.Range) }</h2>
File diff suppressed because it is too large. Load diff
+63 -11
View File
@@ -106,6 +106,18 @@ type PageEditor struct {
URL string
Domain string
DomainVerified bool
// CNAMEValue is the target unique to the page that its domain points
// at; empty when the platform's status page host is not known.
CNAMEValue string
// VerifiedBy is "cname" or "txt", empty for domains verified before
// either was recorded.
VerifiedBy string
// MissingSince and SwitchOffAt are set while the record of a verified
// domain cannot be found.
MissingSince string
SwitchOffAt string
// DomainChangesPerDay is how often the domain may be changed a day.
DomainChangesPerDay int
RecordName string
RecordValue string
Suspended bool
@@ -290,26 +302,53 @@ templ StatusPageEditor(p Page, me Me, e PageEditor) {
</section>
<section>
@sectionHeading("pages.domain")
<p class="mb-4 text-sm text-muted">{ i18n.T(ctx, "pages.domain_intro") }</p>
<form data-api={ "/org/statuspages/" + e.ID + "/domain" } data-method="put" data-next={ "/statuspages/" + e.ID }>
@formError()
@valueField(i18n.T(ctx, "pages.domain_name"), "domain", e.Domain, "status.example.com", false)
@submit(i18n.T(ctx, "common.save"))
</form>
if e.Domain != "" {
<div class="mt-6 border border-rule p-4 text-sm">
<div class="mt-6 space-y-4 border border-rule p-4 text-sm">
if e.DomainVerified {
<p><span class="text-up">●</span> { i18n.T(ctx, "pages.domain_verified") }</p>
<p class="mt-2 text-xs text-muted">{ i18n.T(ctx, "pages.domain_cname") }</p>
<p>
<span class="text-up">●</span>
switch e.VerifiedBy {
case "cname":
{ i18n.T(ctx, "pages.domain_verified_by_cname") }
case "txt":
{ i18n.T(ctx, "pages.domain_verified_by_txt") }
default:
{ i18n.T(ctx, "pages.domain_step_verified") }
}
</p>
if e.MissingSince != "" {
<p class="border-l-2 border-down pl-3" role="alert">{ i18n.T(ctx, "pages.domain_missing", "Since", e.MissingSince, "Date", e.SwitchOffAt) }</p>
} else if e.VerifiedBy != "" {
<p class="text-xs text-muted">{ i18n.T(ctx, "pages.domain_keep") }</p>
}
} else if e.CNAMEValue != "" && !e.OwnServers {
<p>{ i18n.T(ctx, "pages.domain_cname_step") }</p>
@dnsRecordList("CNAME", e.Domain, e.CNAMEValue+".")
@verifyButton(e.ID, "pages.verify_now")
<details>
<summary class="cursor-pointer text-xs text-muted hover:text-ink">{ i18n.T(ctx, "pages.domain_alt_summary") }</summary>
<p class="mb-3 mt-3 text-xs">{ i18n.T(ctx, "pages.domain_alt", "Target", e.CNAMEValue) }</p>
@dnsRecordList("TXT", e.RecordName, e.RecordValue)
@verifyButton(e.ID, "pages.verify")
</details>
} else {
<p class="mb-3">{ i18n.T(ctx, "pages.domain_instructions") }</p>
<dl class="mb-4 grid grid-cols-[max-content_1fr] gap-x-4 gap-y-1 font-mono text-xs">
<dt class="text-muted">TXT</dt>
<dd class="break-all">{ e.RecordName }</dd>
<dt class="text-muted">{ i18n.T(ctx, "pages.value") }</dt>
<dd class="break-all">{ e.RecordValue }</dd>
</dl>
<button type="button" data-post={ "/org/statuspages/" + e.ID + "/domain/verify" } data-ok={ i18n.T(ctx, "pages.domain_verified") } data-reload class="border border-ink px-3 py-1.5 text-sm hover:bg-ink hover:text-paper">{ i18n.T(ctx, "pages.verify") }</button>
<p>{ i18n.T(ctx, "pages.domain_step_verify") }</p>
@dnsRecordList("TXT", e.RecordName, e.RecordValue)
@verifyButton(e.ID, "pages.verify")
if e.OwnServers {
<p>{ i18n.T(ctx, "pages.domain_step_cname_own") }</p>
} else {
<p>{ i18n.T(ctx, "pages.domain_step_cname_unknown") }</p>
}
<p class="text-xs text-muted">{ i18n.T(ctx, "pages.domain_apex") }</p>
}
<p class="text-xs text-muted">{ i18n.T(ctx, "pages.domain_step_tls", "Count", e.DomainChangesPerDay) }</p>
</div>
}
</section>
@@ -317,3 +356,16 @@ templ StatusPageEditor(p Page, me Me, e PageEditor) {
</div>
}
}
templ dnsRecordList(kind, name, value string) {
<dl class="grid grid-cols-[max-content_1fr] gap-x-4 gap-y-1 font-mono text-xs">
<dt class="text-muted">{ kind }</dt>
<dd class="break-all">{ name }</dd>
<dt class="text-muted">{ i18n.T(ctx, "pages.value") }</dt>
<dd class="break-all">{ value }</dd>
</dl>
}
templ verifyButton(pageID, label string) {
<button type="button" data-post={ "/org/statuspages/" + pageID + "/domain/verify" } data-ok={ i18n.T(ctx, "pages.domain_verified") } data-reload class="mt-3 border border-ink px-3 py-1.5 text-sm hover:bg-ink hover:text-paper">{ i18n.T(ctx, label) }</button>
}
File diff suppressed because it is too large. Load diff