Files
uptimesebi/internal/agentapi/agentapi.go
T
Sebastian UnterschützandClaude Opus 5.5 db36d918fe
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
feat: guard certificate orders for custom domains and explain the setup
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

218 lines
6.7 KiB
Go

// Package agentapi defines the protocol between the API and its agents,
// i.e. checkers and status page servers, and a client for it.
//
// Agents never touch Postgres or Redis. They authenticate with an agent
// token and exchange JSON with the API under /agent/v1, which keeps cloud,
// hybrid and self-hosted deployments on one code path.
package agentapi
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"strings"
"time"
"github.com/google/uuid"
)
// Version is the protocol version. The API accepts the current and the
// previous version so agents can be upgraded after the API.
const Version = 1
// Header names sent by agents.
const (
VersionHeader = "X-Agent-Protocol"
InstanceHeader = "X-Agent-Instance"
ReleaseHeader = "X-Agent-Release"
)
// Hello describes the agent the token belongs to.
type Hello struct {
AgentID uuid.UUID `json:"agent_id"`
Name string `json:"name"`
Kind string `json:"kind"`
// Region is the region key; RegionID identifies it uniquely.
Region string `json:"region,omitempty"`
RegionID *uuid.UUID `json:"region_id,omitempty"`
RegionName string `json:"region_name,omitempty"`
// OrgOwned is set for agents that serve a single organization.
OrgOwned bool `json:"org_owned"`
Protocol int `json:"protocol"`
}
// JobsRequest asks for up to Max jobs, waiting up to WaitMS if none are
// ready. Polling doubles as the instance's heartbeat; Max may be 0.
type JobsRequest struct {
Max int `json:"max"`
WaitMS int `json:"wait_ms"`
}
// Job is one check to run.
type Job struct {
MonitorID uuid.UUID `json:"monitor_id"`
ScheduledAt time.Time `json:"scheduled_at"`
Type string `json:"type"`
Target string `json:"target"`
TimeoutMS int `json:"timeout_ms"`
Config json.RawMessage `json:"config"`
// AllowPrivate permits targets on private networks.
AllowPrivate bool `json:"allow_private"`
}
// JobsResponse carries jobs for the polling instance.
type JobsResponse struct {
Jobs []Job `json:"jobs"`
}
// Result reports one finished check.
type Result struct {
MonitorID uuid.UUID `json:"monitor_id"`
ScheduledAt time.Time `json:"scheduled_at"`
StartedAt time.Time `json:"started_at"`
OK bool `json:"ok"`
LatencyMS int `json:"latency_ms"`
StatusCode int `json:"status_code,omitempty"`
Error string `json:"error,omitempty"`
// Evidence is what the check saw (check.Evidence), sent only now and
// then to bound traffic; see the checker's policy.
Evidence json.RawMessage `json:"evidence,omitempty"`
}
// ResultsRequest reports finished checks in a batch.
type ResultsRequest struct {
Results []Result `json:"results"`
}
// MaxResults bounds a results batch.
const MaxResults = 500
// ErrUnauthorized means the agent token was rejected.
var ErrUnauthorized = errors.New("agentapi: token rejected")
// Client talks to the agent API on behalf of one agent instance.
type Client struct {
base string
token string
instance uuid.UUID
release string
hc *http.Client
}
// NewClient returns a client for the API at base. instance identifies this
// process among several running with the same token.
func NewClient(base, token string, instance uuid.UUID, release string) *Client {
return &Client{
base: strings.TrimSuffix(base, "/"),
token: token,
instance: instance,
release: release,
hc: &http.Client{Timeout: 60 * time.Second},
}
}
// WithHTTPClient replaces the HTTP client, e.g. to trust a private CA.
func (c *Client) WithHTTPClient(hc *http.Client) *Client {
c.hc = hc
return c
}
// Instance returns the instance ID sent with every request.
func (c *Client) Instance() uuid.UUID { return c.instance }
func (c *Client) do(ctx context.Context, method, path string, in, out any) error {
return c.doWith(ctx, method, path, nil, in, out)
}
// doWith is do with extra request headers.
func (c *Client) doWith(ctx context.Context, method, path string, header http.Header, in, out any) error {
var body io.Reader
if in != nil {
b, err := json.Marshal(in)
if err != nil {
return err
}
body = bytes.NewReader(b)
}
req, err := http.NewRequestWithContext(ctx, method, c.base+"/agent/v1"+path, body)
if err != nil {
return err
}
req.Header.Set("Authorization", "Bearer "+c.token)
req.Header.Set("Content-Type", "application/json")
req.Header.Set(VersionHeader, fmt.Sprint(Version))
req.Header.Set(InstanceHeader, c.instance.String())
req.Header.Set(ReleaseHeader, c.release)
for k, v := range header {
req.Header[k] = v
}
resp, err := c.hc.Do(req)
if err != nil {
return err
}
defer func() { _ = resp.Body.Close() }()
switch {
case resp.StatusCode == http.StatusUnauthorized:
return ErrUnauthorized
case resp.StatusCode == http.StatusNotFound:
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))
case out == nil:
return nil
}
return json.NewDecoder(resp.Body).Decode(out)
}
// Hello identifies the agent and checks connectivity.
func (c *Client) Hello(ctx context.Context) (Hello, error) {
var h Hello
err := c.do(ctx, http.MethodGet, "/hello", nil, &h)
return h, err
}
// Jobs long-polls for jobs.
func (c *Client) Jobs(ctx context.Context, max int, wait time.Duration) ([]Job, error) {
var resp JobsResponse
err := c.do(ctx, http.MethodPost, "/jobs", JobsRequest{Max: max, WaitMS: int(wait.Milliseconds())}, &resp)
return resp.Jobs, err
}
// Report sends finished checks.
func (c *Client) Report(ctx context.Context, results []Result) error {
return c.do(ctx, http.MethodPost, "/results", ResultsRequest{Results: results}, nil)
}
// Update tells a self-updating agent which release to run.
type Update struct {
// Version is the platform's release; agents follow it.
Version string `json:"version"`
// Image is the agent image of that release, e.g.
// git.example.com/owner/uptimesebi-checker:1.4.2. Empty when the
// platform runs an unreleased build, which agents do not follow.
Image string `json:"image,omitempty"`
}
// Update asks which release the agent should run. It does not count as a
// sign of life of an instance.
func (c *Client) Update(ctx context.Context) (Update, error) {
var u Update
err := c.do(ctx, http.MethodGet, "/update", nil, &u)
return u, err
}
// Release hands this instance's queued jobs back for other instances and
// deregisters it. Call it during graceful shutdown.
func (c *Client) Release(ctx context.Context) error {
return c.do(ctx, http.MethodPost, "/release", nil, nil)
}