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) 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.Agent 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.Agent { return c.MustGet(ctxAgent).(store.Agent) } func instanceOf(c *gin.Context) uuid.UUID { return c.MustGet(ctxInstance).(uuid.UUID) } func regionOf(c *gin.Context) string { return deref(agentOf(c).Region) } func (s *Server) cloud() bool { return s.cfg.Edition == config.EditionCloud } func (s *Server) allowPrivate(a store.Agent) 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.Region), 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.Agent, 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{Region: deref(a.Region), Ids: ids}) 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() err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error { monitors, err := q.MonitorsForJobs(ctx, store.MonitorsForJobsParams{Region: region, Ids: ids}) if err != nil { return err } orgOf := make(map[uuid.UUID]uuid.UUID, len(monitors)) for _, m := range monitors { orgOf[m.ID] = m.OrgID } rows := make([]store.InsertCheckResultsParams, 0, len(req.Results)) for _, r := range req.Results { org, ok := orgOf[r.MonitorID] // 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)) } rows = append(rows, row) } if len(rows) == 0 { return nil } _, err = q.InsertCheckResults(ctx, rows) return err }) if err != nil { internalError(c, err) return } 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] }