diff --git a/.env.example b/.env.example index b1b024e..4721dac 100644 --- a/.env.example +++ b/.env.example @@ -1,6 +1,5 @@ UPTIME_DATABASE_URL=postgres://uptime:uptime@localhost:5432/uptime?sslmode=disable UPTIME_REDIS_URL=redis://localhost:6379/0 -UPTIME_CHECKER_REGION=local # Sentinel instead of a single redis (docker compose --profile sentinel up -d) # UPTIME_REDIS_SENTINEL_MASTER=uptime @@ -13,3 +12,13 @@ UPTIME_PUBLIC_URL=http://localhost:8080 # Lets organizations use IdPs on private networks (e.g. an internal Keycloak). # auto = allowed for UPTIME_EDITION=selfhosted, denied for cloud. UPTIME_SSO_ALLOW_PRIVATE_NETWORKS=auto + +# Checker and status page reach the API only. Create tokens with: +# api agent create --kind checker --region local --name dev +# api agent create --kind statuspage --name dev +# and set UPTIME_AGENT_TOKEN for each process. +UPTIME_API_URL=http://localhost:8080 + +# Integration tests (make test). The Redis database is flushed by the tests. +UPTIME_TEST_DATABASE_URL=postgres://uptime:uptime@localhost:5432/uptime_test?sslmode=disable +UPTIME_TEST_REDIS_URL=redis://localhost:6379/15 diff --git a/.gitignore b/.gitignore index 70854bc..ccb24ab 100644 --- a/.gitignore +++ b/.gitignore @@ -5,3 +5,6 @@ *_templ.txt .env .idea/ +/api +/checker +/statuspage diff --git a/Makefile b/Makefile index 128135b..9a9d618 100644 --- a/Makefile +++ b/Makefile @@ -16,7 +16,8 @@ build: generate web CGO_ENABLED=0 go build -trimpath -ldflags "$(LDFLAGS)" -o bin/ ./cmd/... test: - go test ./... + # Integration tests share one Postgres and Redis database, so packages run one at a time. + go test -p 1 ./... lint: golangci-lint run diff --git a/cmd/api/admin.go b/cmd/api/admin.go new file mode 100644 index 0000000..3b8fc33 --- /dev/null +++ b/cmd/api/admin.go @@ -0,0 +1,129 @@ +package main + +import ( + "context" + "errors" + "flag" + "fmt" + "os" + "text/tabwriter" + "time" + + "github.com/google/uuid" + + "git.zb-server.de/ZB-Server/uptimesebi/internal/api" + "git.zb-server.de/ZB-Server/uptimesebi/internal/auth" + "git.zb-server.de/ZB-Server/uptimesebi/internal/config" + "git.zb-server.de/ZB-Server/uptimesebi/internal/platform" + "git.zb-server.de/ZB-Server/uptimesebi/internal/store" + "git.zb-server.de/ZB-Server/uptimesebi/internal/tenant" +) + +const usage = `usage: + api [serve] + api migrate up|down|status + api region add [name] + api agent create --kind checker|statuspage [--region ] --name + api agent list + api agent revoke ` + +// admin runs operator commands. They act across all organizations, hence the +// system scope, and print to stdout for humans and scripts. +func admin(ctx context.Context, cfg config.API, args []string) error { + if err := cfg.Storage.Validate(); err != nil { + return err + } + pool, err := platform.OpenPostgres(ctx, cfg.DatabaseURL) + if err != nil { + return err + } + defer pool.Close() + db := tenant.New(pool) + + switch { + case len(args) >= 3 && args[0] == "region" && args[1] == "add": + name := args[2] + if len(args) > 3 { + name = args[3] + } + return db.Tx(ctx, tenant.System(), func(q *store.Queries) error { + r, err := q.UpsertRegion(ctx, store.UpsertRegionParams{Key: args[2], Name: name}) + if err == nil { + fmt.Printf("region %s (%s)\n", r.Key, r.Name) + } + return err + }) + case len(args) >= 2 && args[0] == "agent" && args[1] == "create": + return createAgent(ctx, db, args[2:]) + case len(args) == 2 && args[0] == "agent" && args[1] == "list": + return db.Tx(ctx, tenant.System(), func(q *store.Queries) error { + agents, err := q.ListAgents(ctx) + if err != nil { + return err + } + w := tabwriter.NewWriter(os.Stdout, 0, 4, 2, ' ', 0) + _, _ = fmt.Fprintln(w, "ID\tKIND\tREGION\tNAME\tTOKEN\tLAST SEEN\tRELEASE") + for _, a := range agents { + seen := "never" + if a.LastSeenAt != nil { + seen = a.LastSeenAt.Format(time.DateTime) + } + _, _ = fmt.Fprintf(w, "%s\t%s\t%s\t%s\t%s…\t%s\t%s\n", a.ID, a.Kind, deref(a.Region), a.Name, a.Prefix, seen, deref(a.Release)) + } + return w.Flush() + }) + case len(args) == 3 && args[0] == "agent" && args[1] == "revoke": + id, err := uuid.Parse(args[2]) + if err != nil { + return err + } + return db.Tx(ctx, tenant.System(), func(q *store.Queries) error { + n, err := q.DeleteAgent(ctx, id) + if err == nil && n == 0 { + err = errors.New("agent not found") + } + return err + }) + } + return errors.New(usage) +} + +func createAgent(ctx context.Context, db *tenant.DB, args []string) error { + fs := flag.NewFlagSet("agent create", flag.ContinueOnError) + kind := fs.String("kind", "checker", "checker or statuspage") + region := fs.String("region", "", "region key, required for checkers; created if missing") + name := fs.String("name", "", "display name") + if err := fs.Parse(args); err != nil { + return err + } + if *name == "" || (*kind == "checker") != (*region != "") { + return errors.New(usage) + } + tok := api.AgentTokenPrefix + auth.RandomToken() + params := store.CreateAgentParams{Kind: *kind, Name: *name, TokenHash: api.HashToken(tok), Prefix: tok[:len(api.AgentTokenPrefix)+6]} + if *region != "" { + params.Region = region + } + err := db.Tx(ctx, tenant.System(), func(q *store.Queries) error { + if *region != "" { + if _, err := q.UpsertRegion(ctx, store.UpsertRegionParams{Key: *region, Name: ""}); err != nil { + return err + } + } + _, err := q.CreateAgent(ctx, params) + return err + }) + if err != nil { + return err + } + fmt.Println(tok) + return nil +} + +func deref[T any](p *T) T { + var zero T + if p == nil { + return zero + } + return *p +} diff --git a/cmd/api/main.go b/cmd/api/main.go index a7e7ac4..f3b33a1 100644 --- a/cmd/api/main.go +++ b/cmd/api/main.go @@ -38,11 +38,16 @@ func run(log *slog.Logger, level *slog.LevelVar, args []string) error { ctx, stop := platform.SignalContext() defer stop() - if len(args) > 0 && args[0] == "migrate" { - return migrate(ctx, log, cfg.DatabaseURL, args[1:]) - } - if len(args) > 0 && args[0] != "serve" { - return errors.New("usage: api [serve | migrate up|down|status]") + if len(args) > 0 { + switch args[0] { + case "migrate": + return migrate(ctx, log, cfg.DatabaseURL, args[1:]) + case "agent", "region": + return admin(ctx, cfg, args) + case "serve": + default: + return errors.New(usage) + } } if err := cfg.Validate(); err != nil { @@ -52,7 +57,7 @@ func run(log *slog.Logger, level *slog.LevelVar, args []string) error { if err != nil { return err } - deps, err := platform.Connect(ctx, cfg.Common, log) + deps, err := platform.Connect(ctx, cfg.Storage, log) if err != nil { return err } @@ -68,6 +73,7 @@ func run(log *slog.Logger, level *slog.LevelVar, args []string) error { health.Register(r) r.StaticFS("/static", web.Static()) srv.Mount(r) + go srv.RunScheduler(ctx) return platform.Serve(ctx, log, platform.NewHTTPServer(cfg.Listen, r), health, 5*time.Second, cfg.ShutdownTimeout) } diff --git a/cmd/checker/main.go b/cmd/checker/main.go index b813983..7c6959b 100644 --- a/cmd/checker/main.go +++ b/cmd/checker/main.go @@ -1,11 +1,20 @@ -// Command checker executes uptime checks for one region and pulls data from -// external sources. Any number of instances per region may run. +// Command checker executes uptime checks for one region. It talks only to +// the API, never to the database or Redis, so it can run anywhere the API is +// reachable, including customer networks. Any number of instances may share +// a region and token; each check goes to a randomly chosen live instance. package main import ( + "errors" + "fmt" "log/slog" "os" + "github.com/google/uuid" + + "git.zb-server.de/ZB-Server/uptimesebi/internal/agentapi" + "git.zb-server.de/ZB-Server/uptimesebi/internal/buildinfo" + "git.zb-server.de/ZB-Server/uptimesebi/internal/checker" "git.zb-server.de/ZB-Server/uptimesebi/internal/config" "git.zb-server.de/ZB-Server/uptimesebi/internal/platform" ) @@ -26,19 +35,36 @@ func run(log *slog.Logger, level *slog.LevelVar) error { return err } level.Set(cfg.LogLevel) + if err := cfg.Common.Validate(); err != nil { + return err + } ctx, stop := platform.SignalContext() defer stop() - log = log.With("region", cfg.Region) - deps, err := platform.Connect(ctx, cfg.Common, log) + instance := uuid.New() + client := agentapi.NewClient(cfg.APIURL, cfg.Token, instance, buildinfo.Version) + hello, err := platform.Hello(ctx, client, log) if err != nil { return err } - defer deps.Close() + if hello.Kind != "checker" { + return fmt.Errorf("token belongs to a %s agent, not a checker", hello.Kind) + } + log = log.With("region", hello.Region, "agent", hello.Name, "instance", instance) + log.Info("connected to api") - health := platform.NewHealth(deps.Probes()) + runner := checker.New(client, cfg.Concurrency, log) + health := platform.NewHealth(map[string]platform.Probe{"api": runner.Healthy}) r := platform.NewRouter(log) health.Register(r) - return platform.Serve(ctx, log, platform.NewHTTPServer(cfg.HealthListen, r), health, 0, cfg.ShutdownTimeout) + serveErr := make(chan error, 1) + go func() { + serveErr <- platform.Serve(ctx, log, platform.NewHTTPServer(cfg.HealthListen, r), health, 0, cfg.ShutdownTimeout) + }() + runErr := runner.Run(ctx, cfg.ShutdownTimeout) + if errors.Is(runErr, agentapi.ErrUnauthorized) { + stop() + } + return errors.Join(runErr, <-serveErr) } diff --git a/cmd/statuspage/main.go b/cmd/statuspage/main.go index c827959..7c74a50 100644 --- a/cmd/statuspage/main.go +++ b/cmd/statuspage/main.go @@ -1,12 +1,18 @@ // Command statuspage serves public status pages, including on customer -// domains. +// domains. Like the checker it reads data only through the API. package main import ( + "context" + "fmt" "log/slog" "os" "time" + "github.com/google/uuid" + + "git.zb-server.de/ZB-Server/uptimesebi/internal/agentapi" + "git.zb-server.de/ZB-Server/uptimesebi/internal/buildinfo" "git.zb-server.de/ZB-Server/uptimesebi/internal/config" "git.zb-server.de/ZB-Server/uptimesebi/internal/platform" "git.zb-server.de/ZB-Server/uptimesebi/internal/web" @@ -28,16 +34,24 @@ func run(log *slog.Logger, level *slog.LevelVar) error { return err } level.Set(cfg.LogLevel) + if err := cfg.Common.Validate(); err != nil { + return err + } ctx, stop := platform.SignalContext() defer stop() - deps, err := platform.Connect(ctx, cfg.Common, log) + client := agentapi.NewClient(cfg.APIURL, cfg.Token, uuid.New(), buildinfo.Version) + hello, err := platform.Hello(ctx, client, log) if err != nil { return err } - defer deps.Close() + if hello.Kind != "statuspage" { + return fmt.Errorf("token belongs to a %s agent, not a status page server", hello.Kind) + } - health := platform.NewHealth(deps.Probes()) + health := platform.NewHealth(map[string]platform.Probe{ + "api": func(ctx context.Context) error { _, err := client.Hello(ctx); return err }, + }) r := platform.NewRouter(log) health.Register(r) r.StaticFS("/static", web.Static()) diff --git a/deploy/dev/postgres-init.sql b/deploy/dev/postgres-init.sql index 5060fe0..56ebdb6 100644 --- a/deploy/dev/postgres-init.sql +++ b/deploy/dev/postgres-init.sql @@ -5,3 +5,9 @@ CREATE DATABASE uptime OWNER uptime; \connect uptime CREATE EXTENSION IF NOT EXISTS timescaledb; CREATE EXTENSION IF NOT EXISTS citext; + +-- Integration tests run against their own database (UPTIME_TEST_DATABASE_URL). +CREATE DATABASE uptime_test OWNER uptime; +\connect uptime_test +CREATE EXTENSION IF NOT EXISTS timescaledb; +CREATE EXTENSION IF NOT EXISTS citext; diff --git a/go.mod b/go.mod index 7c78cd5..c932653 100644 --- a/go.mod +++ b/go.mod @@ -62,7 +62,7 @@ require ( go.uber.org/multierr v1.11.0 // indirect golang.org/x/arch v0.22.0 // indirect golang.org/x/mod v0.43.0 // indirect - golang.org/x/net v0.62.0 // indirect + golang.org/x/net v0.63.0 // indirect golang.org/x/sync v0.25.0 // indirect golang.org/x/sys v0.50.0 // indirect golang.org/x/tools v0.52.0 // indirect diff --git a/go.sum b/go.sum index ea1bd41..21e3652 100644 --- a/go.sum +++ b/go.sum @@ -150,6 +150,8 @@ golang.org/x/mod v0.43.0 h1:MFuq5J6s35W9D3IjkwyWc9vHh0nENOrt5K8Iof4ofmg= golang.org/x/mod v0.43.0/go.mod h1:4ec1JnuyBz5+FIVhg86UsA39YG8BpnrZdJYSNHmGzHY= golang.org/x/net v0.62.0 h1:18ELalfM5+XNRwzM2nYqXsZQ9ByS1uhj2O/U7+5jqRY= golang.org/x/net v0.62.0/go.mod h1:WgDCOTH8iwtB66T4/GfI94AHo/hhdb7Hah9NDseQfiI= +golang.org/x/net v0.63.0 h1:HCoTmNh9EpD1PpK8gBNFY4gcTY4N+KQEO8ylfIKqFJ0= +golang.org/x/net v0.63.0/go.mod h1:15JLg3IX1bLjHK264EZQEbIpTiR/KVLuo9CTRWd0pig= golang.org/x/oauth2 v0.38.0 h1:uW7XQbcu1eoiQS7uMJvLOjPMl04bTbmY1VeRPxvbspI= golang.org/x/oauth2 v0.38.0/go.mod h1:IxwZNxUULJmpBFf9K/9NTMSIfZZuvuTy1gGxhigP/58= golang.org/x/sync v0.25.0 h1:dJnifr0nMV8/SBnBvdo4eSGGnrc3O4FFx6IqvtLcmRs= diff --git a/internal/agentapi/agentapi.go b/internal/agentapi/agentapi.go new file mode 100644 index 0000000..dec6c3e --- /dev/null +++ b/internal/agentapi/agentapi.go @@ -0,0 +1,177 @@ +// 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 string `json:"region,omitempty"` + 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"` +} + +// 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 >= 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) +} diff --git a/internal/api/agent.go b/internal/api/agent.go new file mode 100644 index 0000000..15ca8a1 --- /dev/null +++ b/internal/api/agent.go @@ -0,0 +1,250 @@ +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] +} diff --git a/internal/api/checker_test.go b/internal/api/checker_test.go new file mode 100644 index 0000000..f9ab00e --- /dev/null +++ b/internal/api/checker_test.go @@ -0,0 +1,205 @@ +package api_test + +import ( + "context" + "errors" + "log/slog" + "net/http" + "net/http/httptest" + "testing" + "time" + + "github.com/google/uuid" + + "git.zb-server.de/ZB-Server/uptimesebi/internal/agentapi" + "git.zb-server.de/ZB-Server/uptimesebi/internal/api" + "git.zb-server.de/ZB-Server/uptimesebi/internal/auth" + "git.zb-server.de/ZB-Server/uptimesebi/internal/checker" + "git.zb-server.de/ZB-Server/uptimesebi/internal/store" + "git.zb-server.de/ZB-Server/uptimesebi/internal/tenant" +) + +// agentToken creates a checker agent for region directly in the database, +// as "api agent create" would. +func (e *env) agentToken(t *testing.T, region string) string { + t.Helper() + tok := api.AgentTokenPrefix + auth.RandomToken() + ctx := context.Background() + err := tenant.New(e.dbPool).Tx(ctx, tenant.System(), func(q *store.Queries) error { + if _, err := q.UpsertRegion(ctx, store.UpsertRegionParams{Key: region}); err != nil { + return err + } + _, err := q.CreateAgent(ctx, store.CreateAgentParams{ + Kind: "checker", Name: "test-" + region, Region: ®ion, TokenHash: api.HashToken(tok), Prefix: tok[:10], + }) + return err + }) + if err != nil { + t.Fatalf("creating agent: %v", err) + } + return tok +} + +// startChecker runs a checker instance until the returned stop is called. +func (e *env) startChecker(t *testing.T, token string) (uuid.UUID, func()) { + t.Helper() + id := uuid.New() + client := agentapi.NewClient(e.srv.URL, token, id, "test").WithHTTPClient(e.srv.Client()) + ctx, cancel := context.WithCancel(context.Background()) + done := make(chan struct{}) + go func() { + defer close(done) + _ = checker.New(client, 8, slog.New(slog.DiscardHandler)).Run(ctx, 5*time.Second) + }() + var once bool + stop := func() { + if once { + return + } + once = true + cancel() + <-done + } + t.Cleanup(stop) + return id, stop +} + +func TestCheckersPerRegion(t *testing.T) { + e := newEnv(t) + ctx, cancel := context.WithCancel(context.Background()) + t.Cleanup(cancel) + go e.api.RunScheduler(ctx) + + target := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/down" { + w.WriteHeader(http.StatusInternalServerError) + } + })) + defer target.Close() + + eu, us := uniq("eu-"), uniq("us-") + euTok, usTok := e.agentToken(t, eu), e.agentToken(t, us) + euA, stopA := e.startChecker(t, euTok) + euB, _ := e.startChecker(t, euTok) + usC, _ := e.startChecker(t, usTok) + + owner := e.browser(t) + owner.signup("o@"+uniq("c")+".test", uniq("chk-")) + org := owner.orgID() + + // Instances register on their first poll. + waitFor(t, 5*time.Second, "both eu instances registered", func() bool { + _, body := owner.do("GET", "/api/v1/regions", nil) + for _, r := range body["regions"].([]any) { + r := r.(map[string]any) + if r["key"] == eu && r["instances"] == float64(2) { + return true + } + } + return false + }) + + const n = 30 + for i := range n { + path := "/up" + if i == 0 { + path = "/down" + } + regions := []string{eu} + if i < 3 { + regions = append(regions, us) + } + st, body := owner.do("POST", "/api/v1/org/monitors", map[string]any{ + "name": "m", "type": "http", "target": target.URL + path, "interval_seconds": 3600, "regions": regions, + }) + if st != http.StatusCreated { + t.Fatalf("create monitor = %d %v", st, body) + } + } + + count := func(checker uuid.UUID) (total, failed int) { + _ = e.dbPool.QueryRow(context.Background(), + `SELECT count(*), count(*) FILTER (WHERE NOT ok) FROM check_results WHERE org_id = $1 AND checker_id = $2`, + org, checker).Scan(&total, &failed) + return total, failed + } + waitFor(t, 15*time.Second, "all first runs reported", func() bool { + a, _ := count(euA) + b, _ := count(euB) + c, _ := count(usC) + return a+b == n && c == 3 + }) + a, aFailed := count(euA) + b, bFailed := count(euB) + if a < 5 || b < 5 { + t.Errorf("eu instances ran %d and %d checks, want both to get a random share of %d", a, b, n) + } + if aFailed+bFailed != 1 { + t.Errorf("failed eu checks = %d, want 1 (the /down monitor)", aFailed+bFailed) + } + + _, body := owner.do("GET", "/api/v1/org/monitors", nil) + withLatest := 0 + for _, m := range body["monitors"].([]any) { + if len(m.(map[string]any)["latest"].([]any)) > 0 { + withLatest++ + } + } + if withLatest != n { + t.Errorf("monitors with latest results = %d, want %d", withLatest, n) + } + + // Stopping one eu instance leaves the other to take every eu check. + stopA() + st, body := owner.do("POST", "/api/v1/org/monitors", map[string]any{ + "name": "after", "type": "tcp", "target": target.Listener.Addr().String(), "interval_seconds": 3600, "regions": []string{eu}, + }) + if st != http.StatusCreated { + t.Fatalf("create monitor = %d %v", st, body) + } + before, _ := count(euB) + waitFor(t, 10*time.Second, "remaining eu instance runs the new monitor", func() bool { + now, _ := count(euB) + return now == before+1 + }) + if after, _ := count(euA); after != a { + t.Errorf("stopped instance ran %d more checks", after-a) + } +} + +func TestAgentAuth(t *testing.T) { + e := newEnv(t) + tok := e.agentToken(t, uniq("x-")) + ctx := context.Background() + if _, err := agentapi.NewClient(e.srv.URL, "usa_wrong", uuid.New(), "t").WithHTTPClient(e.srv.Client()).Hello(ctx); !errors.Is(err, agentapi.ErrUnauthorized) { + t.Errorf("Hello(wrong token) = %v, want %v", err, agentapi.ErrUnauthorized) + } + h, err := agentapi.NewClient(e.srv.URL, tok, uuid.New(), "t").WithHTTPClient(e.srv.Client()).Hello(ctx) + if err != nil || h.Kind != "checker" { + t.Errorf("Hello() = %+v, %v; want checker", h, err) + } + // User API tokens and sessions do not open the agent API. + owner := e.browser(t) + owner.signup("a@"+uniq("a")+".test", uniq("auth-")) + st, _ := owner.do("GET", "/agent/v1/hello", nil) + if st == http.StatusOK { + t.Error("session opened the agent API") + } +} + +func (b *browser) orgID() string { + b.t.Helper() + _, me := b.do("GET", "/api/v1/me", nil) + return me["active_org"].(string) +} + +func waitFor(t *testing.T, d time.Duration, what string, cond func() bool) { + t.Helper() + deadline := time.Now().Add(d) + for !cond() { + if time.Now().After(deadline) { + t.Fatalf("timed out waiting for: %s", what) + } + time.Sleep(100 * time.Millisecond) + } +} diff --git a/internal/api/invitations.go b/internal/api/invitations.go index 1ff42c9..31620d1 100644 --- a/internal/api/invitations.go +++ b/internal/api/invitations.go @@ -65,7 +65,7 @@ func (s *Server) createInvitation(c *gin.Context) { } } _, err = q.CreateInvitation(ctx, store.CreateInvitationParams{ - OrgID: p.Org.ID, Email: email, RoleID: role.ID, TokenHash: hashToken(tok), + OrgID: p.Org.ID, Email: email, RoleID: role.ID, TokenHash: HashToken(tok), InvitedBy: &p.UserID, ExpiresAt: time.Now().Add(invitationTTL), }) return err @@ -138,7 +138,7 @@ func (s *Server) deleteInvitation(c *gin.Context) { // findInvitation returns the invitation for tok, or ok=false if it does not // exist, was used or has expired. func (s *Server) findInvitation(ctx context.Context, tok string) (inv store.GetInvitationByHashRow, ok bool, err error) { - hash := hashToken(tok) + hash := HashToken(tok) var org uuid.UUID err = s.db.Tx(ctx, tenant.Global(), func(q *store.Queries) error { org, err = q.InvitationOrg(ctx, hash) diff --git a/internal/api/monitors.go b/internal/api/monitors.go new file mode 100644 index 0000000..6b8683b --- /dev/null +++ b/internal/api/monitors.go @@ -0,0 +1,376 @@ +package api + +import ( + "context" + "encoding/json" + "errors" + "net/http" + "slices" + "strings" + "time" + + "github.com/gin-gonic/gin" + "github.com/google/uuid" + "github.com/jackc/pgx/v5" + + "git.zb-server.de/ZB-Server/uptimesebi/internal/check" + "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" +) + +type monitorRequest struct { + Name string `json:"name" binding:"required,max=200"` + Type string `json:"type" binding:"required"` + Target string `json:"target" binding:"required,max=2000"` + IntervalSeconds int `json:"interval_seconds" binding:"required"` + TimeoutMS int `json:"timeout_ms"` + Config json.RawMessage `json:"config"` + Enabled *bool `json:"enabled"` + Regions []string `json:"regions" binding:"required,min=1,max=50"` +} + +type latestView struct { + Region string `json:"region"` + Time time.Time `json:"time"` + OK bool `json:"ok"` + LatencyMS *int32 `json:"latency_ms"` + StatusCode *int32 `json:"status_code,omitempty"` + Error *string `json:"error,omitempty"` +} + +type monitorView struct { + ID uuid.UUID `json:"id"` + Name string `json:"name"` + Type string `json:"type"` + Target string `json:"target"` + IntervalSeconds int32 `json:"interval_seconds"` + TimeoutMS int32 `json:"timeout_ms"` + Config json.RawMessage `json:"config"` + Enabled bool `json:"enabled"` + Regions []string `json:"regions"` + Latest []latestView `json:"latest"` +} + +func viewMonitor(m store.Monitor, regions []string) monitorView { + return monitorView{ + ID: m.ID, Name: m.Name, Type: m.Type, Target: m.Target, IntervalSeconds: m.IntervalSeconds, + TimeoutMS: m.TimeoutMs, Config: m.Config, Enabled: m.Enabled, Regions: regions, Latest: []latestView{}, + } +} + +// minInterval is stricter in the cloud, where checks run on shared capacity. +func (s *Server) minInterval() int { + if s.cloud() { + return 30 + } + return 10 +} + +// validateMonitor normalizes req and writes an error response if it is not +// acceptable. +func (s *Server) validateMonitor(c *gin.Context, req *monitorRequest) bool { + req.Name = strings.TrimSpace(req.Name) + req.Target = strings.TrimSpace(req.Target) + if req.Name == "" { + fail(c, http.StatusUnprocessableEntity, "invalid_input") + return false + } + if req.IntervalSeconds < s.minInterval() || req.IntervalSeconds > 86400 { + fail(c, http.StatusUnprocessableEntity, "invalid_interval", "Min", s.minInterval()) + return false + } + if req.TimeoutMS == 0 { + req.TimeoutMS = min(10000, req.IntervalSeconds*1000/2) + } + if req.TimeoutMS < 100 || req.TimeoutMS > 60000 || req.TimeoutMS >= req.IntervalSeconds*1000 { + fail(c, http.StatusUnprocessableEntity, "invalid_timeout") + return false + } + cfg, err := check.Validate(check.Type(req.Type), req.Target, req.Config) + var inv check.ErrInvalid + if errors.As(err, &inv) { + fail(c, http.StatusUnprocessableEntity, inv.Code) + return false + } + if err != nil { + internalError(c, err) + return false + } + req.Config = cfg + slices.Sort(req.Regions) + req.Regions = slices.Compact(req.Regions) + ctx := c.Request.Context() + var known []store.Region + err = s.db.Tx(ctx, current(c).scope(), func(q *store.Queries) error { + var err error + known, err = q.ListRegions(ctx) + return err + }) + if err != nil { + internalError(c, err) + return false + } + for _, r := range req.Regions { + if !slices.ContainsFunc(known, func(k store.Region) bool { return k.Key == r }) { + fail(c, http.StatusUnprocessableEntity, "invalid_region") + return false + } + } + return true +} + +func (s *Server) listMonitors(c *gin.Context) { + p := current(c) + ctx := c.Request.Context() + var out []monitorView + err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error { + monitors, err := q.ListMonitors(ctx) + if err != nil { + return err + } + regions, err := q.AllMonitorRegions(ctx) + if err != nil { + return err + } + latest, err := q.LatestResults(ctx, p.Org.ID) + if err != nil { + return err + } + byMonitor := map[uuid.UUID][]string{} + for _, r := range regions { + byMonitor[r.MonitorID] = append(byMonitor[r.MonitorID], r.Region) + } + latestBy := map[uuid.UUID][]latestView{} + for _, l := range latest { + latestBy[l.MonitorID] = append(latestBy[l.MonitorID], latestView{ + Region: l.Region, Time: l.Time, OK: l.Ok, LatencyMS: l.LatencyMs, StatusCode: l.StatusCode, Error: l.Error, + }) + } + out = make([]monitorView, len(monitors)) + for i, m := range monitors { + out[i] = viewMonitor(m, byMonitor[m.ID]) + if l := latestBy[m.ID]; l != nil { + out[i].Latest = l + } + } + return nil + }) + if err != nil { + internalError(c, err) + return + } + c.JSON(http.StatusOK, gin.H{"monitors": out}) +} + +func (s *Server) createMonitor(c *gin.Context) { + var req monitorRequest + if !bind(c, &req) || !s.validateMonitor(c, &req) { + return + } + p := current(c) + ctx := c.Request.Context() + var m store.Monitor + err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error { + var err error + m, err = q.CreateMonitor(ctx, store.CreateMonitorParams{ + OrgID: p.Org.ID, Name: req.Name, Type: req.Type, Target: req.Target, + IntervalSeconds: int32(req.IntervalSeconds), TimeoutMs: int32(req.TimeoutMS), + Config: req.Config, Enabled: req.Enabled == nil || *req.Enabled, + }) + if err != nil { + return err + } + return setRegions(ctx, q, m, req.Regions) + }) + if err != nil { + internalError(c, err) + return + } + if err := s.syncSchedule(ctx, m, req.Regions, nil); err != nil { + internalError(c, err) + return + } + c.JSON(http.StatusCreated, viewMonitor(m, req.Regions)) +} + +func setRegions(ctx context.Context, q *store.Queries, m store.Monitor, regions []string) error { + if err := q.DeleteMonitorRegions(ctx, m.ID); err != nil { + return err + } + for _, r := range regions { + if err := q.AddMonitorRegion(ctx, store.AddMonitorRegionParams{MonitorID: m.ID, OrgID: m.OrgID, Region: r}); err != nil { + return err + } + } + return nil +} + +// syncSchedule applies a committed monitor change to the scheduler. Should it +// fail, the periodic reconciliation repairs the schedule. +func (s *Server) syncSchedule(ctx context.Context, m store.Monitor, regions, previous []string) error { + if !m.Enabled { + return s.sched.Remove(ctx, m.ID, append(regions, previous...)) + } + return s.sched.Upsert(ctx, schedule.Monitor{ + ID: m.ID, Interval: time.Duration(m.IntervalSeconds) * time.Second, Regions: regions, + }, previous) +} + +func (s *Server) updateMonitor(c *gin.Context) { + id, err := uuid.Parse(c.Param("id")) + if err != nil { + fail(c, http.StatusNotFound, "not_found") + return + } + var req monitorRequest + if !bind(c, &req) || !s.validateMonitor(c, &req) { + return + } + p := current(c) + ctx := c.Request.Context() + var ( + m store.Monitor + previous []string + ) + err = s.db.Tx(ctx, p.scope(), func(q *store.Queries) error { + var err error + if previous, err = q.MonitorRegions(ctx, id); err != nil { + return err + } + m, err = q.UpdateMonitor(ctx, store.UpdateMonitorParams{ + ID: id, Name: req.Name, Type: req.Type, Target: req.Target, + IntervalSeconds: int32(req.IntervalSeconds), TimeoutMs: int32(req.TimeoutMS), + Config: req.Config, Enabled: req.Enabled == nil || *req.Enabled, + }) + if err != nil { + return err + } + return setRegions(ctx, q, m, req.Regions) + }) + if errors.Is(err, pgx.ErrNoRows) { + fail(c, http.StatusNotFound, "not_found") + return + } + if err != nil { + internalError(c, err) + return + } + if err := s.syncSchedule(ctx, m, req.Regions, previous); err != nil { + internalError(c, err) + return + } + c.JSON(http.StatusOK, viewMonitor(m, req.Regions)) +} + +func (s *Server) deleteMonitor(c *gin.Context) { + id, err := uuid.Parse(c.Param("id")) + if err != nil { + fail(c, http.StatusNotFound, "not_found") + return + } + p := current(c) + ctx := c.Request.Context() + var ( + regions []string + n int64 + ) + err = s.db.Tx(ctx, p.scope(), func(q *store.Queries) error { + var err error + if regions, err = q.MonitorRegions(ctx, id); err != nil { + return err + } + n, err = q.DeleteMonitor(ctx, id) + return err + }) + if err != nil { + internalError(c, err) + return + } + if n == 0 { + fail(c, http.StatusNotFound, "not_found") + return + } + if err := s.sched.Remove(ctx, id, regions); err != nil { + internalError(c, err) + return + } + c.Status(http.StatusNoContent) +} + +type regionView struct { + Key string `json:"key"` + Name string `json:"name"` + Instances int64 `json:"instances"` +} + +func (s *Server) listRegions(c *gin.Context) { + ctx := c.Request.Context() + var rows []store.Region + err := s.db.Tx(ctx, tenant.Global(), func(q *store.Queries) error { + var err error + rows, err = q.ListRegions(ctx) + return err + }) + if err != nil { + internalError(c, err) + return + } + out := make([]regionView, len(rows)) + for i, r := range rows { + n, err := s.sched.Instances(ctx, r.Key) + if err != nil { + internalError(c, err) + return + } + out[i] = regionView{Key: r.Key, Name: r.Name, Instances: n} + } + c.JSON(http.StatusOK, gin.H{"regions": out}) +} + +// RunScheduler dispatches due checks and periodically reconciles the +// schedule with the database until ctx ends. Every API replica runs it; +// dispatch is atomic in Redis and reconciliation is idempotent. +func (s *Server) RunScheduler(ctx context.Context) { + dispatch := time.NewTicker(time.Second) + defer dispatch.Stop() + reconcile := time.NewTicker(time.Minute) + defer reconcile.Stop() + s.reconcile(ctx) + for { + select { + case <-ctx.Done(): + return + case <-dispatch.C: + if _, err := s.sched.Dispatch(ctx); err != nil && ctx.Err() == nil { + s.log.WarnContext(ctx, "dispatch failed", "error", err) + } + case <-reconcile.C: + s.reconcile(ctx) + } + } +} + +func (s *Server) reconcile(ctx context.Context) { + // One replica per minute is enough. + ok, err := s.rdb.SetNX(ctx, "sched:reconcile-lock", "1", 55*time.Second).Result() + if err != nil || !ok { + return + } + var rows []store.ListEnabledMonitorsForScheduleRow + err = s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error { + var err error + rows, err = q.ListEnabledMonitorsForSchedule(ctx) + return err + }) + if err == nil { + want := make([]schedule.Monitor, len(rows)) + for i, r := range rows { + want[i] = schedule.Monitor{ID: r.ID, Interval: time.Duration(r.IntervalSeconds) * time.Second, Regions: r.Regions} + } + err = s.sched.Reconcile(ctx, want) + } + if err != nil && ctx.Err() == nil { + s.log.WarnContext(ctx, "schedule reconciliation failed", "error", err) + } +} diff --git a/internal/api/server.go b/internal/api/server.go index 47cbd75..e83386a 100644 --- a/internal/api/server.go +++ b/internal/api/server.go @@ -16,6 +16,7 @@ import ( "git.zb-server.de/ZB-Server/uptimesebi/internal/config" "git.zb-server.de/ZB-Server/uptimesebi/internal/i18n" "git.zb-server.de/ZB-Server/uptimesebi/internal/requestid" + "git.zb-server.de/ZB-Server/uptimesebi/internal/schedule" "git.zb-server.de/ZB-Server/uptimesebi/internal/sealed" "git.zb-server.de/ZB-Server/uptimesebi/internal/sso" "git.zb-server.de/ZB-Server/uptimesebi/internal/store" @@ -36,6 +37,7 @@ type Server struct { limiter *auth.Limiter totp *auth.TOTPVerifier sso *sso.Client + sched *schedule.Scheduler } // Deps are the external resources a Server needs. @@ -61,16 +63,22 @@ func New(cfg config.API, d Deps) *Server { limiter: auth.NewLimiter(d.Redis), totp: auth.NewTOTPVerifier(d.Redis), sso: sso.New(sso.SafeHTTPClient(allowPrivate), cfg.PublicURL+"/sso/callback", allowPrivate), + sched: schedule.New(d.Redis), } } // Mount installs session loading, locale resolution and CSRF protection and // registers the JSON API and the console pages below them. func (s *Server) Mount(r gin.IRouter) { + // Agents authenticate with tokens and never carry cookies, so they skip + // the session and CSRF middleware. + s.mountAgentAPI(r) + g := r.Group("/", s.sessions.Load(), s.localize(), auth.CSRF()) v1 := g.Group("/api/v1") v1.POST("/locale", s.setLocale) + v1.GET("/regions", auth.Require(), s.listRegions) a := v1.Group("/auth") a.POST("/signup", s.signup) @@ -92,6 +100,11 @@ func (s *Server) Mount(r gin.IRouter) { org := v1.Group("/org", s.orgAccess()) org.PUT("/policy", sessionOnly(), can(authz.OrgManage), s.updatePolicy) + org.GET("/monitors", can(authz.MonitorsRead), s.listMonitors) + org.POST("/monitors", can(authz.MonitorsWrite), s.createMonitor) + org.PUT("/monitors/:id", can(authz.MonitorsWrite), s.updateMonitor) + org.DELETE("/monitors/:id", can(authz.MonitorsWrite), s.deleteMonitor) + org.GET("/sso", can(authz.OrgManage), s.listSSOProviders) org.POST("/sso", sessionOnly(), can(authz.OrgManage), s.createSSOProvider) org.PUT("/sso/:id", sessionOnly(), can(authz.OrgManage), s.updateSSOProvider) diff --git a/internal/api/sso_test.go b/internal/api/sso_test.go index 1803ad3..5422510 100644 --- a/internal/api/sso_test.go +++ b/internal/api/sso_test.go @@ -34,6 +34,7 @@ import ( type env struct { srv *httptest.Server dbPool *pgxpool.Pool + api *api.Server } func newEnv(t *testing.T) *env { @@ -89,7 +90,8 @@ func newEnv(t *testing.T) *env { PublicURL: e.srv.URL, SSOPrivateNetworks: "true", } - api.New(cfg, api.Deps{Log: log, DB: tenant.New(pool), Redis: rdb, Keys: keys, Catalog: catalog}).Mount(r) + e.api = api.New(cfg, api.Deps{Log: log, DB: tenant.New(pool), Redis: rdb, Keys: keys, Catalog: catalog}) + e.api.Mount(r) return e } diff --git a/internal/api/tokens.go b/internal/api/tokens.go index 9b7efa0..6539c9e 100644 --- a/internal/api/tokens.go +++ b/internal/api/tokens.go @@ -21,7 +21,8 @@ import ( // tokenPrefix makes tokens recognizable to secret scanners and to humans. const tokenPrefix = "ust_" -func hashToken(tok string) []byte { +// HashToken returns the stored form of an API or agent token. +func HashToken(tok string) []byte { sum := sha256.Sum256([]byte(tok)) return sum[:] } @@ -38,7 +39,7 @@ func (s *Server) tokenPrincipal(ctx context.Context, tok string) (*principal, in if !strings.HasPrefix(tok, tokenPrefix) { return nil, http.StatusUnauthorized, "unauthenticated", nil } - hash := hashToken(tok) + hash := HashToken(tok) var org uuid.UUID err := s.db.Tx(ctx, tenant.Global(), func(q *store.Queries) error { var err error @@ -163,7 +164,7 @@ func (s *Server) createToken(c *gin.Context) { var err error row, err = q.CreateAPIToken(ctx, store.CreateAPITokenParams{ OrgID: p.Org.ID, UserID: p.UserID, Name: strings.TrimSpace(req.Name), - TokenHash: hashToken(tok), Prefix: tok[:len(tokenPrefix)+6], + TokenHash: HashToken(tok), Prefix: tok[:len(tokenPrefix)+6], Permissions: perms.Strings(), ExpiresAt: expires, }) return err diff --git a/internal/check/check.go b/internal/check/check.go new file mode 100644 index 0000000..0c02010 --- /dev/null +++ b/internal/check/check.go @@ -0,0 +1,129 @@ +// Package check runs a single uptime check and validates check settings. +// +// The API validates monitor settings with Validate before storing them, and +// checkers execute them with Run, so both sides agree on what a setting +// means. +package check + +import ( + "context" + "encoding/json" + "errors" + "time" +) + +// Type names a kind of check. The values are stored in the database. +type Type string + +// Check types. +const ( + HTTP Type = "http" + TCP Type = "tcp" + ICMP Type = "icmp" + DNS Type = "dns" + TLS Type = "tls" +) + +// Types lists every check type. +var Types = []Type{HTTP, TCP, ICMP, DNS, TLS} + +// Spec is everything needed to run one check. +type Spec struct { + Type Type + Target string + Timeout time.Duration + Config json.RawMessage + // AllowPrivate permits targets on private networks. It is false for + // shared checkers in the cloud edition. + AllowPrivate bool +} + +// Outcome is the result of one check run. +type Outcome struct { + OK bool + Latency time.Duration + // StatusCode is the HTTP status, or 0 for other types. + StatusCode int + // Error explains a failure in a form suitable for showing to customers. + Error string +} + +// ErrInvalid is wrapped by Validate errors. Its message is the code shown to +// API clients, e.g. "invalid_target". +type ErrInvalid struct{ Code string } + +func (e ErrInvalid) Error() string { return "check: " + e.Code } + +func invalid(code string) error { return ErrInvalid{Code: code} } + +type runner interface { + run(ctx context.Context, s Spec) Outcome +} + +type validator interface { + // validate checks target and config and returns the config with + // defaults applied. + validate(target string, config json.RawMessage) (json.RawMessage, error) +} + +type impl interface { + runner + validator +} + +var impls = map[Type]impl{ + HTTP: httpCheck{}, + TCP: tcpCheck{}, + ICMP: icmpCheck{}, + DNS: dnsCheck{}, + TLS: tlsCheck{}, +} + +// Validate checks target and config for type t and returns the normalized +// config. Errors are ErrInvalid. +func Validate(t Type, target string, config json.RawMessage) (json.RawMessage, error) { + im, ok := impls[t] + if !ok { + return nil, invalid("invalid_type") + } + if len(config) == 0 || string(config) == "null" { + config = json.RawMessage("{}") + } + return im.validate(target, config) +} + +// Run executes s. It never panics on bad input; problems become a failed +// Outcome. +func Run(ctx context.Context, s Spec) Outcome { + im, ok := impls[s.Type] + if !ok { + return Outcome{Error: "unknown check type"} + } + ctx, cancel := context.WithTimeout(ctx, s.Timeout) + defer cancel() + start := time.Now() + o := im.run(ctx, s) + if o.Latency == 0 { + o.Latency = time.Since(start) + } + if !o.OK && o.Error == "" { + o.Error = "check failed" + } + if errors.Is(ctx.Err(), context.DeadlineExceeded) && !o.OK { + o.Error = "timeout after " + s.Timeout.String() + } + return o +} + +func decode[T any](config json.RawMessage) (T, error) { + var v T + if err := json.Unmarshal(config, &v); err != nil { + return v, invalid("invalid_config") + } + return v, nil +} + +func encode(v any) json.RawMessage { + b, _ := json.Marshal(v) + return b +} diff --git a/internal/check/check_test.go b/internal/check/check_test.go new file mode 100644 index 0000000..eb3e106 --- /dev/null +++ b/internal/check/check_test.go @@ -0,0 +1,143 @@ +package check + +import ( + "context" + "encoding/json" + "errors" + "net" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" +) + +func mustValidate(t *testing.T, typ Type, target, config string) json.RawMessage { + t.Helper() + c, err := Validate(typ, target, json.RawMessage(config)) + if err != nil { + t.Fatalf("Validate(%s, %q, %s) failed: %v", typ, target, config, err) + } + return c +} + +func run(t *testing.T, typ Type, target, config string) Outcome { + t.Helper() + return Run(context.Background(), Spec{ + Type: typ, Target: target, Timeout: 2 * time.Second, + Config: mustValidate(t, typ, target, config), AllowPrivate: true, + }) +} + +func TestHTTP(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.URL.Path { + case "/ok": + _, _ = w.Write([]byte("all systems operational")) + case "/fail": + w.WriteHeader(http.StatusServiceUnavailable) + case "/moved": + http.Redirect(w, r, "/ok", http.StatusMovedPermanently) + case "/slow": + time.Sleep(3 * time.Second) + } + })) + defer srv.Close() + + tests := []struct { + name, path, config string + wantOK bool + wantErr string + }{ + {"ok", "/ok", `{}`, true, ""}, + {"server error", "/fail", `{}`, false, "unexpected status 503"}, + {"accepted error code", "/fail", `{"expect_status":["503"]}`, true, ""}, + {"keyword present", "/ok", `{"keyword":"operational"}`, true, ""}, + {"keyword missing", "/ok", `{"keyword":"outage"}`, false, "keyword not found"}, + {"keyword must be absent", "/ok", `{"keyword":"operational","keyword_absent":true}`, false, "keyword present"}, + {"redirect followed", "/moved", `{"expect_status":["200"]}`, true, ""}, + {"redirect not followed", "/moved", `{"expect_status":["200"],"follow_redirects":false}`, false, "unexpected status 301"}, + {"timeout", "/slow", `{}`, false, "timeout after 2s"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + o := run(t, HTTP, srv.URL+tt.path, tt.config) + if o.OK != tt.wantOK || o.Error != tt.wantErr { + t.Errorf("Run() = ok %t err %q, want ok %t err %q", o.OK, o.Error, tt.wantOK, tt.wantErr) + } + }) + } +} + +func TestPrivateTargetsBlocked(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {})) + defer srv.Close() + host := strings.TrimPrefix(srv.URL, "http://") + for _, s := range []Spec{ + {Type: HTTP, Target: srv.URL, Config: mustValidate(t, HTTP, srv.URL, `{}`)}, + {Type: TCP, Target: host, Config: json.RawMessage(`{}`)}, + } { + s.Timeout = time.Second + if o := Run(context.Background(), s); o.OK || o.Error != "target resolves to a non-public address" { + t.Errorf("Run(%s %s) without AllowPrivate = %+v, want blocked", s.Type, s.Target, o) + } + } +} + +func TestTCP(t *testing.T) { + ln, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + addr := ln.Addr().String() + if o := run(t, TCP, addr, `{}`); !o.OK { + t.Errorf("Run(tcp open port) = %+v, want ok", o) + } + _ = ln.Close() + if o := run(t, TCP, addr, `{}`); o.OK || !strings.HasPrefix(o.Error, "connection failed") { + t.Errorf("Run(tcp closed port) = %+v, want connection failed", o) + } +} + +func TestTLS(t *testing.T) { + srv := httptest.NewTLSServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {})) + defer srv.Close() + host := strings.TrimPrefix(srv.URL, "https://") + // The httptest certificate is self-signed, so verification fails; that + // is reported like any other TLS problem. + if o := run(t, TLS, host, `{"server_name":"example.com"}`); o.OK || !strings.Contains(o.Error, "certificate") { + t.Errorf("Run(tls self-signed) = %+v, want certificate error", o) + } +} + +func TestValidate(t *testing.T) { + tests := []struct { + typ Type + target, config string + want string + }{ + {HTTP, "ftp://x", `{}`, "invalid_target"}, + {HTTP, "https://user:pw@x.test", `{}`, "invalid_target"}, + {HTTP, "https://x.test", `{"method":"POST"}`, "invalid_method"}, + {HTTP, "https://x.test", `{"method":"HEAD","keyword":"x"}`, "keyword_needs_get"}, + {HTTP, "https://x.test", `{"expect_status":["6xx"]}`, "invalid_expect_status"}, + {HTTP, "https://x.test", `{"headers":{"X":"a\r\nb"}}`, "invalid_header"}, + {TCP, "x.test", `{}`, "invalid_target"}, + {TCP, "x.test:0", `{}`, "invalid_target"}, + {DNS, "x.test", `{"record":"SRV"}`, "invalid_record"}, + {TLS, "x.test:443", `{"min_days_valid":-1}`, "invalid_config"}, + {"smtp", "x.test", `{}`, "invalid_type"}, + } + for _, tt := range tests { + _, err := Validate(tt.typ, tt.target, json.RawMessage(tt.config)) + var inv ErrInvalid + if !errors.As(err, &inv) || inv.Code != tt.want { + t.Errorf("Validate(%s, %q, %s) = %v, want %s", tt.typ, tt.target, tt.config, err, tt.want) + } + } + got := mustValidate(t, HTTP, "https://x.test", `{}`) + want := `{"method":"GET","expect_status":["2xx","3xx"],"follow_redirects":true,"verify_tls":true}` + if string(got) != want { + t.Errorf("Validate(http defaults) = %s, want %s", got, want) + } +} diff --git a/internal/check/http.go b/internal/check/http.go new file mode 100644 index 0000000..deef359 --- /dev/null +++ b/internal/check/http.go @@ -0,0 +1,171 @@ +package check + +import ( + "bytes" + "context" + "crypto/tls" + "encoding/json" + "errors" + "fmt" + "io" + "net" + "net/http" + "net/url" + "strconv" + "strings" + + "git.zb-server.de/ZB-Server/uptimesebi/internal/netguard" +) + +// HTTPConfig configures an HTTP(S) check. +type HTTPConfig struct { + Method string `json:"method"` + // ExpectStatus lists accepted codes or classes such as "2xx" or "301". + ExpectStatus []string `json:"expect_status"` + // Keyword must appear in the body, or must not if KeywordAbsent is set. + Keyword string `json:"keyword,omitempty"` + KeywordAbsent bool `json:"keyword_absent,omitempty"` + FollowRedirects bool `json:"follow_redirects"` + VerifyTLS bool `json:"verify_tls"` + Headers map[string]string `json:"headers,omitempty"` +} + +// maxBody bounds how much of a response is searched for the keyword. +const maxBody = 1 << 20 + +type httpCheck struct{} + +func (httpCheck) validate(target string, config json.RawMessage) (json.RawMessage, error) { + u, err := url.Parse(target) + if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" || u.User != nil { + return nil, invalid("invalid_target") + } + c := HTTPConfig{Method: http.MethodGet, ExpectStatus: []string{"2xx", "3xx"}, FollowRedirects: true, VerifyTLS: true} + if err := json.Unmarshal(config, &c); err != nil { + return nil, invalid("invalid_config") + } + c.Method = strings.ToUpper(c.Method) + if c.Method != http.MethodGet && c.Method != http.MethodHead { + return nil, invalid("invalid_method") + } + if c.Method == http.MethodHead && c.Keyword != "" { + return nil, invalid("keyword_needs_get") + } + if len(c.ExpectStatus) == 0 || len(c.ExpectStatus) > 20 { + return nil, invalid("invalid_expect_status") + } + for _, p := range c.ExpectStatus { + if !validStatusPattern(p) { + return nil, invalid("invalid_expect_status") + } + } + if len(c.Keyword) > 500 || len(c.Headers) > 20 { + return nil, invalid("invalid_config") + } + for k, v := range c.Headers { + if k == "" || strings.ContainsAny(k+v, "\r\n") || strings.EqualFold(k, "Host") { + return nil, invalid("invalid_header") + } + } + return encode(c), nil +} + +func validStatusPattern(p string) bool { + if len(p) == 3 && p[1:] == "xx" { + return p[0] >= '1' && p[0] <= '5' + } + n, err := strconv.Atoi(p) + return err == nil && n >= 100 && n <= 599 +} + +func statusMatches(code int, patterns []string) bool { + s := strconv.Itoa(code) + for _, p := range patterns { + if p == s || (strings.HasSuffix(p, "xx") && p[0] == s[0]) { + return true + } + } + return false +} + +func (httpCheck) run(ctx context.Context, s Spec) Outcome { + c, err := decode[HTTPConfig](s.Config) + if err != nil { + return Outcome{Error: "invalid configuration"} + } + d := netguard.Dialer(s.AllowPrivate, s.Timeout) + tr := &http.Transport{ + DialContext: d.DialContext, + TLSClientConfig: &tls.Config{InsecureSkipVerify: !c.VerifyTLS}, //nolint:gosec // opt-out chosen by the customer per monitor + DisableKeepAlives: true, + TLSHandshakeTimeout: s.Timeout, + ForceAttemptHTTP2: true, + } + defer tr.CloseIdleConnections() + client := &http.Client{Transport: tr} + if !c.FollowRedirects { + client.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse } + } + req, err := http.NewRequestWithContext(ctx, c.Method, s.Target, nil) + if err != nil { + return Outcome{Error: "invalid target"} + } + req.Header.Set("User-Agent", "uptimesebi-checker") + for k, v := range c.Headers { + req.Header.Set(k, v) + } + resp, err := client.Do(req) + if err != nil { + return Outcome{Error: describeNetErr(err)} + } + defer func() { _ = resp.Body.Close() }() + o := Outcome{StatusCode: resp.StatusCode} + if !statusMatches(resp.StatusCode, c.ExpectStatus) { + o.Error = fmt.Sprintf("unexpected status %d", resp.StatusCode) + return o + } + if c.Keyword != "" { + body, err := io.ReadAll(io.LimitReader(resp.Body, maxBody)) + if err != nil { + o.Error = describeNetErr(err) + return o + } + found := bytes.Contains(body, []byte(c.Keyword)) + switch { + case found && c.KeywordAbsent: + o.Error = "keyword present" + return o + case !found && !c.KeywordAbsent: + o.Error = "keyword not found" + return o + } + } + o.OK = true + return o +} + +// describeNetErr turns transport errors into short, stable messages. +func describeNetErr(err error) string { + var dnsErr *net.DNSError + var certErr *tls.CertificateVerificationError + var opErr *net.OpError + switch { + case errors.Is(err, netguard.ErrForbiddenAddress): + return "target resolves to a non-public address" + case errors.Is(err, context.DeadlineExceeded): + return "timeout" + case errors.As(err, &dnsErr): + if dnsErr.IsNotFound { + return "host not found" + } + return "dns lookup failed" + case errors.As(err, &certErr): + return "tls certificate invalid: " + certErr.Err.Error() + case errors.As(err, &opErr): + if opErr.Op == "dial" { + return "connection failed: " + opErr.Err.Error() + } + return opErr.Op + " failed: " + opErr.Err.Error() + } + return err.Error() +} diff --git a/internal/check/net.go b/internal/check/net.go new file mode 100644 index 0000000..2e317d6 --- /dev/null +++ b/internal/check/net.go @@ -0,0 +1,264 @@ +package check + +import ( + "context" + "crypto/tls" + "encoding/json" + "fmt" + "net" + "net/netip" + "slices" + "strconv" + "strings" + "time" + + "golang.org/x/net/icmp" + "golang.org/x/net/ipv4" + "golang.org/x/net/ipv6" + + "git.zb-server.de/ZB-Server/uptimesebi/internal/netguard" +) + +func validHostPort(target string) bool { + host, port, err := net.SplitHostPort(target) + if err != nil || host == "" { + return false + } + p, err := strconv.Atoi(port) + return err == nil && p > 0 && p < 65536 +} + +func validHost(host string) bool { + if _, err := netip.ParseAddr(host); err == nil { + return true + } + if len(host) == 0 || len(host) > 253 || strings.ContainsAny(host, "/:@ ") { + return false + } + return true +} + +type tcpCheck struct{} + +func (tcpCheck) validate(target string, config json.RawMessage) (json.RawMessage, error) { + if !validHostPort(target) { + return nil, invalid("invalid_target") + } + return json.RawMessage("{}"), nil +} + +func (tcpCheck) run(ctx context.Context, s Spec) Outcome { + start := time.Now() + conn, err := netguard.Dialer(s.AllowPrivate, s.Timeout).DialContext(ctx, "tcp", s.Target) + if err != nil { + return Outcome{Error: describeNetErr(err)} + } + o := Outcome{OK: true, Latency: time.Since(start)} + _ = conn.Close() + return o +} + +// TLSConfig configures a certificate expiry check. +type TLSConfig struct { + // MinDaysValid fails the check when the leaf certificate expires sooner. + MinDaysValid int `json:"min_days_valid"` + // ServerName overrides SNI and verification name; defaults to the host. + ServerName string `json:"server_name,omitempty"` +} + +type tlsCheck struct{} + +func (tlsCheck) validate(target string, config json.RawMessage) (json.RawMessage, error) { + if !validHostPort(target) { + return nil, invalid("invalid_target") + } + c := TLSConfig{MinDaysValid: 14} + if err := json.Unmarshal(config, &c); err != nil { + return nil, invalid("invalid_config") + } + if c.MinDaysValid < 0 || c.MinDaysValid > 365 || (c.ServerName != "" && !validHost(c.ServerName)) { + return nil, invalid("invalid_config") + } + return encode(c), nil +} + +func (tlsCheck) run(ctx context.Context, s Spec) Outcome { + c, err := decode[TLSConfig](s.Config) + if err != nil { + return Outcome{Error: "invalid configuration"} + } + host, _, _ := net.SplitHostPort(s.Target) + if c.ServerName != "" { + host = c.ServerName + } + d := &tls.Dialer{NetDialer: netguard.Dialer(s.AllowPrivate, s.Timeout), Config: &tls.Config{ServerName: host}} + start := time.Now() + conn, err := d.DialContext(ctx, "tcp", s.Target) + if err != nil { + return Outcome{Error: describeNetErr(err)} + } + latency := time.Since(start) + defer func() { _ = conn.Close() }() + certs := conn.(*tls.Conn).ConnectionState().PeerCertificates + if len(certs) == 0 { + return Outcome{Latency: latency, Error: "no certificate presented"} + } + left := time.Until(certs[0].NotAfter) + if days := int(left.Hours() / 24); days < c.MinDaysValid { + return Outcome{Latency: latency, Error: fmt.Sprintf("certificate expires in %d days", days)} + } + return Outcome{OK: true, Latency: latency} +} + +// DNSConfig configures a DNS check. +type DNSConfig struct { + Record string `json:"record"` + // Resolver is host:port of the DNS server to ask; empty uses the + // checker's resolver. + Resolver string `json:"resolver,omitempty"` + // Expect, if set, must be contained in one of the answers. + Expect string `json:"expect,omitempty"` +} + +var dnsRecords = []string{"A", "AAAA", "CNAME", "MX", "NS", "TXT"} + +type dnsCheck struct{} + +func (dnsCheck) validate(target string, config json.RawMessage) (json.RawMessage, error) { + if !validHost(target) { + return nil, invalid("invalid_target") + } + c := DNSConfig{Record: "A"} + if err := json.Unmarshal(config, &c); err != nil { + return nil, invalid("invalid_config") + } + c.Record = strings.ToUpper(c.Record) + if !slices.Contains(dnsRecords, c.Record) { + return nil, invalid("invalid_record") + } + if c.Resolver != "" && !validHostPort(c.Resolver) { + return nil, invalid("invalid_resolver") + } + if len(c.Expect) > 500 { + return nil, invalid("invalid_config") + } + return encode(c), nil +} + +func (dnsCheck) run(ctx context.Context, s Spec) Outcome { + c, err := decode[DNSConfig](s.Config) + if err != nil { + return Outcome{Error: "invalid configuration"} + } + r := net.DefaultResolver + if c.Resolver != "" { + d := netguard.Dialer(s.AllowPrivate, s.Timeout) + r = &net.Resolver{PreferGo: true, Dial: func(ctx context.Context, network, _ string) (net.Conn, error) { + return d.DialContext(ctx, network, c.Resolver) + }} + } + var answers []string + switch c.Record { + case "A", "AAAA": + network := "ip4" + if c.Record == "AAAA" { + network = "ip6" + } + ips, e := r.LookupNetIP(ctx, network, s.Target) + for _, ip := range ips { + answers = append(answers, ip.String()) + } + err = e + case "CNAME": + var cname string + cname, err = r.LookupCNAME(ctx, s.Target) + answers = []string{cname} + case "MX": + var mx []*net.MX + mx, err = r.LookupMX(ctx, s.Target) + for _, m := range mx { + answers = append(answers, m.Host) + } + case "NS": + var ns []*net.NS + ns, err = r.LookupNS(ctx, s.Target) + for _, n := range ns { + answers = append(answers, n.Host) + } + case "TXT": + answers, err = r.LookupTXT(ctx, s.Target) + } + if err != nil { + return Outcome{Error: describeNetErr(err)} + } + if len(answers) == 0 { + return Outcome{Error: "no " + c.Record + " records"} + } + if c.Expect != "" && !slices.ContainsFunc(answers, func(a string) bool { return strings.Contains(a, c.Expect) }) { + return Outcome{Error: "expected answer not found"} + } + return Outcome{OK: true} +} + +type icmpCheck struct{} + +func (icmpCheck) validate(target string, config json.RawMessage) (json.RawMessage, error) { + if !validHost(target) { + return nil, invalid("invalid_target") + } + return json.RawMessage("{}"), nil +} + +// run sends one echo request over an unprivileged ICMP socket. The host must +// allow it via net.ipv4.ping_group_range; otherwise the check reports that. +func (icmpCheck) run(ctx context.Context, s Spec) Outcome { + var addrs []netip.Addr + var err error + if s.AllowPrivate { + addrs, err = net.DefaultResolver.LookupNetIP(ctx, "ip", s.Target) + } else { + addrs, err = netguard.CheckHost(ctx, s.Target) + } + if err != nil { + return Outcome{Error: describeNetErr(err)} + } + if len(addrs) == 0 { + return Outcome{Error: "host not found"} + } + addr := addrs[0].Unmap() + network, proto, echo := "udp4", 1, icmp.Type(ipv4.ICMPTypeEcho) + if addr.Is6() { + network, proto, echo = "udp6", 58, ipv6.ICMPTypeEchoRequest + } + conn, err := icmp.ListenPacket(network, "") + if err != nil { + return Outcome{Error: "icmp not permitted on this checker: " + err.Error()} + } + defer func() { _ = conn.Close() }() + if dl, ok := ctx.Deadline(); ok { + _ = conn.SetDeadline(dl) + } + msg := icmp.Message{Type: echo, Body: &icmp.Echo{ID: 1, Seq: 1, Data: []byte("uptimesebi")}} + b, err := msg.Marshal(nil) + if err != nil { + return Outcome{Error: err.Error()} + } + start := time.Now() + if _, err := conn.WriteTo(b, &net.UDPAddr{IP: addr.AsSlice()}); err != nil { + return Outcome{Error: describeNetErr(err)} + } + buf := make([]byte, 1500) + for { + n, _, err := conn.ReadFrom(buf) + if err != nil { + return Outcome{Error: "no echo reply"} + } + reply, err := icmp.ParseMessage(proto, buf[:n]) + if err != nil { + continue + } + if reply.Type == ipv4.ICMPTypeEchoReply || reply.Type == ipv6.ICMPTypeEchoReply { + return Outcome{OK: true, Latency: time.Since(start)} + } + } +} diff --git a/internal/checker/checker.go b/internal/checker/checker.go new file mode 100644 index 0000000..3abf049 --- /dev/null +++ b/internal/checker/checker.go @@ -0,0 +1,201 @@ +// Package checker is the checker agent: it fetches jobs from the API, runs +// them and reports the results. It keeps no state beyond results that are +// waiting to be sent. +package checker + +import ( + "context" + "errors" + "log/slog" + "sync" + "sync/atomic" + "time" + + "git.zb-server.de/ZB-Server/uptimesebi/internal/agentapi" + "git.zb-server.de/ZB-Server/uptimesebi/internal/check" +) + +// API is the part of agentapi.Client the runner uses. +type API interface { + Jobs(ctx context.Context, max int, wait time.Duration) ([]agentapi.Job, error) + Report(ctx context.Context, results []agentapi.Result) error + Release(ctx context.Context) error +} + +const ( + pollWait = 20 * time.Second + flushInterval = 2 * time.Second + // maxPending bounds results kept while the API is unreachable. + maxPending = 50_000 +) + +// Runner executes jobs with bounded concurrency. +type Runner struct { + api API + log *slog.Logger + slots chan struct{} + run func(context.Context, check.Spec) check.Outcome + + results chan agentapi.Result + lastPoll atomic.Int64 +} + +// New returns a Runner that runs at most concurrency checks at once. +func New(api API, concurrency int, log *slog.Logger) *Runner { + return &Runner{ + api: api, + log: log, + slots: make(chan struct{}, max(concurrency, 1)), + run: check.Run, + results: make(chan agentapi.Result, 1024), + } +} + +// Healthy reports an error unless the API answered a poll recently. +func (r *Runner) Healthy(context.Context) error { + if time.Since(time.UnixMilli(r.lastPoll.Load())) > 2*pollWait+10*time.Second { + return errors.New("no successful poll recently") + } + return nil +} + +// Run polls and executes jobs until ctx is cancelled, then hands queued jobs +// back, lets running checks finish within drain and sends the last results. +// It returns early only if the API rejects the agent token. +func (r *Runner) Run(ctx context.Context, drain time.Duration) error { + var running sync.WaitGroup + reportDone := make(chan struct{}) + reportCtx, stopReport := context.WithCancel(context.WithoutCancel(ctx)) + go func() { + defer close(reportDone) + r.report(reportCtx) + }() + + err := r.poll(ctx, &running) + + releaseCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second) + if rerr := r.api.Release(releaseCtx); rerr != nil { + r.log.Warn("release failed; queued jobs move to other instances once this one is considered gone", "error", rerr) + } + cancel() + + waited := make(chan struct{}) + go func() { running.Wait(); close(waited) }() + select { + case <-waited: + case <-time.After(drain): + r.log.Warn("checks still running at shutdown", "drain", drain) + } + stopReport() + <-reportDone + return err +} + +func (r *Runner) poll(ctx context.Context, running *sync.WaitGroup) error { + backoff := time.Second + for ctx.Err() == nil { + free := cap(r.slots) - len(r.slots) + wait := pollWait + if free == 0 { + // Still poll as a heartbeat, but do not take work. + wait = 0 + } + jobs, err := r.api.Jobs(ctx, free, wait) + switch { + case errors.Is(err, agentapi.ErrUnauthorized): + return err + case err != nil: + if ctx.Err() != nil { + return nil + } + r.log.Warn("polling for jobs failed", "error", err, "retry_in", backoff) + sleep(ctx, backoff) + backoff = min(backoff*2, 30*time.Second) + continue + } + backoff = time.Second + r.lastPoll.Store(time.Now().UnixMilli()) + for _, j := range jobs { + r.slots <- struct{}{} + running.Add(1) + go func() { + defer func() { <-r.slots; running.Done() }() + r.results <- r.execute(ctx, j) + }() + } + if free == 0 { + sleep(ctx, time.Second) + } + } + return nil +} + +func (r *Runner) execute(ctx context.Context, j agentapi.Job) agentapi.Result { + // Checks already started finish even during shutdown; their timeout + // bounds them. + ctx = context.WithoutCancel(ctx) + start := time.Now() + o := r.run(ctx, check.Spec{ + Type: check.Type(j.Type), Target: j.Target, Timeout: time.Duration(j.TimeoutMS) * time.Millisecond, + Config: j.Config, AllowPrivate: j.AllowPrivate, + }) + return agentapi.Result{ + MonitorID: j.MonitorID, ScheduledAt: j.ScheduledAt, StartedAt: start, OK: o.OK, + LatencyMS: int(o.Latency.Milliseconds()), StatusCode: o.StatusCode, Error: o.Error, + } +} + +// report batches results and sends them. Unsent results are retried with +// the next batch; when ctx ends it makes one last attempt. +func (r *Runner) report(ctx context.Context) { + tick := time.NewTicker(flushInterval) + defer tick.Stop() + var pending []agentapi.Result + flush := func(ctx context.Context) { + for len(pending) > 0 { + n := min(len(pending), agentapi.MaxResults) + if err := r.api.Report(ctx, pending[:n]); err != nil { + r.log.Warn("reporting results failed", "error", err, "pending", len(pending)) + return + } + pending = pending[n:] + } + } + for { + select { + case res := <-r.results: + pending = append(pending, res) + if len(pending) > maxPending { + dropped := len(pending) - maxPending + pending = pending[dropped:] + r.log.Warn("dropping old results while the API is unreachable", "dropped", dropped) + } + if len(pending) >= agentapi.MaxResults { + flush(ctx) + } + case <-tick.C: + flush(ctx) + case <-ctx.Done(): + for { + select { + case res := <-r.results: + pending = append(pending, res) + continue + default: + } + break + } + last, cancel := context.WithTimeout(context.Background(), 5*time.Second) + flush(last) + cancel() + return + } + } +} + +func sleep(ctx context.Context, d time.Duration) { + select { + case <-ctx.Done(): + case <-time.After(d): + } +} diff --git a/internal/config/config.go b/internal/config/config.go index 3aead1d..82c03d7 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -24,14 +24,25 @@ const ( // Common holds settings shared by all components. type Common struct { - Edition Edition `env:"UPTIME_EDITION" envDefault:"selfhosted"` - LogLevel slog.Level `env:"UPTIME_LOG_LEVEL" envDefault:"info"` - DatabaseURL string `env:"UPTIME_DATABASE_URL"` - RedisURL string `env:"UPTIME_REDIS_URL"` - RedisSentinel Sentinel + Edition Edition `env:"UPTIME_EDITION" envDefault:"selfhosted"` + LogLevel slog.Level `env:"UPTIME_LOG_LEVEL" envDefault:"info"` ShutdownTimeout time.Duration `env:"UPTIME_SHUTDOWN_TIMEOUT" envDefault:"20s"` } +// Storage locates Postgres and Redis. Only the API connects to them; every +// other component goes through the API. +type Storage struct { + DatabaseURL string `env:"UPTIME_DATABASE_URL"` + RedisURL string `env:"UPTIME_REDIS_URL"` + RedisSentinel Sentinel +} + +// Agent configures how checkers and status page servers reach the API. +type Agent struct { + APIURL string `env:"UPTIME_API_URL,required,notEmpty"` + Token string `env:"UPTIME_AGENT_TOKEN,required,notEmpty"` +} + // Sentinel switches the redis client to failover mode. UPTIME_REDIS_URL then // only contributes credentials, db and TLS for the master; its host is ignored. type Sentinel struct { @@ -58,6 +69,7 @@ const ( // API configures cmd/api. type API struct { Common + Storage Listen string `env:"UPTIME_API_LISTEN" envDefault:":8080"` SecretKeys string `env:"UPTIME_SECRET_KEYS"` Signup SignupMode `env:"UPTIME_SIGNUP" envDefault:"first-user"` @@ -86,6 +98,9 @@ func (a API) Validate() error { if err := a.Common.Validate(); err != nil { return err } + if err := a.Storage.Validate(); err != nil { + return err + } if a.SecretKeys == "" { return fmt.Errorf("config: UPTIME_SECRET_KEYS is required (format id:base64-32-bytes)") } @@ -108,17 +123,19 @@ func (a API) Validate() error { return nil } -// Checker configures cmd/checker. Region names the location this instance -// checks from and must match the regions assigned to monitors. +// Checker configures cmd/checker. Its region is bound to the agent token. type Checker struct { Common - Region string `env:"UPTIME_CHECKER_REGION,required,notEmpty"` + Agent HealthListen string `env:"UPTIME_CHECKER_HEALTH_LISTEN" envDefault:":8081"` + // Concurrency caps checks running at the same time in one instance. + Concurrency int `env:"UPTIME_CHECKER_CONCURRENCY" envDefault:"64"` } // StatusPage configures cmd/statuspage. type StatusPage struct { Common + Agent Listen string `env:"UPTIME_STATUSPAGE_LISTEN" envDefault:":8082"` } @@ -131,13 +148,17 @@ func Load[T any]() (T, error) { return cfg, nil } -// Validate reports missing or contradictory settings. +// Validate reports an unknown edition. func (c Common) Validate() error { switch c.Edition { case EditionCloud, EditionSelfHosted: - default: - return fmt.Errorf("config: unknown edition %q", c.Edition) + return nil } + return fmt.Errorf("config: unknown edition %q", c.Edition) +} + +// Validate reports missing or contradictory database and Redis settings. +func (c Storage) Validate() error { if c.DatabaseURL == "" { return fmt.Errorf("config: UPTIME_DATABASE_URL is required") } diff --git a/internal/config/config_test.go b/internal/config/config_test.go index c62092a..2ed970c 100644 --- a/internal/config/config_test.go +++ b/internal/config/config_test.go @@ -2,20 +2,20 @@ package config import "testing" -func TestCommonValidateRedisModes(t *testing.T) { +func TestStorageValidateRedisModes(t *testing.T) { tests := []struct { name string - modify func(*Common) + modify func(*Storage) wantErr bool }{ - {"standalone", func(c *Common) { c.RedisURL = "redis://r" }, false}, - {"no redis", func(*Common) {}, true}, - {"sentinel", func(c *Common) { c.RedisSentinel = Sentinel{Master: "m", Addrs: []string{"s:26379"}} }, false}, - {"sentinel without addrs", func(c *Common) { c.RedisSentinel = Sentinel{Master: "m"} }, true}, + {"standalone", func(c *Storage) { c.RedisURL = "redis://r" }, false}, + {"no redis", func(*Storage) {}, true}, + {"sentinel", func(c *Storage) { c.RedisSentinel = Sentinel{Master: "m", Addrs: []string{"s:26379"}} }, false}, + {"sentinel without addrs", func(c *Storage) { c.RedisSentinel = Sentinel{Master: "m"} }, true}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - c := Common{Edition: EditionSelfHosted, DatabaseURL: "postgres://x"} + c := Storage{DatabaseURL: "postgres://x"} tt.modify(&c) if err := c.Validate(); (err != nil) != tt.wantErr { t.Errorf("Validate() = %v, want error: %t", err, tt.wantErr) diff --git a/internal/i18n/i18n_test.go b/internal/i18n/i18n_test.go index 16a932c..c6d3676 100644 --- a/internal/i18n/i18n_test.go +++ b/internal/i18n/i18n_test.go @@ -68,6 +68,7 @@ var usagePatterns = []struct { {re: regexp.MustCompile(`[^(]"(sso_[a-z_]+)"`), prefix: "error.", dir: "api"}, {re: regexp.MustCompile(`return "(invalid_[a-z_]+)"`), prefix: "error."}, {re: regexp.MustCompile(`code = "([a-z_]+)"`), prefix: "error."}, + {re: regexp.MustCompile(`\binvalid\("([a-z_]+)"\)`), prefix: "error."}, {re: regexp.MustCompile(`NoticeID = "([a-z0-9_.]+)"`)}, {re: regexp.MustCompile(`@(?:settingsHeading|sectionHeading)\("([a-z0-9_.]+)"`)}, {re: regexp.MustCompile(`@settingsHeading\("[a-z0-9_.]+", "([a-z0-9_.]+)"`)}, diff --git a/internal/i18n/locales/de.json b/internal/i18n/locales/de.json index f610030..f4a1e12 100644 --- a/internal/i18n/locales/de.json +++ b/internal/i18n/locales/de.json @@ -32,20 +32,33 @@ "console.nav.tokens": "API-Tokens", "console.sso_required_action": "Mit SSO anmelden", "console.totp_missing_action": "Jetzt einrichten", + "error.agent_protocol_unsupported": "Diese Agent-Version wird von der API nicht unterstützt. Bitte den Agent aktualisieren.", "error.already_assigned": "Das Mitglied hat diese Rolle bereits.", "error.already_member": "Diese Person ist bereits Mitglied.", "error.email_taken": "Diese E-Mail-Adresse ist bereits registriert.", "error.forbidden": "Dafür fehlt dir die Berechtigung.", "error.internal": "Interner Fehler.", "error.invalid_code": "Code ungültig.", + "error.invalid_config": "Die Check-Einstellungen sind ungültig.", "error.invalid_credentials": "E-Mail oder Passwort falsch.", "error.invalid_domain": "Eine der Domains ist ungültig.", "error.invalid_email": "Bitte eine gültige E-Mail-Adresse eingeben.", + "error.invalid_expect_status": "Erwartete Statuscodes müssen Codes wie 200 oder Klassen wie 2xx sein.", + "error.invalid_header": "Ein Request-Header ist ungültig.", "error.invalid_input": "Eingaben prüfen.", + "error.invalid_interval": "Das Intervall muss mindestens {{.Min}} Sekunden und höchstens einen Tag betragen.", + "error.invalid_method": "Nur GET- und HEAD-Anfragen werden unterstützt.", "error.invalid_permissions": "Mindestens eine Berechtigung auswählen.", + "error.invalid_record": "Nicht unterstützter DNS-Record-Typ.", + "error.invalid_region": "Unbekannte Region.", + "error.invalid_resolver": "Der Resolver muss als host:port angegeben werden.", "error.invalid_slug": "Kurzname: 2–63 Zeichen, a–z, 0–9 und Bindestrich.", + "error.invalid_target": "Das Ziel passt nicht zu diesem Check-Typ.", + "error.invalid_timeout": "Der Timeout muss zwischen 100 ms und 60 s liegen und kürzer als das Intervall sein.", + "error.invalid_type": "Unbekannter Check-Typ.", "error.invitation_email_mismatch": "Diese Einladung ging an eine andere E-Mail-Adresse als die, mit der du angemeldet bist.", "error.invitation_invalid": "Diese Einladung ist ungültig, abgelaufen oder wurde bereits verwendet.", + "error.keyword_needs_get": "Keyword-Checks brauchen GET-Anfragen.", "error.mfa_expired": "Anmeldung abgelaufen, bitte erneut anmelden.", "error.no_password": "Konto ohne Passwort.", "error.not_found": "Nicht gefunden.", diff --git a/internal/i18n/locales/en.json b/internal/i18n/locales/en.json index 19b7654..41979f2 100644 --- a/internal/i18n/locales/en.json +++ b/internal/i18n/locales/en.json @@ -32,20 +32,33 @@ "console.nav.tokens": "API tokens", "console.sso_required_action": "Sign in with SSO", "console.totp_missing_action": "Set up now", + "error.agent_protocol_unsupported": "This agent version is not supported by the API. Please update the agent.", "error.already_assigned": "The member already has this role.", "error.already_member": "This person is already a member.", "error.email_taken": "This email address is already registered.", "error.forbidden": "You are not allowed to do this.", "error.internal": "Internal error.", "error.invalid_code": "Invalid code.", + "error.invalid_config": "The check settings are not valid.", "error.invalid_credentials": "Wrong email or password.", "error.invalid_domain": "One of the domains is not valid.", "error.invalid_email": "Please enter a valid email address.", + "error.invalid_expect_status": "Expected status codes must be codes like 200 or classes like 2xx.", + "error.invalid_header": "A request header is not valid.", "error.invalid_input": "Please check your input.", + "error.invalid_interval": "The interval must be at least {{.Min}} seconds and at most one day.", + "error.invalid_method": "Only GET and HEAD requests are supported.", "error.invalid_permissions": "Choose at least one permission.", + "error.invalid_record": "Unsupported DNS record type.", + "error.invalid_region": "Unknown region.", + "error.invalid_resolver": "The resolver must be given as host:port.", "error.invalid_slug": "Short name: 2–63 characters, a–z, 0–9 and hyphen.", + "error.invalid_target": "The target is not valid for this check type.", + "error.invalid_timeout": "The timeout must be between 100 ms and 60 s and shorter than the interval.", + "error.invalid_type": "Unknown check type.", "error.invitation_email_mismatch": "This invitation was sent to a different email address than the one you are signed in with.", "error.invitation_invalid": "This invitation is invalid, expired or was already used.", + "error.keyword_needs_get": "Keyword checks need GET requests.", "error.mfa_expired": "Sign-in expired, please start again.", "error.no_password": "This account has no password.", "error.not_found": "Not found.", diff --git a/internal/migrations/sql/00013_monitors.sql b/internal/migrations/sql/00013_monitors.sql new file mode 100644 index 0000000..7bdcc26 --- /dev/null +++ b/internal/migrations/sql/00013_monitors.sql @@ -0,0 +1,115 @@ +-- +goose Up +-- Regions appear when a checker for them first starts. Organization-private +-- regions for customer-hosted checkers follow with the remote mode. +CREATE TABLE regions ( + key text PRIMARY KEY CHECK (key ~ '^[a-z0-9][a-z0-9-]{0,39}$'), + name text NOT NULL, + created_at timestamptz NOT NULL DEFAULT now() +); + +CREATE TABLE monitors ( + id uuid PRIMARY KEY DEFAULT gen_random_uuid(), + org_id uuid NOT NULL REFERENCES orgs (id) ON DELETE CASCADE, + name text NOT NULL CHECK (length(name) BETWEEN 1 AND 200), + type text NOT NULL CHECK (type IN ('http', 'tcp', 'icmp', 'dns', 'tls')), + target text NOT NULL CHECK (length(target) BETWEEN 1 AND 2000), + interval_seconds integer NOT NULL CHECK (interval_seconds BETWEEN 10 AND 86400), + timeout_ms integer NOT NULL CHECK (timeout_ms BETWEEN 100 AND 60000), + -- Type-specific settings, validated by the application. + config jsonb NOT NULL DEFAULT '{}', + enabled boolean NOT NULL DEFAULT true, + created_at timestamptz NOT NULL DEFAULT now(), + updated_at timestamptz NOT NULL DEFAULT now() +); + +CREATE INDEX monitors_org_idx ON monitors (org_id); + +CREATE TABLE monitor_regions ( + monitor_id uuid NOT NULL REFERENCES monitors (id) ON DELETE CASCADE, + org_id uuid NOT NULL REFERENCES orgs (id) ON DELETE CASCADE, + region text NOT NULL REFERENCES regions (key), + PRIMARY KEY (monitor_id, region) +); + +ALTER TABLE monitors ENABLE ROW LEVEL SECURITY; +ALTER TABLE monitors FORCE ROW LEVEL SECURITY; +CREATE POLICY monitors_tenant ON monitors FOR ALL + USING (app_scope_system() OR org_id = app_org_id()) + WITH CHECK (app_scope_system() OR org_id = app_org_id()); + +ALTER TABLE monitor_regions ENABLE ROW LEVEL SECURITY; +ALTER TABLE monitor_regions FORCE ROW LEVEL SECURITY; +CREATE POLICY monitor_regions_tenant ON monitor_regions FOR ALL + USING (app_scope_system() OR org_id = app_org_id()) + WITH CHECK (app_scope_system() OR org_id = app_org_id()); + +-- check_results is deliberately not under row-level security: TimescaleDB +-- refuses both compression and continuous aggregates on tables with row +-- security. Tenant isolation for this table and its aggregates is enforced +-- in the queries, which all take org_id as a parameter. +CREATE TABLE check_results ( + time timestamptz NOT NULL, + org_id uuid NOT NULL, + monitor_id uuid NOT NULL, + region text NOT NULL, + checker_id uuid NOT NULL, + ok boolean NOT NULL, + latency_ms integer, + status_code integer, + error text +); + +SELECT create_hypertable('check_results', by_range('time', INTERVAL '1 day')); +CREATE INDEX check_results_monitor_idx ON check_results (monitor_id, time DESC); + +ALTER TABLE check_results SET ( + timescaledb.compress, + timescaledb.compress_segmentby = 'org_id, monitor_id, region', + timescaledb.compress_orderby = 'time DESC' +); +SELECT add_compression_policy('check_results', INTERVAL '7 days'); +SELECT add_retention_policy('check_results', INTERVAL '90 days'); + +CREATE MATERIALIZED VIEW check_results_1h WITH (timescaledb.continuous) AS +SELECT time_bucket(INTERVAL '1 hour', time) AS bucket, + org_id, monitor_id, region, + count(*) AS total, + count(*) FILTER (WHERE ok) AS ok_count, + avg(latency_ms)::real AS avg_latency_ms, + max(latency_ms) AS max_latency_ms +FROM check_results +GROUP BY 1, 2, 3, 4 +WITH NO DATA; + +-- Include the not yet materialized recent hours in queries. +ALTER MATERIALIZED VIEW check_results_1h SET (timescaledb.materialized_only = false); + +SELECT add_continuous_aggregate_policy('check_results_1h', + start_offset => INTERVAL '3 days', end_offset => INTERVAL '5 minutes', schedule_interval => INTERVAL '5 minutes'); + +CREATE MATERIALIZED VIEW check_results_1d WITH (timescaledb.continuous) AS +SELECT time_bucket(INTERVAL '1 day', bucket) AS bucket, + org_id, monitor_id, region, + sum(total)::bigint AS total, + sum(ok_count)::bigint AS ok_count, + (sum(avg_latency_ms * total) / nullif(sum(total), 0))::real AS avg_latency_ms, + max(max_latency_ms) AS max_latency_ms +FROM check_results_1h +GROUP BY 1, 2, 3, 4 +WITH NO DATA; + +ALTER MATERIALIZED VIEW check_results_1d SET (timescaledb.materialized_only = false); + +SELECT add_continuous_aggregate_policy('check_results_1d', + start_offset => INTERVAL '30 days', end_offset => INTERVAL '1 hour', schedule_interval => INTERVAL '1 hour'); + +-- Aggregates outlive the raw data. +SELECT add_retention_policy('check_results_1h', INTERVAL '400 days'); + +-- +goose Down +DROP MATERIALIZED VIEW check_results_1d; +DROP MATERIALIZED VIEW check_results_1h; +DROP TABLE check_results; +DROP TABLE monitor_regions; +DROP TABLE monitors; +DROP TABLE regions; diff --git a/internal/migrations/sql/00014_agents.sql b/internal/migrations/sql/00014_agents.sql new file mode 100644 index 0000000..f5d4f7f --- /dev/null +++ b/internal/migrations/sql/00014_agents.sql @@ -0,0 +1,28 @@ +-- +goose Up +-- Agents are checkers and status page servers. Agents without an org are run +-- by the operator and serve every organization; org-owned agents arrive with +-- customer-hosted checkers. +CREATE TABLE agents ( + id uuid PRIMARY KEY DEFAULT gen_random_uuid(), + org_id uuid REFERENCES orgs (id) ON DELETE CASCADE, + kind text NOT NULL CHECK (kind IN ('checker', 'statuspage')), + name text NOT NULL CHECK (length(name) BETWEEN 1 AND 100), + region text REFERENCES regions (key), + token_hash bytea NOT NULL UNIQUE, + prefix text NOT NULL, + last_seen_at timestamptz, + release text, + created_at timestamptz NOT NULL DEFAULT now(), + CHECK ((kind = 'checker') = (region IS NOT NULL)) +); + +ALTER TABLE agents ENABLE ROW LEVEL SECURITY; +ALTER TABLE agents FORCE ROW LEVEL SECURITY; +CREATE POLICY agents_read ON agents FOR SELECT + USING (org_id IS NULL OR app_scope_system() OR org_id = app_org_id()); +CREATE POLICY agents_write ON agents FOR ALL + USING (app_scope_system() OR org_id = app_org_id()) + WITH CHECK (app_scope_system() OR org_id = app_org_id()); + +-- +goose Down +DROP TABLE agents; diff --git a/internal/netguard/netguard.go b/internal/netguard/netguard.go new file mode 100644 index 0000000..4f55ea0 --- /dev/null +++ b/internal/netguard/netguard.go @@ -0,0 +1,58 @@ +// Package netguard keeps customer-supplied addresses from reaching our own +// infrastructure. Identity providers and monitored targets are configured by +// customers; in the cloud edition they must not be able to probe private +// networks through us. +package netguard + +import ( + "context" + "errors" + "net" + "net/netip" + "syscall" + "time" +) + +// ErrForbiddenAddress is returned when a destination resolves to an address +// the caller may not contact. +var ErrForbiddenAddress = errors.New("netguard: destination resolves to a non-public address") + +var cgnat = netip.MustParsePrefix("100.64.0.0/10") + +// IsPublic reports whether a is a globally routable unicast address. +func IsPublic(a netip.Addr) bool { + a = a.Unmap() + return a.IsGlobalUnicast() && !a.IsPrivate() && !cgnat.Contains(a) +} + +// Dialer returns a dialer that, unless allowPrivate is set, refuses to +// connect to non-public addresses. The check runs on the resolved address at +// connect time, so DNS rebinding and redirects cannot bypass it. +func Dialer(allowPrivate bool, timeout time.Duration) *net.Dialer { + d := &net.Dialer{Timeout: timeout} + if !allowPrivate { + d.Control = func(_, address string, _ syscall.RawConn) error { + ap, err := netip.ParseAddrPort(address) + if err != nil || !IsPublic(ap.Addr()) { + return ErrForbiddenAddress + } + return nil + } + } + return d +} + +// CheckHost resolves host and fails if any of its addresses is non-public. +// Use it where no dialer is involved, such as ICMP. +func CheckHost(ctx context.Context, host string) ([]netip.Addr, error) { + addrs, err := net.DefaultResolver.LookupNetIP(ctx, "ip", host) + if err != nil { + return nil, err + } + for _, a := range addrs { + if !IsPublic(a) { + return nil, ErrForbiddenAddress + } + } + return addrs, nil +} diff --git a/internal/netguard/netguard_test.go b/internal/netguard/netguard_test.go new file mode 100644 index 0000000..47967af --- /dev/null +++ b/internal/netguard/netguard_test.go @@ -0,0 +1,50 @@ +package netguard + +import ( + "context" + "errors" + "net" + "net/netip" + "testing" + "time" +) + +func TestIsPublic(t *testing.T) { + tests := map[string]bool{ + "8.8.8.8": true, + "2606:4700::1111": true, + "127.0.0.1": false, + "10.1.2.3": false, + "172.16.0.1": false, + "192.168.1.1": false, + "169.254.169.254": false, + "100.64.0.1": false, + "0.0.0.0": false, + "::1": false, + "fd00::1": false, + "fe80::1": false, + "::ffff:127.0.0.1": false, + } + for addr, want := range tests { + if got := IsPublic(netip.MustParseAddr(addr)); got != want { + t.Errorf("IsPublic(%s) = %t, want %t", addr, got, want) + } + } +} + +func TestDialerBlocksLoopback(t *testing.T) { + ln, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + defer func() { _ = ln.Close() }() + ctx := context.Background() + if _, err := Dialer(false, time.Second).DialContext(ctx, "tcp", ln.Addr().String()); !errors.Is(err, ErrForbiddenAddress) { + t.Errorf("Dialer(false).Dial(loopback) error = %v, want %v", err, ErrForbiddenAddress) + } + conn, err := Dialer(true, time.Second).DialContext(ctx, "tcp", ln.Addr().String()) + if err != nil { + t.Fatalf("Dialer(true).Dial(loopback) failed: %v", err) + } + _ = conn.Close() +} diff --git a/internal/platform/agent.go b/internal/platform/agent.go new file mode 100644 index 0000000..af5d7d8 --- /dev/null +++ b/internal/platform/agent.go @@ -0,0 +1,29 @@ +package platform + +import ( + "context" + "errors" + "log/slog" + "time" + + "git.zb-server.de/ZB-Server/uptimesebi/internal/agentapi" +) + +// Hello waits until the API accepts the agent token, retrying while the API +// is unreachable so agents can start before it. A rejected token is fatal. +func Hello(ctx context.Context, c *agentapi.Client, log *slog.Logger) (agentapi.Hello, error) { + backoff := time.Second + for { + h, err := c.Hello(ctx) + if err == nil || errors.Is(err, agentapi.ErrUnauthorized) || ctx.Err() != nil { + return h, err + } + log.Warn("api not reachable yet", "error", err, "retry_in", backoff) + select { + case <-ctx.Done(): + return h, ctx.Err() + case <-time.After(backoff): + } + backoff = min(backoff*2, 30*time.Second) + } +} diff --git a/internal/platform/redis.go b/internal/platform/redis.go index 585704f..414d6a6 100644 --- a/internal/platform/redis.go +++ b/internal/platform/redis.go @@ -11,7 +11,7 @@ import ( // OpenRedis connects to a single server or, when c.RedisSentinel is enabled, // to the current master via sentinel with automatic failover. -func OpenRedis(ctx context.Context, c config.Common) (*redis.Client, error) { +func OpenRedis(ctx context.Context, c config.Storage) (*redis.Client, error) { var rdb *redis.Client if c.RedisSentinel.Enabled() { opts, err := failoverOptions(c.RedisURL, c.RedisSentinel) diff --git a/internal/platform/run.go b/internal/platform/run.go index 3b3a715..843a8e4 100644 --- a/internal/platform/run.go +++ b/internal/platform/run.go @@ -47,7 +47,7 @@ func SignalContext() (context.Context, context.CancelFunc) { // Connect validates c, refuses to start against an outdated schema, and // opens Postgres and Redis. -func Connect(ctx context.Context, c config.Common, log *slog.Logger) (*Deps, error) { +func Connect(ctx context.Context, c config.Storage, log *slog.Logger) (*Deps, error) { if err := c.Validate(); err != nil { return nil, err } diff --git a/internal/schedule/schedule.go b/internal/schedule/schedule.go new file mode 100644 index 0000000..933fa42 --- /dev/null +++ b/internal/schedule/schedule.go @@ -0,0 +1,294 @@ +// Package schedule distributes due checks to checker instances. +// +// It runs inside the API, which is the only component with Redis access. +// Per region, a sorted set holds each monitor's next due time. Dispatch +// moves due monitors into the queue of a randomly chosen live instance of +// that region and schedules their next run in the same atomic step, so any +// number of API replicas can dispatch concurrently without a leader, and a +// lost job never stops a monitor from running again. +// +// Instances announce themselves by polling. One that stops polling is +// considered gone after StaleAfter; its queued jobs return to the region. +package schedule + +import ( + "context" + "errors" + "fmt" + "strconv" + "strings" + "time" + + "github.com/google/uuid" + "github.com/redis/go-redis/v9" +) + +// StaleAfter is how long an instance may stay silent before its queued jobs +// are given to others. Instances poll at least every PollInterval. +const ( + PollInterval = 20 * time.Second + StaleAfter = 45 * time.Second +) + +const ( + keyRegions = "sched:regions" + keyIntervals = "sched:intervals" + jobsPrefix = "sched:jobs:" + // jobsTTL drops queues of instances that vanished together with every + // API replica that could have recovered them. + jobsTTL = 10 * time.Minute +) + +func keyDue(region string) string { return "sched:due:" + region } +func keyInstances(region string) string { return "sched:instances:" + region } + +// Scheduler is safe for concurrent use. +type Scheduler struct { + rdb redis.UniversalClient + now func() time.Time +} + +// New returns a Scheduler on rdb. +func New(rdb redis.UniversalClient) *Scheduler { + return &Scheduler{rdb: rdb, now: time.Now} +} + +// Entry is one dispatched run. +type Entry struct { + MonitorID uuid.UUID + ScheduledAt time.Time +} + +// Monitor is the schedule-relevant part of a monitor. +type Monitor struct { + ID uuid.UUID + Interval time.Duration + Regions []string +} + +// Upsert schedules m in its regions and removes it from others it was in. +// A monitor new to a region runs right away; an existing schedule keeps its +// phase so edits do not cause bursts. +func (s *Scheduler) Upsert(ctx context.Context, m Monitor, previousRegions []string) error { + now := s.now().UnixMilli() + id := m.ID.String() + _, err := s.rdb.TxPipelined(ctx, func(p redis.Pipeliner) error { + p.HSet(ctx, keyIntervals, id, int64(m.Interval/time.Millisecond)) + keep := map[string]bool{} + for _, r := range m.Regions { + keep[r] = true + p.SAdd(ctx, keyRegions, r) + p.ZAddNX(ctx, keyDue(r), redis.Z{Score: float64(now), Member: id}) + } + for _, r := range previousRegions { + if !keep[r] { + p.ZRem(ctx, keyDue(r), id) + } + } + return nil + }) + return err +} + +// Remove unschedules a monitor from regions. Runs already queued for an +// instance are dropped at dispatch or job resolution. +func (s *Scheduler) Remove(ctx context.Context, id uuid.UUID, regions []string) error { + _, err := s.rdb.TxPipelined(ctx, func(p redis.Pipeliner) error { + p.HDel(ctx, keyIntervals, id.String()) + for _, r := range regions { + p.ZRem(ctx, keyDue(r), id.String()) + } + return nil + }) + return err +} + +// Reconcile makes Redis match want, the full set of enabled monitors. It +// repairs drift after a Redis failover or a missed update and is safe to run +// from several replicas. +func (s *Scheduler) Reconcile(ctx context.Context, want []Monitor) error { + byRegion := map[string]map[string]bool{} + for _, m := range want { + if err := s.Upsert(ctx, m, nil); err != nil { + return err + } + for _, r := range m.Regions { + if byRegion[r] == nil { + byRegion[r] = map[string]bool{} + } + byRegion[r][m.ID.String()] = true + } + } + wanted := map[string]bool{} + for _, m := range want { + wanted[m.ID.String()] = true + } + ids, err := s.rdb.HKeys(ctx, keyIntervals).Result() + if err != nil { + return err + } + for _, id := range ids { + if !wanted[id] { + s.rdb.HDel(ctx, keyIntervals, id) + } + } + regions, err := s.rdb.SMembers(ctx, keyRegions).Result() + if err != nil { + return err + } + for _, r := range regions { + members, err := s.rdb.ZRange(ctx, keyDue(r), 0, -1).Result() + if err != nil { + return err + } + for _, id := range members { + if !byRegion[r][id] { + s.rdb.ZRem(ctx, keyDue(r), id) + } + } + } + return nil +} + +// Heartbeat records that instance of region is alive. +func (s *Scheduler) Heartbeat(ctx context.Context, region string, instance uuid.UUID) error { + return s.rdb.ZAdd(ctx, keyInstances(region), redis.Z{Score: float64(s.now().UnixMilli()), Member: instance.String()}).Err() +} + +// dispatchScript runs per region. +// +// KEYS: due set, instance set, interval hash. +// ARGV: now ms, stale-before ms, batch limit, job queue prefix, queue TTL s. +var dispatchScript = redis.NewScript(` +local now = tonumber(ARGV[1]) +for _, inst in ipairs(redis.call('ZRANGEBYSCORE', KEYS[2], '-inf', ARGV[2])) do + local q = ARGV[4] .. inst + for _, job in ipairs(redis.call('LRANGE', q, 0, -1)) do + local m = string.sub(job, 1, string.find(job, '|', 1, true) - 1) + if redis.call('HEXISTS', KEYS[3], m) == 1 then + redis.call('ZADD', KEYS[1], 'LT', now, m) + end + end + redis.call('DEL', q) + redis.call('ZREM', KEYS[2], inst) +end +local live = redis.call('ZRANGE', KEYS[2], 0, -1) +if #live == 0 then return 0 end +local due = redis.call('ZRANGEBYSCORE', KEYS[1], '-inf', now, 'WITHSCORES', 'LIMIT', 0, ARGV[3]) +local n = 0 +for i = 1, #due, 2 do + local m, at = due[i], tonumber(due[i + 1]) + local interval = tonumber(redis.call('HGET', KEYS[3], m)) + if interval == nil then + redis.call('ZREM', KEYS[1], m) + else + local q = ARGV[4] .. live[math.random(#live)] + redis.call('RPUSH', q, m .. '|' .. string.format('%.0f', at)) + redis.call('EXPIRE', q, ARGV[5]) + local nxt = at + interval + if nxt <= now then nxt = now + interval end + redis.call('ZADD', KEYS[1], nxt, m) + n = n + 1 + end +end +return n +`) + +// Dispatch hands due runs of every region to random live instances and +// returns how many it dispatched. +func (s *Scheduler) Dispatch(ctx context.Context) (int, error) { + regions, err := s.rdb.SMembers(ctx, keyRegions).Result() + if err != nil { + return 0, err + } + now := s.now() + total := 0 + for _, r := range regions { + n, err := dispatchScript.Run(ctx, s.rdb, + []string{keyDue(r), keyInstances(r), keyIntervals}, + now.UnixMilli(), now.Add(-StaleAfter).UnixMilli(), 1000, jobsPrefix, int(jobsTTL.Seconds()), + ).Int() + if err != nil { + return total, fmt.Errorf("schedule: dispatch %s: %w", r, err) + } + total += n + } + return total, nil +} + +// Take pops up to max queued runs for instance, waiting up to wait for the +// first one. It returns within about a second once ctx is done, so long polls +// do not hold up shutdown or cancelled requests. +func (s *Scheduler) Take(ctx context.Context, instance uuid.UUID, max int, wait time.Duration) ([]Entry, error) { + if max <= 0 { + return nil, nil + } + q := jobsPrefix + instance.String() + raw, err := s.rdb.LPopCount(ctx, q, max).Result() + if err != nil && !errors.Is(err, redis.Nil) { + return nil, err + } + deadline := time.Now().Add(wait) + for len(raw) == 0 && ctx.Err() == nil { + left := time.Until(deadline) + if left <= 0 { + 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() + if errors.Is(err, redis.Nil) { + continue + } + if err != nil { + return nil, err + } + raw = []string{first[1]} + if max > 1 { + more, err := s.rdb.LPopCount(ctx, q, max-1).Result() + if err != nil && !errors.Is(err, redis.Nil) { + return nil, err + } + raw = append(raw, more...) + } + } + out := make([]Entry, 0, len(raw)) + for _, r := range raw { + if e, ok := parseEntry(r); ok { + out = append(out, e) + } + } + return out, nil +} + +// 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, + // which keeps that logic in one place. + if err := s.rdb.ZAdd(ctx, keyInstances(region), redis.Z{Score: 0, Member: instance.String()}).Err(); err != nil { + return err + } + _, err := s.Dispatch(ctx) + return err +} + +// Instances returns the live instance count per region. +func (s *Scheduler) Instances(ctx context.Context, region string) (int64, error) { + min := strconv.FormatInt(s.now().Add(-StaleAfter).UnixMilli(), 10) + return s.rdb.ZCount(ctx, keyInstances(region), min, "+inf").Result() +} + +func parseEntry(s string) (Entry, bool) { + id, at, ok := strings.Cut(s, "|") + if !ok { + return Entry{}, false + } + mid, err := uuid.Parse(id) + if err != nil { + return Entry{}, false + } + ms, err := strconv.ParseFloat(at, 64) + if err != nil { + return Entry{}, false + } + return Entry{MonitorID: mid, ScheduledAt: time.UnixMilli(int64(ms))}, true +} diff --git a/internal/schedule/schedule_test.go b/internal/schedule/schedule_test.go new file mode 100644 index 0000000..c6a0112 --- /dev/null +++ b/internal/schedule/schedule_test.go @@ -0,0 +1,205 @@ +package schedule + +import ( + "context" + "os" + "testing" + "time" + + "github.com/google/uuid" + "github.com/redis/go-redis/v9" +) + +func newTest(t *testing.T) (*Scheduler, *time.Time) { + t.Helper() + url := os.Getenv("UPTIME_TEST_REDIS_URL") + if url == "" { + t.Skip("UPTIME_TEST_REDIS_URL not set") + } + opts, err := redis.ParseURL(url) + if err != nil { + t.Fatal(err) + } + rdb := redis.NewClient(opts) + t.Cleanup(func() { _ = rdb.Close() }) + if err := rdb.FlushDB(context.Background()).Err(); err != nil { + t.Fatal(err) + } + now := time.UnixMilli(1_800_000_000_000) + s := New(rdb) + s.now = func() time.Time { return now } + return s, &now +} + +func takeAll(t *testing.T, s *Scheduler, inst uuid.UUID) []Entry { + t.Helper() + e, err := s.Take(context.Background(), inst, 1000, 0) + if err != nil { + t.Fatalf("Take() failed: %v", err) + } + return e +} + +func mustDispatch(t *testing.T, s *Scheduler) int { + t.Helper() + n, err := s.Dispatch(context.Background()) + if err != nil { + t.Fatalf("Dispatch() failed: %v", err) + } + return n +} + +// TestDispatchSpreadsRandomly runs many monitors against three instances of +// one region and expects every instance to get a substantial share. +func TestDispatchSpreadsRandomly(t *testing.T) { + s, _ := newTest(t) + ctx := context.Background() + insts := []uuid.UUID{uuid.New(), uuid.New(), uuid.New()} + for _, in := range insts { + if err := s.Heartbeat(ctx, "eu", in); err != nil { + t.Fatal(err) + } + } + const monitors = 600 + for range monitors { + if err := s.Upsert(ctx, Monitor{ID: uuid.New(), Interval: time.Minute, Regions: []string{"eu"}}, nil); err != nil { + t.Fatal(err) + } + } + if n := mustDispatch(t, s); n != monitors { + t.Fatalf("Dispatch() = %d, want %d", n, monitors) + } + total := 0 + for _, in := range insts { + got := len(takeAll(t, s, in)) + total += got + if got < monitors/3-80 || got > monitors/3+80 { + t.Errorf("instance received %d of %d jobs, want about %d", got, monitors, monitors/3) + } + } + if total != monitors { + t.Errorf("instances received %d jobs, want %d", total, monitors) + } +} + +func TestDispatchReschedulesAndKeepsRegionsApart(t *testing.T) { + s, now := newTest(t) + ctx := context.Background() + eu, us := uuid.New(), uuid.New() + _ = s.Heartbeat(ctx, "eu", eu) + _ = s.Heartbeat(ctx, "us", us) + m := Monitor{ID: uuid.New(), Interval: 30 * time.Second, Regions: []string{"eu", "us"}} + _ = s.Upsert(ctx, m, nil) + + mustDispatch(t, s) + for _, in := range []uuid.UUID{eu, us} { + if got := takeAll(t, s, in); len(got) != 1 || got[0].MonitorID != m.ID || !got[0].ScheduledAt.Equal(*now) { + t.Errorf("instance jobs = %+v, want one run of %v at %v", got, m.ID, *now) + } + } + if n := mustDispatch(t, s); n != 0 { + t.Errorf("Dispatch() before next interval = %d, want 0", n) + } + *now = now.Add(30 * time.Second) + _ = s.Heartbeat(ctx, "eu", eu) + _ = s.Heartbeat(ctx, "us", us) + if n := mustDispatch(t, s); n != 2 { + t.Errorf("Dispatch() after interval = %d, want 2", n) + } + + // Leaving a region stops runs there. + _ = s.Upsert(ctx, Monitor{ID: m.ID, Interval: m.Interval, Regions: []string{"eu"}}, m.Regions) + takeAll(t, s, eu) + takeAll(t, s, us) + *now = now.Add(30 * time.Second) + _ = s.Heartbeat(ctx, "eu", eu) + _ = s.Heartbeat(ctx, "us", us) + mustDispatch(t, s) + if got := takeAll(t, s, us); len(got) != 0 { + t.Errorf("us instance got %d jobs after region removal, want 0", len(got)) + } +} + +func TestStaleInstanceJobsMoveToLiveOne(t *testing.T) { + s, now := newTest(t) + ctx := context.Background() + dead, alive := uuid.New(), uuid.New() + _ = s.Heartbeat(ctx, "eu", dead) + m := Monitor{ID: uuid.New(), Interval: time.Hour, Regions: []string{"eu"}} + _ = s.Upsert(ctx, m, nil) + mustDispatch(t, s) + + *now = now.Add(StaleAfter + time.Second) + _ = s.Heartbeat(ctx, "eu", alive) + mustDispatch(t, s) + got := takeAll(t, s, alive) + if len(got) != 1 || got[0].MonitorID != m.ID { + t.Errorf("live instance jobs = %+v, want the stale instance's run", got) + } + if n, _ := s.Instances(ctx, "eu"); n != 1 { + t.Errorf("Instances() = %d, want 1", n) + } +} + +func TestReleaseHandsJobsOver(t *testing.T) { + s, _ := newTest(t) + ctx := context.Background() + leaving, staying := uuid.New(), uuid.New() + _ = s.Heartbeat(ctx, "eu", leaving) + m := Monitor{ID: uuid.New(), Interval: time.Hour, Regions: []string{"eu"}} + _ = s.Upsert(ctx, m, nil) + mustDispatch(t, s) + _ = s.Heartbeat(ctx, "eu", staying) + + if err := s.Release(ctx, "eu", leaving); err != nil { + t.Fatal(err) + } + if got := takeAll(t, s, staying); len(got) != 1 { + t.Errorf("staying instance got %d jobs, want 1", len(got)) + } +} + +func TestRemoveAndReconcile(t *testing.T) { + s, _ := newTest(t) + ctx := context.Background() + in := uuid.New() + _ = s.Heartbeat(ctx, "eu", in) + keep := Monitor{ID: uuid.New(), Interval: time.Minute, Regions: []string{"eu"}} + gone := Monitor{ID: uuid.New(), Interval: time.Minute, Regions: []string{"eu"}} + _ = s.Upsert(ctx, keep, nil) + _ = s.Upsert(ctx, gone, nil) + + if err := s.Reconcile(ctx, []Monitor{keep}); err != nil { + t.Fatal(err) + } + mustDispatch(t, s) + got := takeAll(t, s, in) + if len(got) != 1 || got[0].MonitorID != keep.ID { + t.Errorf("jobs after Reconcile = %+v, want only %v", got, keep.ID) + } +} + +func TestTakeWaits(t *testing.T) { + s, _ := newTest(t) + ctx := context.Background() + in := uuid.New() + start := time.Now() + got, err := s.Take(ctx, in, 10, 300*time.Millisecond) + 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 { + t.Errorf("Take() returned after %v, want it to wait about 300ms", waited) + } +} + +func TestTakeReturnsWhenCancelled(t *testing.T) { + s, _ := newTest(t) + ctx, cancel := context.WithCancel(context.Background()) + go func() { time.Sleep(100 * time.Millisecond); cancel() }() + start := time.Now() + _, _ = s.Take(ctx, uuid.New(), 10, 20*time.Second) + if took := time.Since(start); took > 2*time.Second { + t.Errorf("Take() returned %v after cancellation, want within about a second", took) + } +} diff --git a/internal/sso/httpclient.go b/internal/sso/httpclient.go index c132918..069d24b 100644 --- a/internal/sso/httpclient.go +++ b/internal/sso/httpclient.go @@ -2,35 +2,21 @@ package sso import ( "context" - "errors" "net" "net/http" - "net/netip" - "syscall" "time" + + "git.zb-server.de/ZB-Server/uptimesebi/internal/netguard" ) // ErrForbiddenAddress is returned when an IdP resolves to an address the // client may not contact. -var ErrForbiddenAddress = errors.New("sso: issuer resolves to a non-public address") - -var cgnat = netip.MustParsePrefix("100.64.0.0/10") +var ErrForbiddenAddress = netguard.ErrForbiddenAddress // SafeHTTPClient returns a client for talking to customer-configured IdPs. -// Unless allowPrivate is set it refuses to connect to loopback, private, -// link-local and similar ranges. The check runs on the resolved address at -// dial time, so DNS rebinding and redirects cannot bypass it. +// Unless allowPrivate is set it refuses to connect to non-public addresses. func SafeHTTPClient(allowPrivate bool) *http.Client { - d := &net.Dialer{Timeout: 5 * time.Second} - if !allowPrivate { - d.Control = func(_, address string, _ syscall.RawConn) error { - ap, err := netip.ParseAddrPort(address) - if err != nil || !isPublic(ap.Addr()) { - return ErrForbiddenAddress - } - return nil - } - } + d := netguard.Dialer(allowPrivate, 5*time.Second) tr := http.DefaultTransport.(*http.Transport).Clone() tr.Proxy = nil tr.DialContext = func(ctx context.Context, network, addr string) (net.Conn, error) { @@ -38,8 +24,3 @@ func SafeHTTPClient(allowPrivate bool) *http.Client { } return &http.Client{Transport: tr, Timeout: 10 * time.Second} } - -func isPublic(a netip.Addr) bool { - a = a.Unmap() - return a.IsGlobalUnicast() && !a.IsPrivate() && !cgnat.Contains(a) -} diff --git a/internal/sso/httpclient_test.go b/internal/sso/httpclient_test.go index 226344d..11712e2 100644 --- a/internal/sso/httpclient_test.go +++ b/internal/sso/httpclient_test.go @@ -4,33 +4,9 @@ import ( "errors" "net/http" "net/http/httptest" - "net/netip" "testing" ) -func TestIsPublic(t *testing.T) { - tests := map[string]bool{ - "8.8.8.8": true, - "2606:4700::1111": true, - "127.0.0.1": false, - "10.1.2.3": false, - "172.16.0.1": false, - "192.168.1.1": false, - "169.254.169.254": false, - "100.64.0.1": false, - "0.0.0.0": false, - "::1": false, - "fd00::1": false, - "fe80::1": false, - "::ffff:127.0.0.1": false, - } - for addr, want := range tests { - if got := isPublic(netip.MustParseAddr(addr)); got != want { - t.Errorf("isPublic(%s) = %t, want %t", addr, got, want) - } - } -} - func TestSafeHTTPClientBlocksLoopback(t *testing.T) { srv := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {})) defer srv.Close() diff --git a/internal/store/agents.sql.go b/internal/store/agents.sql.go new file mode 100644 index 0000000..c2fd43a --- /dev/null +++ b/internal/store/agents.sql.go @@ -0,0 +1,179 @@ +// Code generated by sqlc. DO NOT EDIT. +// versions: +// sqlc v1.31.1 +// source: agents.sql + +package store + +import ( + "context" + + "github.com/google/uuid" +) + +const createAgent = `-- name: CreateAgent :one +INSERT INTO agents (org_id, kind, name, region, token_hash, prefix) +VALUES ($1, $2, $3, $4, $5, $6) +RETURNING id, org_id, kind, name, region, token_hash, prefix, last_seen_at, release, created_at +` + +type CreateAgentParams struct { + OrgID *uuid.UUID + Kind string + Name string + Region *string + TokenHash []byte + Prefix string +} + +func (q *Queries) CreateAgent(ctx context.Context, arg CreateAgentParams) (Agent, error) { + row := q.db.QueryRow(ctx, createAgent, + arg.OrgID, + arg.Kind, + arg.Name, + arg.Region, + arg.TokenHash, + arg.Prefix, + ) + var i Agent + err := row.Scan( + &i.ID, + &i.OrgID, + &i.Kind, + &i.Name, + &i.Region, + &i.TokenHash, + &i.Prefix, + &i.LastSeenAt, + &i.Release, + &i.CreatedAt, + ) + return i, err +} + +const deleteAgent = `-- name: DeleteAgent :execrows +DELETE FROM agents WHERE id = $1 +` + +func (q *Queries) DeleteAgent(ctx context.Context, id uuid.UUID) (int64, error) { + result, err := q.db.Exec(ctx, deleteAgent, id) + if err != nil { + return 0, err + } + return result.RowsAffected(), nil +} + +const getAgentByHash = `-- name: GetAgentByHash :one +SELECT id, org_id, kind, name, region, token_hash, prefix, last_seen_at, release, created_at FROM agents WHERE token_hash = $1 +` + +func (q *Queries) GetAgentByHash(ctx context.Context, tokenHash []byte) (Agent, error) { + row := q.db.QueryRow(ctx, getAgentByHash, tokenHash) + var i Agent + err := row.Scan( + &i.ID, + &i.OrgID, + &i.Kind, + &i.Name, + &i.Region, + &i.TokenHash, + &i.Prefix, + &i.LastSeenAt, + &i.Release, + &i.CreatedAt, + ) + return i, err +} + +const listAgents = `-- name: ListAgents :many +SELECT id, org_id, kind, name, region, token_hash, prefix, last_seen_at, release, created_at FROM agents ORDER BY kind, region, name +` + +func (q *Queries) ListAgents(ctx context.Context) ([]Agent, error) { + rows, err := q.db.Query(ctx, listAgents) + if err != nil { + return nil, err + } + defer rows.Close() + items := []Agent{} + for rows.Next() { + var i Agent + if err := rows.Scan( + &i.ID, + &i.OrgID, + &i.Kind, + &i.Name, + &i.Region, + &i.TokenHash, + &i.Prefix, + &i.LastSeenAt, + &i.Release, + &i.CreatedAt, + ); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} + +const listRegions = `-- name: ListRegions :many +SELECT key, name, created_at FROM regions ORDER BY key +` + +func (q *Queries) ListRegions(ctx context.Context) ([]Region, error) { + rows, err := q.db.Query(ctx, listRegions) + if err != nil { + return nil, err + } + defer rows.Close() + items := []Region{} + for rows.Next() { + var i Region + if err := rows.Scan(&i.Key, &i.Name, &i.CreatedAt); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} + +const touchAgent = `-- name: TouchAgent :exec +UPDATE agents SET last_seen_at = now(), release = $2 +WHERE id = $1 AND (last_seen_at IS NULL OR last_seen_at < now() - interval '30 seconds' OR release IS DISTINCT FROM $2) +` + +type TouchAgentParams struct { + ID uuid.UUID + Release *string +} + +func (q *Queries) TouchAgent(ctx context.Context, arg TouchAgentParams) error { + _, err := q.db.Exec(ctx, touchAgent, arg.ID, arg.Release) + return err +} + +const upsertRegion = `-- name: UpsertRegion :one +INSERT INTO regions (key, name) VALUES ($1, coalesce(nullif($2::text, ''), $1)) +ON CONFLICT (key) DO UPDATE SET name = CASE WHEN $2::text = '' THEN regions.name ELSE EXCLUDED.name END +RETURNING key, name, created_at +` + +type UpsertRegionParams struct { + Key string + Name string +} + +// An empty name names a new region after its key and keeps an existing name. +func (q *Queries) UpsertRegion(ctx context.Context, arg UpsertRegionParams) (Region, error) { + row := q.db.QueryRow(ctx, upsertRegion, arg.Key, arg.Name) + var i Region + err := row.Scan(&i.Key, &i.Name, &i.CreatedAt) + return i, err +} diff --git a/internal/store/check_results.sql.go b/internal/store/check_results.sql.go new file mode 100644 index 0000000..ffceffb --- /dev/null +++ b/internal/store/check_results.sql.go @@ -0,0 +1,161 @@ +// Code generated by sqlc. DO NOT EDIT. +// versions: +// sqlc v1.31.1 +// source: check_results.sql + +package store + +import ( + "context" + "time" + + "github.com/google/uuid" +) + +type InsertCheckResultsParams struct { + Time time.Time + OrgID uuid.UUID + MonitorID uuid.UUID + Region string + CheckerID uuid.UUID + Ok bool + LatencyMs *int32 + StatusCode *int32 + Error *string +} + +const latestResults = `-- name: LatestResults :many +SELECT DISTINCT ON (monitor_id, region) monitor_id, region, time, ok, latency_ms, status_code, error +FROM check_results +WHERE org_id = $1 AND time > now() - interval '1 day' +ORDER BY monitor_id, region, time DESC +` + +type LatestResultsRow struct { + MonitorID uuid.UUID + Region string + Time time.Time + Ok bool + LatencyMs *int32 + StatusCode *int32 + Error *string +} + +// Newest result per monitor and region in the org. +func (q *Queries) LatestResults(ctx context.Context, orgID uuid.UUID) ([]LatestResultsRow, error) { + rows, err := q.db.Query(ctx, latestResults, orgID) + if err != nil { + return nil, err + } + defer rows.Close() + items := []LatestResultsRow{} + for rows.Next() { + var i LatestResultsRow + if err := rows.Scan( + &i.MonitorID, + &i.Region, + &i.Time, + &i.Ok, + &i.LatencyMs, + &i.StatusCode, + &i.Error, + ); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} + +const recentResults = `-- name: RecentResults :many +SELECT time, region, ok, latency_ms, status_code, error +FROM check_results +WHERE org_id = $1 AND monitor_id = $2 AND time > $3 +ORDER BY time DESC +LIMIT 500 +` + +type RecentResultsParams struct { + OrgID uuid.UUID + MonitorID uuid.UUID + Time time.Time +} + +type RecentResultsRow struct { + Time time.Time + Region string + Ok bool + LatencyMs *int32 + StatusCode *int32 + Error *string +} + +func (q *Queries) RecentResults(ctx context.Context, arg RecentResultsParams) ([]RecentResultsRow, error) { + rows, err := q.db.Query(ctx, recentResults, arg.OrgID, arg.MonitorID, arg.Time) + if err != nil { + return nil, err + } + defer rows.Close() + items := []RecentResultsRow{} + for rows.Next() { + var i RecentResultsRow + if err := rows.Scan( + &i.Time, + &i.Region, + &i.Ok, + &i.LatencyMs, + &i.StatusCode, + &i.Error, + ); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} + +const uptimeSince = `-- name: UptimeSince :many +SELECT monitor_id, sum(total)::bigint AS total, sum(ok_count)::bigint AS ok_count +FROM check_results_1h +WHERE org_id = $1 AND bucket >= $2 +GROUP BY monitor_id +` + +type UptimeSinceParams struct { + OrgID uuid.UUID + Bucket interface{} +} + +type UptimeSinceRow struct { + MonitorID uuid.UUID + Total int64 + OkCount int64 +} + +// Uptime per monitor from the hourly aggregate, including the not yet +// materialized most recent hours (real-time aggregation). +func (q *Queries) UptimeSince(ctx context.Context, arg UptimeSinceParams) ([]UptimeSinceRow, error) { + rows, err := q.db.Query(ctx, uptimeSince, arg.OrgID, arg.Bucket) + if err != nil { + return nil, err + } + defer rows.Close() + items := []UptimeSinceRow{} + for rows.Next() { + var i UptimeSinceRow + if err := rows.Scan(&i.MonitorID, &i.Total, &i.OkCount); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} diff --git a/internal/store/copyfrom.go b/internal/store/copyfrom.go index d60d6fd..bf2d682 100644 --- a/internal/store/copyfrom.go +++ b/internal/store/copyfrom.go @@ -9,6 +9,48 @@ import ( "context" ) +// iteratorForInsertCheckResults implements pgx.CopyFromSource. +type iteratorForInsertCheckResults struct { + rows []InsertCheckResultsParams + skippedFirstNextCall bool +} + +func (r *iteratorForInsertCheckResults) Next() bool { + if len(r.rows) == 0 { + return false + } + if !r.skippedFirstNextCall { + r.skippedFirstNextCall = true + return true + } + r.rows = r.rows[1:] + return len(r.rows) > 0 +} + +func (r iteratorForInsertCheckResults) Values() ([]interface{}, error) { + return []interface{}{ + r.rows[0].Time, + r.rows[0].OrgID, + r.rows[0].MonitorID, + r.rows[0].Region, + r.rows[0].CheckerID, + r.rows[0].Ok, + r.rows[0].LatencyMs, + r.rows[0].StatusCode, + r.rows[0].Error, + }, nil +} + +func (r iteratorForInsertCheckResults) Err() error { + return nil +} + +// check_results and its aggregates have no row-level security (see +// migration 00013). Every query here must filter by org_id. +func (q *Queries) InsertCheckResults(ctx context.Context, arg []InsertCheckResultsParams) (int64, error) { + return q.db.CopyFrom(ctx, []string{"check_results"}, []string{"time", "org_id", "monitor_id", "region", "checker_id", "ok", "latency_ms", "status_code", "error"}, &iteratorForInsertCheckResults{rows: arg}) +} + // iteratorForInsertRecoveryCodes implements pgx.CopyFromSource. type iteratorForInsertRecoveryCodes struct { rows []InsertRecoveryCodesParams diff --git a/internal/store/models.go b/internal/store/models.go index 1afa83b..23c7587 100644 --- a/internal/store/models.go +++ b/internal/store/models.go @@ -10,6 +10,19 @@ import ( "github.com/google/uuid" ) +type Agent struct { + ID uuid.UUID + OrgID *uuid.UUID + Kind string + Name string + Region *string + TokenHash []byte + Prefix string + LastSeenAt *time.Time + Release *string + CreatedAt time.Time +} + type ApiToken struct { ID uuid.UUID OrgID uuid.UUID @@ -23,6 +36,40 @@ type ApiToken struct { CreatedAt time.Time } +type CheckResult struct { + Time time.Time + OrgID uuid.UUID + MonitorID uuid.UUID + Region string + CheckerID uuid.UUID + Ok bool + LatencyMs *int32 + StatusCode *int32 + Error *string +} + +type CheckResults1d struct { + Bucket interface{} + OrgID uuid.UUID + MonitorID uuid.UUID + Region string + Total int64 + OkCount int64 + AvgLatencyMs float32 + MaxLatencyMs interface{} +} + +type CheckResults1h struct { + Bucket interface{} + OrgID uuid.UUID + MonitorID uuid.UUID + Region string + Total int64 + OkCount int64 + AvgLatencyMs float32 + MaxLatencyMs interface{} +} + type Invitation struct { ID uuid.UUID OrgID uuid.UUID @@ -42,6 +89,26 @@ type Membership struct { CreatedAt time.Time } +type Monitor struct { + ID uuid.UUID + OrgID uuid.UUID + Name string + Type string + Target string + IntervalSeconds int32 + TimeoutMs int32 + Config []byte + Enabled bool + CreatedAt time.Time + UpdatedAt time.Time +} + +type MonitorRegion struct { + MonitorID uuid.UUID + OrgID uuid.UUID + Region string +} + type Org struct { ID uuid.UUID Slug string @@ -60,6 +127,12 @@ type RecoveryCode struct { CreatedAt time.Time } +type Region struct { + Key string + Name string + CreatedAt time.Time +} + type Role struct { ID uuid.UUID OrgID *uuid.UUID diff --git a/internal/store/monitors.sql.go b/internal/store/monitors.sql.go new file mode 100644 index 0000000..6161932 --- /dev/null +++ b/internal/store/monitors.sql.go @@ -0,0 +1,332 @@ +// Code generated by sqlc. DO NOT EDIT. +// versions: +// sqlc v1.31.1 +// source: monitors.sql + +package store + +import ( + "context" + + "github.com/google/uuid" +) + +const addMonitorRegion = `-- name: AddMonitorRegion :exec +INSERT INTO monitor_regions (monitor_id, org_id, region) VALUES ($1, $2, $3) +` + +type AddMonitorRegionParams struct { + MonitorID uuid.UUID + OrgID uuid.UUID + Region string +} + +func (q *Queries) AddMonitorRegion(ctx context.Context, arg AddMonitorRegionParams) error { + _, err := q.db.Exec(ctx, addMonitorRegion, arg.MonitorID, arg.OrgID, arg.Region) + return err +} + +const allMonitorRegions = `-- name: AllMonitorRegions :many +SELECT monitor_id, region FROM monitor_regions +` + +type AllMonitorRegionsRow struct { + MonitorID uuid.UUID + Region string +} + +func (q *Queries) AllMonitorRegions(ctx context.Context) ([]AllMonitorRegionsRow, error) { + rows, err := q.db.Query(ctx, allMonitorRegions) + if err != nil { + return nil, err + } + defer rows.Close() + items := []AllMonitorRegionsRow{} + for rows.Next() { + var i AllMonitorRegionsRow + if err := rows.Scan(&i.MonitorID, &i.Region); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} + +const createMonitor = `-- name: CreateMonitor :one +INSERT INTO monitors (org_id, name, type, target, interval_seconds, timeout_ms, config, enabled) +VALUES ($1, $2, $3, $4, $5, $6, $7, $8) +RETURNING id, org_id, name, type, target, interval_seconds, timeout_ms, config, enabled, created_at, updated_at +` + +type CreateMonitorParams struct { + OrgID uuid.UUID + Name string + Type string + Target string + IntervalSeconds int32 + TimeoutMs int32 + Config []byte + Enabled bool +} + +func (q *Queries) CreateMonitor(ctx context.Context, arg CreateMonitorParams) (Monitor, error) { + row := q.db.QueryRow(ctx, createMonitor, + arg.OrgID, + arg.Name, + arg.Type, + arg.Target, + arg.IntervalSeconds, + arg.TimeoutMs, + arg.Config, + arg.Enabled, + ) + var i Monitor + err := row.Scan( + &i.ID, + &i.OrgID, + &i.Name, + &i.Type, + &i.Target, + &i.IntervalSeconds, + &i.TimeoutMs, + &i.Config, + &i.Enabled, + &i.CreatedAt, + &i.UpdatedAt, + ) + return i, err +} + +const deleteMonitor = `-- name: DeleteMonitor :execrows +DELETE FROM monitors WHERE id = $1 +` + +func (q *Queries) DeleteMonitor(ctx context.Context, id uuid.UUID) (int64, error) { + result, err := q.db.Exec(ctx, deleteMonitor, id) + if err != nil { + return 0, err + } + return result.RowsAffected(), nil +} + +const deleteMonitorRegions = `-- name: DeleteMonitorRegions :exec +DELETE FROM monitor_regions WHERE monitor_id = $1 +` + +func (q *Queries) DeleteMonitorRegions(ctx context.Context, monitorID uuid.UUID) error { + _, err := q.db.Exec(ctx, deleteMonitorRegions, monitorID) + return err +} + +const getMonitor = `-- name: GetMonitor :one +SELECT id, org_id, name, type, target, interval_seconds, timeout_ms, config, enabled, created_at, updated_at FROM monitors WHERE id = $1 +` + +func (q *Queries) GetMonitor(ctx context.Context, id uuid.UUID) (Monitor, error) { + row := q.db.QueryRow(ctx, getMonitor, id) + var i Monitor + err := row.Scan( + &i.ID, + &i.OrgID, + &i.Name, + &i.Type, + &i.Target, + &i.IntervalSeconds, + &i.TimeoutMs, + &i.Config, + &i.Enabled, + &i.CreatedAt, + &i.UpdatedAt, + ) + return i, err +} + +const listEnabledMonitorsForSchedule = `-- name: ListEnabledMonitorsForSchedule :many +SELECT m.id, m.interval_seconds, array_agg(r.region ORDER BY r.region)::text[] AS regions +FROM monitors m +JOIN monitor_regions r ON r.monitor_id = m.id +WHERE m.enabled +GROUP BY m.id, m.interval_seconds +` + +type ListEnabledMonitorsForScheduleRow struct { + ID uuid.UUID + IntervalSeconds int32 + Regions []string +} + +// System scope: every enabled monitor with its regions, for reconciling the +// schedule. +func (q *Queries) ListEnabledMonitorsForSchedule(ctx context.Context) ([]ListEnabledMonitorsForScheduleRow, error) { + rows, err := q.db.Query(ctx, listEnabledMonitorsForSchedule) + if err != nil { + return nil, err + } + defer rows.Close() + items := []ListEnabledMonitorsForScheduleRow{} + for rows.Next() { + var i ListEnabledMonitorsForScheduleRow + if err := rows.Scan(&i.ID, &i.IntervalSeconds, &i.Regions); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} + +const listMonitors = `-- name: ListMonitors :many +SELECT id, org_id, name, type, target, interval_seconds, timeout_ms, config, enabled, created_at, updated_at FROM monitors ORDER BY name +` + +func (q *Queries) ListMonitors(ctx context.Context) ([]Monitor, error) { + rows, err := q.db.Query(ctx, listMonitors) + if err != nil { + return nil, err + } + defer rows.Close() + items := []Monitor{} + for rows.Next() { + var i Monitor + if err := rows.Scan( + &i.ID, + &i.OrgID, + &i.Name, + &i.Type, + &i.Target, + &i.IntervalSeconds, + &i.TimeoutMs, + &i.Config, + &i.Enabled, + &i.CreatedAt, + &i.UpdatedAt, + ); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} + +const monitorRegions = `-- name: MonitorRegions :many +SELECT region FROM monitor_regions WHERE monitor_id = $1 ORDER BY region +` + +func (q *Queries) MonitorRegions(ctx context.Context, monitorID uuid.UUID) ([]string, error) { + rows, err := q.db.Query(ctx, monitorRegions, monitorID) + if err != nil { + return nil, err + } + defer rows.Close() + items := []string{} + for rows.Next() { + var region string + if err := rows.Scan(®ion); err != nil { + return nil, err + } + items = append(items, region) + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} + +const monitorsForJobs = `-- name: MonitorsForJobs :many +SELECT m.id, m.org_id, m.name, m.type, m.target, m.interval_seconds, m.timeout_ms, m.config, m.enabled, m.created_at, m.updated_at FROM monitors m +JOIN monitor_regions r ON r.monitor_id = m.id AND r.region = $1 +WHERE m.id = ANY ($2::uuid[]) AND m.enabled +` + +type MonitorsForJobsParams struct { + Region string + Ids []uuid.UUID +} + +// System scope: monitors to hand to a checker of region, skipping ones that +// were disabled, deleted or moved out of the region since dispatch. +func (q *Queries) MonitorsForJobs(ctx context.Context, arg MonitorsForJobsParams) ([]Monitor, error) { + rows, err := q.db.Query(ctx, monitorsForJobs, arg.Region, arg.Ids) + if err != nil { + return nil, err + } + defer rows.Close() + items := []Monitor{} + for rows.Next() { + var i Monitor + if err := rows.Scan( + &i.ID, + &i.OrgID, + &i.Name, + &i.Type, + &i.Target, + &i.IntervalSeconds, + &i.TimeoutMs, + &i.Config, + &i.Enabled, + &i.CreatedAt, + &i.UpdatedAt, + ); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} + +const updateMonitor = `-- name: UpdateMonitor :one +UPDATE monitors SET name = $2, type = $3, target = $4, interval_seconds = $5, + timeout_ms = $6, config = $7, enabled = $8, updated_at = now() +WHERE id = $1 +RETURNING id, org_id, name, type, target, interval_seconds, timeout_ms, config, enabled, created_at, updated_at +` + +type UpdateMonitorParams struct { + ID uuid.UUID + Name string + Type string + Target string + IntervalSeconds int32 + TimeoutMs int32 + Config []byte + Enabled bool +} + +func (q *Queries) UpdateMonitor(ctx context.Context, arg UpdateMonitorParams) (Monitor, error) { + row := q.db.QueryRow(ctx, updateMonitor, + arg.ID, + arg.Name, + arg.Type, + arg.Target, + arg.IntervalSeconds, + arg.TimeoutMs, + arg.Config, + arg.Enabled, + ) + var i Monitor + err := row.Scan( + &i.ID, + &i.OrgID, + &i.Name, + &i.Type, + &i.Target, + &i.IntervalSeconds, + &i.TimeoutMs, + &i.Config, + &i.Enabled, + &i.CreatedAt, + &i.UpdatedAt, + ) + return i, err +} diff --git a/internal/store/querier.go b/internal/store/querier.go index b88cd25..e885093 100644 --- a/internal/store/querier.go +++ b/internal/store/querier.go @@ -13,22 +13,29 @@ import ( type Querier interface { APITokenOrg(ctx context.Context, hash []byte) (uuid.UUID, error) AddMembership(ctx context.Context, arg AddMembershipParams) error + AddMonitorRegion(ctx context.Context, arg AddMonitorRegionParams) error + AllMonitorRegions(ctx context.Context) ([]AllMonitorRegionsRow, error) AnyUserExists(ctx context.Context) (bool, error) // Shortens tokens that would outlive a newly set maximum lifetime. ClampAPITokenExpiry(ctx context.Context, arg ClampAPITokenExpiryParams) (int64, error) CountRoleAssignments(ctx context.Context, roleID uuid.UUID) (int64, error) CountUnusedRecoveryCodes(ctx context.Context, userID uuid.UUID) (int64, error) CreateAPIToken(ctx context.Context, arg CreateAPITokenParams) (ApiToken, error) + CreateAgent(ctx context.Context, arg CreateAgentParams) (Agent, error) CreateAssignment(ctx context.Context, arg CreateAssignmentParams) (RoleAssignment, error) CreateIdentity(ctx context.Context, arg CreateIdentityParams) error CreateInvitation(ctx context.Context, arg CreateInvitationParams) (Invitation, error) + CreateMonitor(ctx context.Context, arg CreateMonitorParams) (Monitor, error) CreateOrg(ctx context.Context, arg CreateOrgParams) (Org, error) CreateRole(ctx context.Context, arg CreateRoleParams) (Role, error) CreateSSOProvider(ctx context.Context, arg CreateSSOProviderParams) (SsoProvider, error) CreateUser(ctx context.Context, arg CreateUserParams) (User, error) DeleteAPIToken(ctx context.Context, id uuid.UUID) (int64, error) + DeleteAgent(ctx context.Context, id uuid.UUID) (int64, error) DeleteAssignment(ctx context.Context, id uuid.UUID) (int64, error) DeleteInvitation(ctx context.Context, id uuid.UUID) (int64, error) + DeleteMonitor(ctx context.Context, id uuid.UUID) (int64, error) + DeleteMonitorRegions(ctx context.Context, monitorID uuid.UUID) error DeleteOrg(ctx context.Context, id uuid.UUID) (int64, error) DeleteRecoveryCodes(ctx context.Context, userID uuid.UUID) error DeleteRole(ctx context.Context, id uuid.UUID) (int64, error) @@ -38,26 +45,39 @@ type Querier interface { EnableTOTP(ctx context.Context, arg EnableTOTPParams) error GetAPIToken(ctx context.Context, id uuid.UUID) (ApiToken, error) GetAPITokenByHash(ctx context.Context, tokenHash []byte) (ApiToken, error) + GetAgentByHash(ctx context.Context, tokenHash []byte) (Agent, error) GetAssignment(ctx context.Context, id uuid.UUID) (RoleAssignment, error) GetIdentity(ctx context.Context, arg GetIdentityParams) (UserIdentity, error) GetInvitation(ctx context.Context, id uuid.UUID) (Invitation, error) GetInvitationByHash(ctx context.Context, tokenHash []byte) (GetInvitationByHashRow, error) GetMembership(ctx context.Context, arg GetMembershipParams) (Membership, error) + GetMonitor(ctx context.Context, id uuid.UUID) (Monitor, error) GetOrg(ctx context.Context, id uuid.UUID) (Org, error) GetOrgBySlug(ctx context.Context, slug string) (Org, error) GetRole(ctx context.Context, id uuid.UUID) (Role, error) GetSSOProvider(ctx context.Context, id uuid.UUID) (SsoProvider, error) GetUser(ctx context.Context, id uuid.UUID) (User, error) GetUserByEmail(ctx context.Context, email string) (User, error) + // check_results and its aggregates have no row-level security (see + // migration 00013). Every query here must filter by org_id. + InsertCheckResults(ctx context.Context, arg []InsertCheckResultsParams) (int64, error) InsertRecoveryCodes(ctx context.Context, arg []InsertRecoveryCodesParams) (int64, error) InvitationOrg(ctx context.Context, hash []byte) (uuid.UUID, error) IsMember(ctx context.Context, arg IsMemberParams) (bool, error) + // Newest result per monitor and region in the org. + LatestResults(ctx context.Context, orgID uuid.UUID) ([]LatestResultsRow, error) ListAPITokens(ctx context.Context, arg ListAPITokensParams) ([]ListAPITokensRow, error) + ListAgents(ctx context.Context) ([]Agent, error) ListAssignments(ctx context.Context, orgID uuid.UUID) ([]ListAssignmentsRow, error) + // System scope: every enabled monitor with its regions, for reconciling the + // schedule. + ListEnabledMonitorsForSchedule(ctx context.Context) ([]ListEnabledMonitorsForScheduleRow, error) ListEnabledSSOProviders(ctx context.Context) ([]ListEnabledSSOProvidersRow, error) + ListMonitors(ctx context.Context) ([]Monitor, error) ListOrgMembers(ctx context.Context, orgID uuid.UUID) ([]ListOrgMembersRow, error) ListOrgs(ctx context.Context) ([]Org, error) ListPendingInvitations(ctx context.Context) ([]ListPendingInvitationsRow, error) + ListRegions(ctx context.Context) ([]Region, error) ListRoles(ctx context.Context) ([]Role, error) ListSSOProviders(ctx context.Context) ([]SsoProvider, error) ListUserIdentitiesInOrg(ctx context.Context, userID uuid.UUID) ([]ListUserIdentitiesInOrgRow, error) @@ -65,15 +85,27 @@ type Querier interface { MarkInvitationAccepted(ctx context.Context, id uuid.UUID) (int64, error) // Every role a member holds, with the scope it applies to. MemberGrants(ctx context.Context, arg MemberGrantsParams) ([]MemberGrantsRow, error) + MonitorRegions(ctx context.Context, monitorID uuid.UUID) ([]string, error) + // System scope: monitors to hand to a checker of region, skipping ones that + // were disabled, deleted or moved out of the region since dispatch. + MonitorsForJobs(ctx context.Context, arg MonitorsForJobsParams) ([]Monitor, error) OrgIDBySlug(ctx context.Context, slug string) (uuid.UUID, error) + RecentResults(ctx context.Context, arg RecentResultsParams) ([]RecentResultsRow, error) RemoveMembership(ctx context.Context, arg RemoveMembershipParams) (int64, error) SetPasswordHash(ctx context.Context, arg SetPasswordHashParams) error SetUserLocale(ctx context.Context, arg SetUserLocaleParams) error TouchAPIToken(ctx context.Context, id uuid.UUID) error + TouchAgent(ctx context.Context, arg TouchAgentParams) error TouchIdentity(ctx context.Context, arg TouchIdentityParams) error + UpdateMonitor(ctx context.Context, arg UpdateMonitorParams) (Monitor, error) UpdateOrgPolicy(ctx context.Context, arg UpdateOrgPolicyParams) (Org, error) UpdateRole(ctx context.Context, arg UpdateRoleParams) (Role, error) UpdateSSOProvider(ctx context.Context, arg UpdateSSOProviderParams) (SsoProvider, error) + // An empty name names a new region after its key and keeps an existing name. + UpsertRegion(ctx context.Context, arg UpsertRegionParams) (Region, error) + // Uptime per monitor from the hourly aggregate, including the not yet + // materialized most recent hours (real-time aggregation). + UptimeSince(ctx context.Context, arg UptimeSinceParams) ([]UptimeSinceRow, error) UseRecoveryCode(ctx context.Context, arg UseRecoveryCodeParams) (int64, error) } diff --git a/internal/store/queries/agents.sql b/internal/store/queries/agents.sql new file mode 100644 index 0000000..e1b1282 --- /dev/null +++ b/internal/store/queries/agents.sql @@ -0,0 +1,26 @@ +-- name: UpsertRegion :one +-- An empty name names a new region after its key and keeps an existing name. +INSERT INTO regions (key, name) VALUES (sqlc.arg(key), coalesce(nullif(sqlc.arg(name)::text, ''), sqlc.arg(key))) +ON CONFLICT (key) DO UPDATE SET name = CASE WHEN sqlc.arg(name)::text = '' THEN regions.name ELSE EXCLUDED.name END +RETURNING *; + +-- name: ListRegions :many +SELECT * FROM regions ORDER BY key; + +-- name: CreateAgent :one +INSERT INTO agents (org_id, kind, name, region, token_hash, prefix) +VALUES ($1, $2, $3, $4, $5, $6) +RETURNING *; + +-- name: GetAgentByHash :one +SELECT * FROM agents WHERE token_hash = $1; + +-- name: ListAgents :many +SELECT * FROM agents ORDER BY kind, region, name; + +-- name: DeleteAgent :execrows +DELETE FROM agents WHERE id = $1; + +-- name: TouchAgent :exec +UPDATE agents SET last_seen_at = now(), release = $2 +WHERE id = $1 AND (last_seen_at IS NULL OR last_seen_at < now() - interval '30 seconds' OR release IS DISTINCT FROM $2); diff --git a/internal/store/queries/check_results.sql b/internal/store/queries/check_results.sql new file mode 100644 index 0000000..2c6c8da --- /dev/null +++ b/internal/store/queries/check_results.sql @@ -0,0 +1,28 @@ +-- check_results and its aggregates have no row-level security (see +-- migration 00013). Every query here must filter by org_id. + +-- name: InsertCheckResults :copyfrom +INSERT INTO check_results (time, org_id, monitor_id, region, checker_id, ok, latency_ms, status_code, error) +VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9); + +-- name: LatestResults :many +-- Newest result per monitor and region in the org. +SELECT DISTINCT ON (monitor_id, region) monitor_id, region, time, ok, latency_ms, status_code, error +FROM check_results +WHERE org_id = $1 AND time > now() - interval '1 day' +ORDER BY monitor_id, region, time DESC; + +-- name: RecentResults :many +SELECT time, region, ok, latency_ms, status_code, error +FROM check_results +WHERE org_id = $1 AND monitor_id = $2 AND time > $3 +ORDER BY time DESC +LIMIT 500; + +-- name: UptimeSince :many +-- Uptime per monitor from the hourly aggregate, including the not yet +-- materialized most recent hours (real-time aggregation). +SELECT monitor_id, sum(total)::bigint AS total, sum(ok_count)::bigint AS ok_count +FROM check_results_1h +WHERE org_id = $1 AND bucket >= $2 +GROUP BY monitor_id; diff --git a/internal/store/queries/monitors.sql b/internal/store/queries/monitors.sql new file mode 100644 index 0000000..54d5fc5 --- /dev/null +++ b/internal/store/queries/monitors.sql @@ -0,0 +1,47 @@ +-- name: CreateMonitor :one +INSERT INTO monitors (org_id, name, type, target, interval_seconds, timeout_ms, config, enabled) +VALUES ($1, $2, $3, $4, $5, $6, $7, $8) +RETURNING *; + +-- name: UpdateMonitor :one +UPDATE monitors SET name = $2, type = $3, target = $4, interval_seconds = $5, + timeout_ms = $6, config = $7, enabled = $8, updated_at = now() +WHERE id = $1 +RETURNING *; + +-- name: DeleteMonitor :execrows +DELETE FROM monitors WHERE id = $1; + +-- name: GetMonitor :one +SELECT * FROM monitors WHERE id = $1; + +-- name: ListMonitors :many +SELECT * FROM monitors ORDER BY name; + +-- name: MonitorRegions :many +SELECT region FROM monitor_regions WHERE monitor_id = $1 ORDER BY region; + +-- name: AllMonitorRegions :many +SELECT monitor_id, region FROM monitor_regions; + +-- name: DeleteMonitorRegions :exec +DELETE FROM monitor_regions WHERE monitor_id = $1; + +-- name: AddMonitorRegion :exec +INSERT INTO monitor_regions (monitor_id, org_id, region) VALUES ($1, $2, $3); + +-- name: ListEnabledMonitorsForSchedule :many +-- System scope: every enabled monitor with its regions, for reconciling the +-- schedule. +SELECT m.id, m.interval_seconds, array_agg(r.region ORDER BY r.region)::text[] AS regions +FROM monitors m +JOIN monitor_regions r ON r.monitor_id = m.id +WHERE m.enabled +GROUP BY m.id, m.interval_seconds; + +-- name: MonitorsForJobs :many +-- System scope: monitors to hand to a checker of region, skipping ones that +-- were disabled, deleted or moved out of the region since dispatch. +SELECT m.* FROM monitors m +JOIN monitor_regions r ON r.monitor_id = m.id AND r.region = sqlc.arg(region) +WHERE m.id = ANY (sqlc.arg(ids)::uuid[]) AND m.enabled; diff --git a/internal/store/results_test.go b/internal/store/results_test.go new file mode 100644 index 0000000..f30de7f --- /dev/null +++ b/internal/store/results_test.go @@ -0,0 +1,30 @@ +package store + +import ( + "os" + "regexp" + "strings" + "testing" +) + +// TestResultQueriesFilterByOrg guards the tables that cannot use row-level +// security: every read of check results must be restricted to one org. +func TestResultQueriesFilterByOrg(t *testing.T) { + src, err := os.ReadFile("queries/check_results.sql") + if err != nil { + t.Fatal(err) + } + blocks := regexp.MustCompile(`(?m)^-- name: `).Split(string(src), -1)[1:] + if len(blocks) == 0 { + t.Fatal("no queries found") + } + for _, b := range blocks { + name, _, _ := strings.Cut(b, " ") + if strings.Contains(b, ":copyfrom") { + continue + } + if !regexp.MustCompile(`(?i)WHERE[^;]*\borg_id\s*=\s*\$1`).MatchString(b) { + t.Errorf("query %s does not filter by org_id = $1", name) + } + } +}