From d3cf9f48e1f3a3c93b83c5f71f86b3b52c41f4ea Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebastian=20Untersch=C3=BCtz?= Date: Sun, 22 Nov 2026 16:17:08 +0100 Subject: [PATCH] feat: database monitors with sealed credentials Secret monitor settings such as database passwords are stored sealed, bound to monitor type and field, never returned by the API, the console or exports, kept when an edit leaves them empty, and opened only for the checker's job. Monitor types are validated by the check package; the database only checks their format. Compose gets a checks profile with MariaDB, MongoDB and SQL Server, and CI tests against MariaDB and MongoDB. Closes #93 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3 --- .env.example | 5 + .gitea/workflows/ci.yaml | 15 + compose.yaml | 32 + internal/api/agent.go | 8 +- internal/api/console.go | 5 + internal/api/dbcheck_test.go | 73 + internal/api/gdpr.go | 4 +- internal/api/monitors.go | 13 +- internal/api/monitorsecrets.go | 98 ++ internal/i18n/i18n_test.go | 4 +- internal/i18n/locales/de.json | 23 +- internal/i18n/locales/en.json | 23 +- .../migrations/sql/00035_monitor_types.sql | 11 + internal/web/monitors.templ | 56 +- internal/web/monitors_templ.go | 1204 ++++++++++------- 15 files changed, 1079 insertions(+), 495 deletions(-) create mode 100644 internal/api/dbcheck_test.go create mode 100644 internal/api/monitorsecrets.go create mode 100644 internal/migrations/sql/00035_monitor_types.sql diff --git a/.env.example b/.env.example index 6f166c7..fba5078 100644 --- a/.env.example +++ b/.env.example @@ -22,6 +22,11 @@ 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 +# Database checks are also tested against these when set +# (docker compose --profile checks up -d --wait). +# UPTIME_TEST_MYSQL_ADDR=localhost:13306 +# UPTIME_TEST_MONGO_ADDR=localhost:27018 +# UPTIME_TEST_MSSQL_ADDR=localhost:11433 # Reverse proxies allowed to set X-Forwarded-For (comma-separated IPs/CIDRs). # UPTIME_TRUSTED_PROXIES=10.0.0.0/8 diff --git a/.gitea/workflows/ci.yaml b/.gitea/workflows/ci.yaml index 4a9ff4f..f9bd87b 100644 --- a/.gitea/workflows/ci.yaml +++ b/.gitea/workflows/ci.yaml @@ -55,9 +55,24 @@ jobs: POSTGRES_PASSWORD: postgres redis: image: redis:8-alpine + # Targets of the database checks; SQL Server is left to local runs, + # its image is too large for ephemeral runners. + mariadb: + image: mariadb:11 + env: + MARIADB_ROOT_PASSWORD: checkpw + MARIADB_DATABASE: shop + options: --health-cmd "healthcheck.sh --connect" --health-interval 2s --health-retries 60 + mongo: + image: mongo:8 + env: + MONGO_INITDB_ROOT_USERNAME: root + MONGO_INITDB_ROOT_PASSWORD: checkpw env: UPTIME_TEST_DATABASE_URL: postgres://uptime:uptime@timescaledb:5432/uptime_test?sslmode=disable UPTIME_TEST_REDIS_URL: redis://redis:6379/15 + UPTIME_TEST_MYSQL_ADDR: mariadb:3306 + UPTIME_TEST_MONGO_ADDR: mongo:27017 steps: - uses: actions/checkout@v7 # The runners are ephemeral and clone every action from GitHub, which diff --git a/compose.yaml b/compose.yaml index c5de703..afef203 100644 --- a/compose.yaml +++ b/compose.yaml @@ -50,5 +50,37 @@ services: <<: *sentinel environment: {PORT: "26381"} + # Databases the database checks are tested against: + # docker compose --profile checks up -d --wait + mariadb: + image: mariadb:11 + profiles: [checks] + environment: {MARIADB_ROOT_PASSWORD: checkpw, MARIADB_DATABASE: shop} + ports: ["13306:3306"] + healthcheck: + test: ["CMD", "healthcheck.sh", "--connect"] + interval: 2s + retries: 60 + + mongo: + image: mongo:8 + profiles: [checks] + environment: {MONGO_INITDB_ROOT_USERNAME: root, MONGO_INITDB_ROOT_PASSWORD: checkpw} + ports: ["27018:27017"] + healthcheck: + test: ["CMD", "mongosh", "--quiet", "--eval", "db.runCommand({ping: 1})"] + interval: 2s + retries: 60 + + mssql: + image: mcr.microsoft.com/mssql/server:2022-latest + profiles: [checks] + environment: {ACCEPT_EULA: "Y", MSSQL_SA_PASSWORD: "Check-pw-2026"} + ports: ["11433:1433"] + healthcheck: + test: ["CMD-SHELL", "/opt/mssql-tools18/bin/sqlcmd -C -S localhost -U sa -P \"$$MSSQL_SA_PASSWORD\" -Q 'SELECT 1' || exit 1"] + interval: 3s + retries: 60 + volumes: pgdata: diff --git a/internal/api/agent.go b/internal/api/agent.go index 88c13dc..39acfde 100644 --- a/internal/api/agent.go +++ b/internal/api/agent.go @@ -14,6 +14,7 @@ import ( "github.com/redis/go-redis/v9" "git.zb-server.de/ZB-Server/uptimesebi/internal/agentapi" + "git.zb-server.de/ZB-Server/uptimesebi/internal/check" "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" @@ -190,9 +191,14 @@ func (s *Server) resolveJobs(ctx context.Context, a store.GetAgentByHashRow, ent if !ok { continue } + cfg, err := s.openMonitorConfig(check.Type(m.Type), m.Config) + if err != nil { + s.log.ErrorContext(ctx, "opening monitor secrets failed", "monitor", m.ID, "error", err) + 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), + TimeoutMS: int(m.TimeoutMs), Config: cfg, AllowPrivate: s.allowPrivate(a), }) orgs[m.ID] = m.OrgID } diff --git a/internal/api/console.go b/internal/api/console.go index 81cdf62..7700fe9 100644 --- a/internal/api/console.go +++ b/internal/api/console.go @@ -616,6 +616,11 @@ func fillForm(f *web.MonitorForm, m store.Monitor) { _ = json.Unmarshal(m.Config, &c) f.PromQuery, f.PromOp, f.PromThreshold, f.PromMode = c.Query, c.Op, strconv.FormatFloat(c.Threshold, 'g', -1, 64), c.Mode f.PromEmptyOK, f.PromVerify, f.Headers = c.EmptyOK, c.VerifyTLS, headerLines(c.Headers) + case check.Postgres, check.MySQL, check.MSSQL, check.MongoDB, check.Redis: + var c check.DBConfig + cfg, secrets := publicMonitorConfig(m.Config) + _ = json.Unmarshal(cfg, &c) + f.DB = web.DBForm{User: c.User, Database: c.Database, TLS: c.TLS, Query: c.Query, Expect: c.Expect, PasswordSet: slices.Contains(secrets, "password")} case check.Alertmanager: var c check.AlertmanagerConfig _ = json.Unmarshal(m.Config, &c) diff --git a/internal/api/dbcheck_test.go b/internal/api/dbcheck_test.go new file mode 100644 index 0000000..c47fe98 --- /dev/null +++ b/internal/api/dbcheck_test.go @@ -0,0 +1,73 @@ +package api_test + +import ( + "context" + "net/http" + "net/url" + "os" + "strings" + "testing" + "time" + + "github.com/jackc/pgx/v5" +) + +func TestDatabaseMonitorSecrets(t *testing.T) { + e := newEnv(t) + ctx, cancel := context.WithCancel(context.Background()) + t.Cleanup(cancel) + go e.api.RunScheduler(ctx) + tok, region := e.platformChecker(t, uniq("eu-")) + e.startChecker(t, tok) + pg, _ := url.Parse(os.Getenv("UPTIME_TEST_DATABASE_URL")) + + owner := e.browser(t) + owner.signup("o@"+uniq("db")+".test", uniq("db-")) + monitor := map[string]any{ + "name": "Main DB", "type": "postgres", "target": pg.Host, "interval_seconds": 10, "timeout_ms": 5000, "confirmations": 1, + "regions": []string{region}, + "config": map[string]any{"user": "uptime", "password": "uptime", "database": "uptime_test", "tls": "disable", "query": "SELECT 41 + 1", "expect": "42"}, + } + st, body := owner.do("POST", "/api/v1/org/monitors", monitor) + if st != http.StatusCreated { + t.Fatalf("create = %d %v", st, body) + } + id := body["id"].(string) + if _, hasPassword := body["config"].(map[string]any)["password"]; hasPassword || mustJSON(body["secrets_set"]) != `["password"]` { + t.Errorf("create answer exposes or misses the password: %s", mustJSON(body)) + } + var stored string + _ = e.asSystem(t, func(tx pgx.Tx) error { + return tx.QueryRow(context.Background(), `SELECT config::text FROM monitors WHERE id = $1`, id).Scan(&stored) + }) + if strings.Contains(stored, `"password"`) || !strings.Contains(stored, "sealed_password") { + t.Errorf("stored config = %s", stored) + } + + latestOK := func() bool { + _, list := owner.do("GET", "/api/v1/org/monitors", nil) + for _, m := range list["monitors"].([]any) { + if l := m.(map[string]any)["latest"].([]any); len(l) > 0 && l[0].(map[string]any)["ok"] == true { + return true + } + } + return false + } + waitFor(t, 15*time.Second, "the checker signing in with the sealed password", latestOK) + + // Saving without the password keeps it. + monitor["config"] = map[string]any{"user": "uptime", "database": "uptime_test", "tls": "disable", "query": "SELECT 41 + 1", "expect": "42"} + if st, body := owner.do("PUT", "/api/v1/org/monitors/"+id, monitor); st != http.StatusOK || mustJSON(body["secrets_set"]) != `["password"]` { + t.Fatalf("update without password = %d %v", st, body) + } + if _, _, page := owner.page("/monitors/" + id + "/edit"); strings.Contains(page, `value="uptime_test"`) == false || strings.Contains(page, "sealed_") { + t.Error("the editor lacks the settings or shows the sealed password") + } + _, list := owner.do("GET", "/api/v1/org/monitors", nil) + _, _, export := owner.download("/api/v1/org/export?format=json") + for _, raw := range []string{mustJSON(list), string(export)} { + if strings.Contains(raw, "sealed_password") { + t.Error("a sealed password leaves the API") + } + } +} diff --git a/internal/api/gdpr.go b/internal/api/gdpr.go index 79de2c3..b0115fc 100644 --- a/internal/api/gdpr.go +++ b/internal/api/gdpr.go @@ -408,7 +408,7 @@ func (s *Server) buildOrgExport(ctx context.Context, p *principal) (orgExport, e x.Monitors = append(x.Monitors, exportMonitor{ ID: m.ID, Name: m.Name, Type: m.Type, Target: m.Target, IntervalSeconds: m.IntervalSeconds, TimeoutMS: m.TimeoutMs, Confirmations: m.Confirmations, Enabled: m.Enabled, GroupID: m.GroupID, - Regions: orEmpty(regions[m.ID]), Config: rawJSON(m.Config), CreatedAt: m.CreatedAt, + Regions: orEmpty(regions[m.ID]), Config: rawJSON(first(publicMonitorConfig(m.Config))), CreatedAt: m.CreatedAt, }) } @@ -672,3 +672,5 @@ func (s *Server) deleteOrg(c *gin.Context) { map[string]any{"slug": p.Org.Slug, "name": p.Org.Name}) c.JSON(http.StatusOK, gin.H{"status": "deleted"}) } + +func first[A, B any](a A, _ B) A { return a } diff --git a/internal/api/monitors.go b/internal/api/monitors.go index 713dad5..7dd759b 100644 --- a/internal/api/monitors.go +++ b/internal/api/monitors.go @@ -62,6 +62,9 @@ type monitorView struct { Latest []latestView `json:"latest"` // PingURL is where heartbeat monitors are pinged. PingURL string `json:"ping_url,omitempty"` + // SecretsSet names secret settings that are set; their values are + // never returned. + SecretsSet []string `json:"secrets_set,omitempty"` } // withPingURL adds the ping URL of heartbeat monitors. @@ -73,9 +76,11 @@ func (s *Server) withPingURL(v monitorView) monitorView { } func viewMonitor(m store.Monitor, regions []uuid.UUID) monitorView { + cfg, secrets := publicMonitorConfig(m.Config) 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, Confirmations: m.Confirmations, GroupID: m.GroupID, Regions: regions, Latest: []latestView{}, + TimeoutMS: m.TimeoutMs, Config: cfg, Enabled: m.Enabled, Confirmations: m.Confirmations, GroupID: m.GroupID, Regions: regions, Latest: []latestView{}, + SecretsSet: secrets, } } @@ -244,6 +249,7 @@ func (s *Server) createMonitor(c *gin.Context) { return } req.Target = passiveTarget(check.Type(req.Type), req.Target) + req.Config = s.sealMonitorConfig(check.Type(req.Type), req.Config, nil) var m store.Monitor err = s.db.Tx(ctx, p.scope(), func(q *store.Queries) error { var err error @@ -338,6 +344,11 @@ func (s *Server) updateMonitor(c *gin.Context) { if previous, err = q.MonitorRegions(ctx, id); err != nil { return err } + if old.Type == req.Type { + req.Config = s.sealMonitorConfig(check.Type(req.Type), req.Config, old.Config) + } else { + req.Config = s.sealMonitorConfig(check.Type(req.Type), req.Config, nil) + } if check.Passive(check.Type(req.Type)) { // The ping URL stays the same across edits. req.Target = old.Target diff --git a/internal/api/monitorsecrets.go b/internal/api/monitorsecrets.go new file mode 100644 index 0000000..300f8e9 --- /dev/null +++ b/internal/api/monitorsecrets.go @@ -0,0 +1,98 @@ +package api + +import ( + "encoding/base64" + "encoding/json" + "slices" + "strings" + + "git.zb-server.de/ZB-Server/uptimesebi/internal/check" +) + +// Monitor settings listed by check.SecretFields, such as database +// passwords, are stored as "sealed_": encrypted and bound to the +// monitor type and field. They are never returned; checkers get them in +// plain text with their jobs. + +const sealedPrefix = "sealed_" + +func monitorSecretAAD(t check.Type, field string) []byte { + return []byte("monitor:" + string(t) + ":" + field) +} + +// sealMonitorConfig replaces secret settings in cfg by their sealed form. +// A secret left empty keeps its value from previous, so forms need not ask +// for passwords again. +func (s *Server) sealMonitorConfig(t check.Type, cfg, previous []byte) []byte { + fields := check.SecretFields(t) + if len(fields) == 0 { + return cfg + } + var m, old map[string]any + if json.Unmarshal(cfg, &m) != nil { + return cfg + } + _ = json.Unmarshal(previous, &old) + for _, f := range fields { + v, _ := m[f].(string) + delete(m, f) + switch { + case v != "": + m[sealedPrefix+f] = base64.StdEncoding.EncodeToString(s.keys.Seal([]byte(v), monitorSecretAAD(t, f))) + case old[sealedPrefix+f] != nil: + m[sealedPrefix+f] = old[sealedPrefix+f] + } + } + out, _ := json.Marshal(m) + return out +} + +// openMonitorConfig restores secret settings for a checker. +func (s *Server) openMonitorConfig(t check.Type, cfg []byte) ([]byte, error) { + fields := check.SecretFields(t) + if len(fields) == 0 { + return cfg, nil + } + var m map[string]any + if err := json.Unmarshal(cfg, &m); err != nil { + return nil, err + } + for _, f := range fields { + sealed, ok := m[sealedPrefix+f].(string) + delete(m, sealedPrefix+f) + if !ok { + continue + } + raw, err := base64.StdEncoding.DecodeString(sealed) + if err != nil { + return nil, err + } + plain, err := s.keys.Open(raw, monitorSecretAAD(t, f)) + if err != nil { + return nil, err + } + m[f] = string(plain) + } + return json.Marshal(m) +} + +// publicMonitorConfig drops sealed secrets from cfg and names those set. +func publicMonitorConfig(cfg []byte) ([]byte, []string) { + var m map[string]any + if json.Unmarshal(cfg, &m) != nil { + return cfg, nil + } + var set []string + for k := range m { + if f, ok := strings.CutPrefix(k, sealedPrefix); ok { + set = append(set, f) + delete(m, k) + } + } + if set == nil { + return cfg, nil + } + slices.Sort(set) + out, _ := json.Marshal(m) + return out, set +} diff --git a/internal/i18n/i18n_test.go b/internal/i18n/i18n_test.go index e20cf9c..2b7c783 100644 --- a/internal/i18n/i18n_test.go +++ b/internal/i18n/i18n_test.go @@ -152,7 +152,7 @@ func TestDynamicFamilies(t *testing.T) { en := catalogKeys(t)["en"] families := map[string][]string{ "status.": {"up", "degraded", "down", "unknown", "paused", "maintenance"}, - "monitors.type_": {"http", "tcp", "tls", "dns", "icmp", "json", "prometheus", "heartbeat", "alertmanager"}, + "monitors.type_": {"http", "tcp", "tls", "dns", "icmp", "json", "prometheus", "postgres", "mysql", "mssql", "mongodb", "redis", "heartbeat", "alertmanager"}, "channels.type_": {"webhook", "email", "slack", "discord", "teams", "googlechat", "mattermost", "rocketchat", "telegram", "matrix", "ntfy", "gotify", "pushover", "pushbullet", "signal", "pagerduty", "opsgenie", "apprise"}, "agents.kind_": {"checker", "statuspage"}, "page.status.": {"operational", "degraded", "outage", "unknown", "maintenance"}, @@ -163,6 +163,8 @@ func TestDynamicFamilies(t *testing.T) { "evidence.stage_": {"dns", "connect", "tls", "response", "body"}, "evidence.phase_": {"dns", "connect", "tls", "wait", "download"}, "channels.field_": {"webhook_url", "channel", "bot_token", "chat_id", "thread_id", "api_url", "homeserver_url", "access_token", "room_id", "server_url", "topic", "priority", "app_token", "user_key", "device", "number", "recipients", "routing_key", "severity", "api_key", "region", "urls", "config_key"}, + "monitors.db_database_": {"postgres", "mysql", "mssql", "mongodb", "redis"}, + "monitors.db_tls_": {"require", "verify", "disable"}, "weekday.": {"0", "1", "2", "3", "4", "5", "6"}, "md.": {"heading", "bold", "italic", "strike", "link", "ul", "ol", "quote", "code", "codeblock", "table", "hr"}, "maintenance.recurrence_": {"none", "daily", "weekly", "monthly"}, diff --git a/internal/i18n/locales/de.json b/internal/i18n/locales/de.json index c0dd450..bee1ccd 100644 --- a/internal/i18n/locales/de.json +++ b/internal/i18n/locales/de.json @@ -573,6 +573,21 @@ "monitors.by_region_hint": "Anteil erfolgreicher Checks aus jeder Region. Die SLA sinkt nur, wenn alle Regionen gleichzeitig ausfallen.", "monitors.confirmations": "Fehlschläge bis zum Alarm", "monitors.confirmations_hint": "Aufeinanderfolgende Fehlschläge pro Region. Alarm gibt es erst, wenn alle gewählten Regionen ausfallen.", + "monitors.db_database_mongodb": "Authentifizierungs-Datenbank", + "monitors.db_database_mssql": "Datenbank", + "monitors.db_database_mysql": "Datenbank", + "monitors.db_database_postgres": "Datenbank", + "monitors.db_database_redis": "Datenbanknummer (0–15)", + "monitors.db_expect": "Erwarteter erster Wert (optional)", + "monitors.db_hint": "Ziel ist host:port. Verbindet sich, meldet sich an und führt die Abfrage aus; das Passwort wird verschlüsselt gespeichert und nur an Checker übergeben.", + "monitors.db_password": "Passwort", + "monitors.db_query": "Abfrage (optional)", + "monitors.db_tls": "Verschlüsselung", + "monitors.db_tls_disable": "Keine", + "monitors.db_tls_require": "TLS, Zertifikat ungeprüft", + "monitors.db_tls_verify": "TLS mit geprüftem Zertifikat", + "monitors.db_user": "Benutzer", + "monitors.db_user_redis": "Benutzer (ACL, optional)", "monitors.delete": "Monitor löschen", "monitors.delete_confirm": "Diesen Monitor samt Verlauf löschen?", "monitors.dns_expect": "Erwartete Antwort (optional)", @@ -624,12 +639,13 @@ "monitors.recent": "Letzte Checks", "monitors.regions": "Regionen", "monitors.regions_hint": "Geprüft von einem zufälligen Checker jeder gewählten Region. Deine eigenen Regionen stehen oben.", + "monitors.secret_unchanged": "unverändert", "monitors.sla": "SLA", "monitors.sla_table": "SLA nach Zeitraum", "monitors.stale_hours": "Verfällt nach (Stunden)", "monitors.stale_hours_hint": "Ein feuernder Alert, den Alertmanager nicht mehr wiederholt, gilt nach dieser Zeit als beendet. Halte sie über repeat_interval.", "monitors.target": "Ziel", - "monitors.target_hint": "URL für HTTP, host:port für TCP und TLS, Hostname für DNS und ICMP.", + "monitors.target_hint": "URL für HTTP, host:port für TCP, TLS und Datenbanken, Hostname für DNS und ICMP.", "monitors.timeout": "Timeout (ms)", "monitors.tls_min_days": "Mindestens Tage bis Ablauf", "monitors.tls_server_name": "Servername (optional)", @@ -640,7 +656,12 @@ "monitors.type_http": "HTTP(S)", "monitors.type_icmp": "Ping (ICMP)", "monitors.type_json": "JSON-API", + "monitors.type_mongodb": "MongoDB", + "monitors.type_mssql": "Microsoft SQL Server", + "monitors.type_mysql": "MySQL / MariaDB", + "monitors.type_postgres": "PostgreSQL", "monitors.type_prometheus": "Prometheus", + "monitors.type_redis": "Redis", "monitors.type_tcp": "TCP-Port", "monitors.type_tls": "TLS-Zertifikat", "monitors.uptime_chart": "Uptime pro Zeitraum", diff --git a/internal/i18n/locales/en.json b/internal/i18n/locales/en.json index e7e32e5..b110005 100644 --- a/internal/i18n/locales/en.json +++ b/internal/i18n/locales/en.json @@ -573,6 +573,21 @@ "monitors.by_region_hint": "Share of successful checks from each region. The SLA only drops when all regions fail at the same time.", "monitors.confirmations": "Failures before alerting", "monitors.confirmations_hint": "Consecutive failures per region. An alert needs every selected region to fail.", + "monitors.db_database_mongodb": "Authentication database", + "monitors.db_database_mssql": "Database", + "monitors.db_database_mysql": "Database", + "monitors.db_database_postgres": "Database", + "monitors.db_database_redis": "Database number (0–15)", + "monitors.db_expect": "Expected first value (optional)", + "monitors.db_hint": "Target is host:port. Connects, signs in and runs the query; the password is stored encrypted and only handed to checkers.", + "monitors.db_password": "Password", + "monitors.db_query": "Query (optional)", + "monitors.db_tls": "Encryption", + "monitors.db_tls_disable": "None", + "monitors.db_tls_require": "TLS, certificate not verified", + "monitors.db_tls_verify": "TLS with verified certificate", + "monitors.db_user": "User", + "monitors.db_user_redis": "User (ACL, optional)", "monitors.delete": "Delete monitor", "monitors.delete_confirm": "Delete this monitor and its history?", "monitors.dns_expect": "Expected answer (optional)", @@ -624,12 +639,13 @@ "monitors.recent": "Recent checks", "monitors.regions": "Regions", "monitors.regions_hint": "Checked from a random checker in each selected region. Your own regions are listed first.", + "monitors.secret_unchanged": "unchanged", "monitors.sla": "SLA", "monitors.sla_table": "SLA by period", "monitors.stale_hours": "Stale after (hours)", "monitors.stale_hours_hint": "A firing alert Alertmanager stops repeating counts as over after this time. Keep it above repeat_interval.", "monitors.target": "Target", - "monitors.target_hint": "URL for HTTP, host:port for TCP and TLS, host name for DNS and ICMP.", + "monitors.target_hint": "URL for HTTP, host:port for TCP, TLS and databases, host name for DNS and ICMP.", "monitors.timeout": "Timeout (ms)", "monitors.tls_min_days": "Minimum days until expiry", "monitors.tls_server_name": "Server name (optional)", @@ -640,7 +656,12 @@ "monitors.type_http": "HTTP(S)", "monitors.type_icmp": "Ping (ICMP)", "monitors.type_json": "JSON API", + "monitors.type_mongodb": "MongoDB", + "monitors.type_mssql": "Microsoft SQL Server", + "monitors.type_mysql": "MySQL / MariaDB", + "monitors.type_postgres": "PostgreSQL", "monitors.type_prometheus": "Prometheus", + "monitors.type_redis": "Redis", "monitors.type_tcp": "TCP port", "monitors.type_tls": "TLS certificate", "monitors.uptime_chart": "Uptime per period", diff --git a/internal/migrations/sql/00035_monitor_types.sql b/internal/migrations/sql/00035_monitor_types.sql new file mode 100644 index 0000000..6515017 --- /dev/null +++ b/internal/migrations/sql/00035_monitor_types.sql @@ -0,0 +1,11 @@ +-- +goose Up +-- Monitor types follow the check package, which validates them with their +-- settings; listing them here as well meant a migration per new type. +ALTER TABLE monitors DROP CONSTRAINT monitors_type_check; +ALTER TABLE monitors ADD CONSTRAINT monitors_type_check CHECK (type ~ '^[a-z]{2,32}$'); + +-- +goose Down +DELETE FROM monitors WHERE type NOT IN ('http', 'tcp', 'icmp', 'dns', 'tls', 'json', 'prometheus', 'heartbeat', 'alertmanager'); +ALTER TABLE monitors DROP CONSTRAINT monitors_type_check; +ALTER TABLE monitors ADD CONSTRAINT monitors_type_check + CHECK (type IN ('http', 'tcp', 'icmp', 'dns', 'tls', 'json', 'prometheus', 'heartbeat', 'alertmanager')); diff --git a/internal/web/monitors.templ b/internal/web/monitors.templ index fe97e2a..7101e77 100644 --- a/internal/web/monitors.templ +++ b/internal/web/monitors.templ @@ -491,6 +491,18 @@ type MonitorForm struct { PromVerify bool Matchers []MatcherRow StaleHours int + DB DBForm +} + +// DBForm holds the settings of database checks. The password is never +// filled in; PasswordSet tells the form one is stored. +type DBForm struct { + User string + Database string + TLS string + Query string + Expect string + PasswordSet bool } // MatcherRow is one label matcher of an alertmanager monitor. @@ -576,7 +588,7 @@ templ MonitorEditor(p Page, me Me, f MonitorForm) {