Files
uptimesebi/internal/api/agent.go
T
Sebastian UnterschützandClaude Opus 5.5 a6126b353e feat(api): manage status pages with themes, custom domains and export
Organizations build pages from their monitors, grouped into sections
with public names, choose an accent color, logo and CSS, verify custom
domains with a TXT record and export a page as one self-contained HTML
file. Assignments scoped to a single status page are honored.

Closes #21
Closes #23
Closes #24

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

268 lines
7.7 KiB
Go

package api
import (
"context"
"errors"
"net/http"
"strconv"
"time"
"unicode/utf8"
"github.com/gin-gonic/gin"
"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/schedule"
"git.zb-server.de/ZB-Server/uptimesebi/internal/store"
"git.zb-server.de/ZB-Server/uptimesebi/internal/tenant"
)
// AgentTokenPrefix marks agent tokens, distinct from user API tokens.
const AgentTokenPrefix = "usa_"
const (
ctxAgent = "api.agent"
ctxInstance = "api.instance"
maxJobWait = 25 * time.Second
maxJobBatch = 200
)
func (s *Server) mountAgentAPI(r gin.IRouter) {
g := r.Group("/agent/v1", s.agentAuth())
g.GET("/hello", s.agentHello)
g.GET("/pages", requireAgentKind("statuspage"), s.agentPage)
checker := g.Group("", requireAgentKind("checker"))
checker.POST("/jobs", s.agentJobs)
checker.POST("/results", s.agentResults)
checker.POST("/release", s.agentRelease)
}
// agentAuth authenticates the agent token and the protocol version and
// requires an instance ID, which distinguishes processes sharing a token.
func (s *Server) agentAuth() gin.HandlerFunc {
return func(c *gin.Context) {
v, err := strconv.Atoi(c.GetHeader(agentapi.VersionHeader))
if err != nil || v < agentapi.Version-1 || v > agentapi.Version {
fail(c, http.StatusUpgradeRequired, "agent_protocol_unsupported")
return
}
instance, err := uuid.Parse(c.GetHeader(agentapi.InstanceHeader))
if err != nil {
fail(c, http.StatusBadRequest, "invalid_input")
return
}
tok := bearerToken(c)
if len(tok) <= len(AgentTokenPrefix) || tok[:len(AgentTokenPrefix)] != AgentTokenPrefix {
fail(c, http.StatusUnauthorized, "unauthenticated")
return
}
ctx := c.Request.Context()
var a store.GetAgentByHashRow
release := truncate(c.GetHeader(agentapi.ReleaseHeader), 64)
err = s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
var err error
if a, err = q.GetAgentByHash(ctx, HashToken(tok)); err != nil {
return err
}
return q.TouchAgent(ctx, store.TouchAgentParams{ID: a.ID, Release: &release})
})
if errors.Is(err, pgx.ErrNoRows) {
fail(c, http.StatusUnauthorized, "unauthenticated")
return
}
if err != nil {
internalError(c, err)
return
}
c.Set(ctxAgent, a)
c.Set(ctxInstance, instance)
c.Next()
}
}
func requireAgentKind(kind string) gin.HandlerFunc {
return func(c *gin.Context) {
if agentOf(c).Kind != kind {
fail(c, http.StatusForbidden, "forbidden")
return
}
c.Next()
}
}
func agentOf(c *gin.Context) store.GetAgentByHashRow {
return c.MustGet(ctxAgent).(store.GetAgentByHashRow)
}
func instanceOf(c *gin.Context) uuid.UUID { return c.MustGet(ctxInstance).(uuid.UUID) }
// regionOf returns the agent's region ID in the string form used for the
// schedule and check results.
func regionOf(c *gin.Context) string {
if id := agentOf(c).RegionID; id != nil {
return id.String()
}
return ""
}
func (s *Server) cloud() bool { return s.cfg.Edition == config.EditionCloud }
func (s *Server) allowPrivate(a store.GetAgentByHashRow) bool {
// Operator checkers in the cloud share our network; customers must not
// reach it through them. Customer-run checkers and self-hosted
// installations check whatever their operator can reach.
return !s.cloud() || a.OrgID != nil
}
func (s *Server) agentHello(c *gin.Context) {
a := agentOf(c)
c.JSON(http.StatusOK, agentapi.Hello{
AgentID: a.ID, Name: a.Name, Kind: a.Kind, Region: deref(a.RegionKey), RegionID: a.RegionID,
RegionName: deref(a.RegionName), OrgOwned: a.OrgID != nil, Protocol: agentapi.Version,
})
}
func (s *Server) agentJobs(c *gin.Context) {
var req agentapi.JobsRequest
if !bind(c, &req) {
return
}
ctx := c.Request.Context()
region, instance := regionOf(c), instanceOf(c)
if err := s.sched.Heartbeat(ctx, region, instance); err != nil {
internalError(c, err)
return
}
wait := min(time.Duration(req.WaitMS)*time.Millisecond, maxJobWait)
entries, err := s.sched.Take(ctx, instance, min(req.Max, maxJobBatch), wait)
if err != nil && ctx.Err() == nil {
internalError(c, err)
return
}
jobs, err := s.resolveJobs(ctx, agentOf(c), entries)
if err != nil {
internalError(c, err)
return
}
c.JSON(http.StatusOK, agentapi.JobsResponse{Jobs: jobs})
}
// resolveJobs attaches the current monitor settings to dispatched runs.
// Checking is cross-tenant work, hence the system scope.
func (s *Server) resolveJobs(ctx context.Context, a store.GetAgentByHashRow, entries []schedule.Entry) ([]agentapi.Job, error) {
jobs := []agentapi.Job{}
if len(entries) == 0 {
return jobs, nil
}
ids := make([]uuid.UUID, len(entries))
for i, e := range entries {
ids[i] = e.MonitorID
}
var rows []store.Monitor
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
var err error
rows, err = q.MonitorsForJobs(ctx, store.MonitorsForJobsParams{RegionID: deref(a.RegionID), Ids: ids, AgentOrg: a.OrgID})
return err
})
if err != nil {
return nil, err
}
byID := make(map[uuid.UUID]store.Monitor, len(rows))
for _, m := range rows {
byID[m.ID] = m
}
for _, e := range entries {
m, ok := byID[e.MonitorID]
if !ok {
continue
}
jobs = append(jobs, agentapi.Job{
MonitorID: m.ID, ScheduledAt: e.ScheduledAt, Type: m.Type, Target: m.Target,
TimeoutMS: int(m.TimeoutMs), Config: m.Config, AllowPrivate: s.allowPrivate(a),
})
}
return jobs, nil
}
func (s *Server) agentResults(c *gin.Context) {
var req agentapi.ResultsRequest
if !bind(c, &req) {
return
}
if len(req.Results) > agentapi.MaxResults {
fail(c, http.StatusRequestEntityTooLarge, "invalid_input")
return
}
ctx := c.Request.Context()
region, instance := regionOf(c), instanceOf(c)
ids := make([]uuid.UUID, len(req.Results))
for i, r := range req.Results {
ids[i] = r.MonitorID
}
now := time.Now()
monitors := map[uuid.UUID]store.MonitorsForResultsRow{}
var accepted []agentapi.Result
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
a := agentOf(c)
rows, err := q.MonitorsForResults(ctx, store.MonitorsForResultsParams{RegionID: deref(a.RegionID), Ids: ids, AgentOrg: a.OrgID})
if err != nil {
return err
}
for _, m := range rows {
monitors[m.ID] = m
}
params := make([]store.InsertCheckResultsParams, 0, len(req.Results))
for _, r := range req.Results {
m, ok := monitors[r.MonitorID]
org := m.OrgID
// A checker may only report monitors of its own region, and
// timestamps far from now are rejected rather than skewing
// history.
if !ok || r.StartedAt.After(now.Add(time.Minute)) || r.StartedAt.Before(now.Add(-24*time.Hour)) {
continue
}
row := store.InsertCheckResultsParams{
Time: r.StartedAt, OrgID: org, MonitorID: r.MonitorID, Region: region,
CheckerID: instance, Ok: r.OK, LatencyMs: ptr(int32(max(r.LatencyMS, 0))),
}
if r.StatusCode > 0 {
row.StatusCode = ptr(int32(r.StatusCode))
}
if r.Error != "" {
row.Error = ptr(truncateValid(r.Error, 500))
}
params = append(params, row)
accepted = append(accepted, r)
}
if len(params) == 0 {
return nil
}
_, err = q.InsertCheckResults(ctx, params)
return err
})
if err != nil {
internalError(c, err)
return
}
s.evaluateResults(ctx, region, accepted, monitors)
c.Status(http.StatusNoContent)
}
func (s *Server) agentRelease(c *gin.Context) {
if err := s.sched.Release(c.Request.Context(), regionOf(c), instanceOf(c)); err != nil {
internalError(c, err)
return
}
c.Status(http.StatusNoContent)
}
// truncateValid shortens s to n bytes without splitting a UTF-8 sequence.
func truncateValid(s string, n int) string {
if len(s) <= n {
return s
}
for n > 0 && !utf8.RuneStart(s[n]) {
n--
}
return s[:n]
}