// 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 { 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) 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 >= 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) } // 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) }