Lightweight server monitoring with historical data, docker stats, and alerts.
feat(monitors): add option to ignore TLS errors for HTTPS monitors (#2500)
Sven van Ginkeld89f844a2a0a
diff --git a/agent/network_monitor.go b/agent/network_monitor.goindex 5fa908396..b0486181c 100644--- a/agent/network_monitor.go+++ b/agent/network_monitor.go@@ -1,6 +1,7 @@package agentimport (+ "crypto/tls""errors""fmt""net/http"@@ -20,7 +21,11 @@ type MonitorManager struct {}func newMonitorManager() *MonitorManager {- return newMonitorManagerWithProbe(networkMonitorProbe(&http.Client{Timeout: monitor.MaxProbeTimeout}))+ client := &http.Client{Timeout: monitor.MaxProbeTimeout}+ insecureTransport := http.DefaultTransport.(*http.Transport).Clone()+ insecureTransport.TLSClientConfig = &tls.Config{InsecureSkipVerify: true}+ insecureClient := &http.Client{Timeout: monitor.MaxProbeTimeout, Transport: insecureTransport}+ return newMonitorManagerWithProbe(networkMonitorProbe(client, insecureClient))}func newMonitorManagerWithProbe(probe monitorProbe) *MonitorManager {diff --git a/agent/network_monitor_probe.go b/agent/network_monitor_probe.goindex 7d7b6ae30..e1ac7c427 100644--- a/agent/network_monitor_probe.go+++ b/agent/network_monitor_probe.go@@ -18,7 +18,9 @@ const networkMonitorUserAgent = "Beszel-Agent/" + beszel.Version + " (+https://b// Implementations must honor cancellation and bound their execution time.type monitorProbe func(context.Context, monitor.Config) (int64, error)-func networkMonitorProbe(client *http.Client) monitorProbe {+// networkMonitorProbe returns a probe that uses client for HTTP monitors, or+// insecureClient for HTTP monitors that skip TLS certificate verification.+func networkMonitorProbe(client, insecureClient *http.Client) monitorProbe {return func(ctx context.Context, config monitor.Config) (int64, error) {switch config.Protocol {case "icmp":@@ -26,6 +28,9 @@ func networkMonitorProbe(client *http.Client) monitorProbe {case "tcp":return monitorTCP(ctx, config.Target, config.Port)case "http":+ if config.SkipTLSVerify {+ return monitorHTTP(ctx, insecureClient, config.Target)+ }return monitorHTTP(ctx, client, config.Target)case "dns":return monitorDNS(ctx, config.Target, config.Server)diff --git a/agent/network_monitor_test.go b/agent/network_monitor_test.goindex 1116ce3ce..d1e37e591 100644--- a/agent/network_monitor_test.go+++ b/agent/network_monitor_test.go@@ -145,7 +145,7 @@ func TestMonitorManagerApplySyncUpsertRunsImmediatelyAndReturnsResult(t *testingpm := &MonitorManager{monitors: make(map[string]*monitorTask),- probe: networkMonitorProbe(server.Client()),+ probe: networkMonitorProbe(server.Client(), nil),}resp, err := pm.HandleSyncRequest(monitor.SyncRequest{@@ -261,6 +261,24 @@ func TestMonitorHTTP(t *testing.T) {assert.Equal(t, int64(-1), responseUs)require.Error(t, err)})++ t.Run("self-signed certificate", func(t *testing.T) {+ server := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ w.WriteHeader(http.StatusNoContent)+ }))+ defer server.Close()+ probe := newMonitorManager().probe+ config := monitor.Config{Protocol: "http", Target: server.URL}++ responseUs, err := probe(context.Background(), config)+ assert.Equal(t, int64(-1), responseUs)+ require.Error(t, err)++ config.SkipTLSVerify = true+ responseUs, err = probe(context.Background(), config)+ require.NoError(t, err)+ assert.GreaterOrEqual(t, responseUs, int64(0))+ })}func TestMonitorTCP(t *testing.T) {@@ -576,7 +594,7 @@ func TestMonitorProbeTimeoutRecordsLoss(t *testing.T) {defer server.Close()defer close(release)pm := newMonitorManager()- pm.probe = networkMonitorProbe(&http.Client{Timeout: 20 * time.Millisecond})+ pm.probe = networkMonitorProbe(&http.Client{Timeout: 20 * time.Millisecond}, nil)task := newMonitorTask(monitor.Config{ID: "timeout", Protocol: "http", Target: server.URL})defer task.cancel()diff --git a/internal/entities/monitor/monitor.go b/internal/entities/monitor/monitor.goindex 4d41cd6d7..530010cf5 100644--- a/internal/entities/monitor/monitor.go+++ b/internal/entities/monitor/monitor.go@@ -28,6 +28,9 @@ type Config struct {// Server is the DNS server to query (host or host:port, default port 53).// Only used when Protocol is "dns"; empty means use the system resolver.Server string `cbor:"5,keyasint,omitempty"`+ // SkipTLSVerify disables certificate verification for HTTPS targets, such as+ // those with self-signed certificates. Only used when Protocol is "http".+ SkipTLSVerify bool `cbor:"6,keyasint,omitempty" db:"skipTlsVerify"`}// CertInfo holds details of the leaf TLS certificate presented by a target.diff --git a/internal/hub/network_monitors.go b/internal/hub/network_monitors.goindex 5529aa584..b6da50e8e 100644--- a/internal/hub/network_monitors.go+++ b/internal/hub/network_monitors.go@@ -68,6 +68,10 @@ func bindNetworkMonitorsEvents(hub *Hub) {if protocol != "dns" {e.Record.Set("server", "")}+ // only http uses TLS verification - clear it for other protocols+ if protocol != "http" {+ e.Record.Set("skipTlsVerify", false)+ }ID := generateMonitorID(systemID, *monitorConfigFromRecord(e.Record))if ID != e.Record.Id {newRecord := copyMonitorToNewRecord(e.Record, ID)@@ -115,6 +119,8 @@ func monitorConfigFromRecord(record *core.Record) *monitor.Config {Port: uint16(record.GetInt("port")),Interval: uint16(record.GetInt("interval")),Server: record.GetString("server"),+ // SkipTLSVerify is a probe option, not part of the monitor's identity, so it does not affect the ID.+ SkipTLSVerify: record.GetBool("skipTlsVerify"),}}@@ -139,7 +145,7 @@ func copyMonitorToNewRecord(oldRecord *core.Record, newID string) *core.Record {collection := oldRecord.Collection()newRecord := core.NewRecord(collection)newRecord.Id = newID- fields := []string{"system", "target", "protocol", "port", "server", "interval", "enabled"}+ fields := []string{"system", "target", "protocol", "port", "server", "interval", "enabled", "skipTlsVerify"}for _, field := range fields {newRecord.Set(field, oldRecord.Get(field))}diff --git a/internal/hub/network_monitors_test.go b/internal/hub/network_monitors_test.goindex 3c82bcb58..28b7a0842 100644--- a/internal/hub/network_monitors_test.go+++ b/internal/hub/network_monitors_test.go@@ -295,20 +295,21 @@ func TestCopyMonitorToNewRecordDropsResultFields(t *testing.T) {oldRecord := core.NewRecord(collection)oldRecord.Load(map[string]any{- "system": "sys123",- "target": "https://example.com",- "protocol": "http",- "port": 443,- "server": "1.1.1.1",- "interval": 60,- "enabled": true,- "res": 1200,- "resAvg1h": 1300,- "resMin1h": 900,- "resMax1h": 1600,- "loss1h": 5,- "certInfo": map[string]any{"expires": 1800000000000},- "updated": "2026-04-29 12:00:00.000Z",+ "system": "sys123",+ "target": "https://example.com",+ "protocol": "http",+ "port": 443,+ "server": "1.1.1.1",+ "interval": 60,+ "enabled": true,+ "skipTlsVerify": true,+ "res": 1200,+ "resAvg1h": 1300,+ "resMin1h": 900,+ "resMax1h": 1600,+ "loss1h": 5,+ "certInfo": map[string]any{"expires": 1800000000000},+ "updated": "2026-04-29 12:00:00.000Z",})newRecord := copyMonitorToNewRecord(oldRecord, "next12345")@@ -319,6 +320,7 @@ func TestCopyMonitorToNewRecordDropsResultFields(t *testing.T) {assert.Equal(t, 443, newRecord.GetInt("port"))assert.Equal(t, "1.1.1.1", newRecord.GetString("server"))assert.True(t, newRecord.GetBool("enabled"))+ assert.True(t, newRecord.GetBool("skipTlsVerify"))assert.Contains(t, []string{"", "null"}, newRecord.GetString("certInfo"))assert.Zero(t, newRecord.GetFloat("res"))assert.Zero(t, newRecord.GetFloat("resAvg1h"))diff --git a/internal/hub/systems/network_monitor_sync_test.go b/internal/hub/systems/network_monitor_sync_test.goindex a89077afc..b09817af1 100644--- a/internal/hub/systems/network_monitor_sync_test.go+++ b/internal/hub/systems/network_monitor_sync_test.go@@ -177,6 +177,23 @@ func TestNetworkMonitorReconnectSync(t *testing.T) {}}+func TestGetMonitorConfigsForSystemIncludesSkipTLSVerify(t *testing.T) {+ sys, app := newTestSystemWithHub(t)+ collection, err := app.FindCachedCollectionByNameOrId("network_monitors")+ require.NoError(t, err)+ record := core.NewRecord(collection)+ record.Load(map[string]any{+ "system": sys.Id, "target": "https://self-signed.example", "protocol": "http",+ "interval": 60, "enabled": true, "skipTlsVerify": true,+ })+ require.NoError(t, app.SaveNoValidate(record))++ configs, err := sys.manager.GetMonitorConfigsForSystem(sys.Id)+ require.NoError(t, err)+ require.Len(t, configs, 1)+ require.True(t, configs[0].SkipTLSVerify, "full sync must keep the skip TLS verify option")+}+func TestGetMonitorConfigsForSystemQueryError(t *testing.T) {sys, app := newTestSystemWithHub(t)_, err := app.DB().NewQuery("DROP TABLE network_monitors").Execute()diff --git a/internal/hub/systems/system_manager.go b/internal/hub/systems/system_manager.goindex e00c3924f..a01897aa5 100644--- a/internal/hub/systems/system_manager.go+++ b/internal/hub/systems/system_manager.go@@ -380,7 +380,7 @@ func (sm *SystemManager) resetFailedSmartFetchState(systemID string) {func (sm *SystemManager) GetMonitorConfigsForSystem(systemID string) ([]monitor.Config, error) {var configs []monitor.Configerr := sm.hub.DB().- NewQuery("SELECT id, target, protocol, port, interval, server FROM network_monitors WHERE system = {:system} AND enabled = true").+ NewQuery("SELECT id, target, protocol, port, interval, server, skipTlsVerify FROM network_monitors WHERE system = {:system} AND enabled = true").Bind(dbx.Params{"system": systemID}).All(&configs)return configs, errdiff --git a/internal/migrations/1790964708_network_monitor_skip_tls_verify.go b/internal/migrations/1790964708_network_monitor_skip_tls_verify.gonew file mode 100644index 000000000..8327d3912--- /dev/null+++ b/internal/migrations/1790964708_network_monitor_skip_tls_verify.go@@ -0,0 +1,24 @@+package migrations++import (+ "github.com/pocketbase/pocketbase/core"+ m "github.com/pocketbase/pocketbase/migrations"+)++func init() {+ m.Register(func(app core.App) error {+ collection, err := app.FindCollectionByNameOrId("network_monitors")+ if err != nil {+ return err+ }+ collection.Fields.Add(&core.BoolField{Id: "nm_skip_tls_verify", Name: "skipTlsVerify"})+ return app.Save(collection)+ }, func(app core.App) error {+ collection, err := app.FindCollectionByNameOrId("network_monitors")+ if err != nil {+ return err+ }+ collection.Fields.RemoveByName("skipTlsVerify")+ return app.Save(collection)+ })+}diff --git a/internal/site/src/components/network-monitors-table/monitor-dialog.tsx b/internal/site/src/components/network-monitors-table/monitor-dialog.tsxindex dfe56422d..6a0b91166 100644--- a/internal/site/src/components/network-monitors-table/monitor-dialog.tsx+++ b/internal/site/src/components/network-monitors-table/monitor-dialog.tsx@@ -19,6 +19,7 @@ import {} from "@/components/ui/dropdown-menu"import { Sheet, SheetContent, SheetDescription, SheetFooter, SheetHeader, SheetTitle } from "@/components/ui/sheet"import { Button } from "@/components/ui/button"+import { Switch } from "@/components/ui/switch"import { Input } from "@/components/ui/input"import { Label } from "@/components/ui/label"import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"@@ -40,6 +41,7 @@ type MonitorValues = {port: numberserver: stringinterval: string+ skipTlsVerify: boolean}type NormalizedMonitorValues = Omit<MonitorValues, "system" | "interval"> & {@@ -63,6 +65,7 @@ const NormalizedMonitorValuesSchema = v.pipe(port: v.number(),server: v.pipe(v.string(), v.trim()),interval: MonitorIntervalSchema,+ skipTlsVerify: v.boolean(),}),v.transform((input): NormalizedMonitorValues => {let { protocol, port } = input@@ -84,6 +87,8 @@ const NormalizedMonitorValuesSchema = v.pipe(// Only DNS monitors use a custom server; clear it for other protocols.server: protocol === "dns" ? input.server : "",interval: input.interval,+ // Only HTTPS targets use TLS; clear it for everything else.+ skipTlsVerify: protocol === "http" && isHttpsTarget(httpTarget) && input.skipTlsVerify,}}),v.forward(@@ -121,6 +126,10 @@ const BulkMonitorSchema = v.object({server: v.optional(v.pipe(v.string(), v.trim())),})+function isHttpsTarget(target: string) {+ return /^https:\/\//i.test(target)+}+function normalizeHttpTarget(target: string, port = 0) {const useExplicitPort = port > 0 && port !== 80 && port !== 443const hasOriginOnlyTarget = /^https?:\/\/[^/?#]+$/i.test(target)@@ -198,6 +207,7 @@ function parseBulkMonitorLine(line: string, lineNumber: number, system: string)port: parsed.output.port ? Number(parsed.output.port) : 0,server: parsed.output.server || "",interval: parsed.output.interval || `${defaultInterval}`,+ skipTlsVerify: false,})}@@ -720,6 +730,7 @@ function MonitorDialogContent({const [port, setPort] = useState(monitor?.protocol === "tcp" && monitor.port ? String(monitor.port) : "")const [server, setServer] = useState(monitor?.protocol === "dns" ? (monitor.server ?? "") : "")const [monitorInterval, setMonitorInterval] = useState(String(monitor?.interval ?? defaultInterval))+ const [skipTlsVerify, setSkipTlsVerify] = useState(monitor?.skipTlsVerify ?? false)const [loading, setLoading] = useState(false)const [selectedSystemId, setSelectedSystemId] = useState(monitor?.system ?? "")const [selectedSystemIds, setSelectedSystemIds] = useState<Set<string>>(new Set())@@ -728,6 +739,8 @@ function MonitorDialogContent({const { t } = useLingui()const isEditing = !!monitorconst dnsTargetIsIp = protocol === "dns" && isIpAddress(target.trim())+ // Bare hostnames are normalized to https, so they can also skip verification.+ const usesTls = protocol === "http" && !/^http:\/\//i.test(target.trim())// When the dialog is opened, initialize form fields with monitor values (if editing) or defaults (if adding).useEffect(() => {@@ -740,6 +753,7 @@ function MonitorDialogContent({setPort(monitor?.protocol === "tcp" && monitor.port ? String(monitor.port) : "")setServer(monitor?.protocol === "dns" ? (monitor.server ?? "") : "")setMonitorInterval(String(monitor?.interval ?? defaultInterval))+ setSkipTlsVerify(monitor?.skipTlsVerify ?? false)setSelectedSystemId(monitor?.system ?? "")setSelectedSystemIds(new Set())setLoading(false)@@ -761,6 +775,7 @@ function MonitorDialogContent({port: protocol === "tcp" ? Number(port) : 0,server: protocol === "dns" ? server.trim() : "",interval: monitorInterval,+ skipTlsVerify,},monitor ? monitor.enabled : true)@@ -910,6 +925,22 @@ function MonitorDialogContent({required/></div>+ {usesTls && (+ <label+ htmlFor="monitor-skip-tls-verify"+ className="flex items-center justify-between gap-4 cursor-pointer rounded-lg border border-muted-foreground/15 hover:border-muted-foreground/20 transition-colors duration-100 px-3.5 py-3"+ >+ <div className="grid gap-1 select-none">+ <span className="text-sm font-medium">+ <Trans>Ignore TLS certificate errors</Trans>+ </span>+ <span className="text-xs text-muted-foreground">+ <Trans>Use for self-signed certificates.</Trans>+ </span>+ </div>+ <Switch id="monitor-skip-tls-verify" checked={skipTlsVerify} onCheckedChange={setSkipTlsVerify} />+ </label>+ )}<DialogFooter>{!isEditing && onOpenBulkAdd && (<Buttondiff --git a/internal/site/src/components/network-monitors-table/network-monitors-columns.tsx b/internal/site/src/components/network-monitors-table/network-monitors-columns.tsxindex 91dde913b..e8b3e26e8 100644--- a/internal/site/src/components/network-monitors-table/network-monitors-columns.tsx+++ b/internal/site/src/components/network-monitors-table/network-monitors-columns.tsx@@ -16,6 +16,7 @@ import {PlayCircleIcon,CopyIcon,ShieldCheckIcon,+ ShieldOffIcon,} from "lucide-react"import { t } from "@lingui/core/macro"import type { NetworkMonitorRecord, SystemRecord } from "@/types"@@ -50,6 +51,8 @@ const protocolColors: Record<string, string> = {tcp: "bg-purple-500/15! text-purple-600 dark:text-purple-400",http: "bg-green-500/15! text-green-700 dark:text-green-400",dns: "bg-amber-500/15! text-amber-600 dark:text-amber-400",+ // HTTP monitors that skip TLS certificate verification+ insecure: "bg-orange-500/15! text-orange-600 dark:text-orange-400",}const SYSTEM_STATUS_COLORS = {@@ -175,8 +178,16 @@ export function getMonitorColumns(meta: { label: t`Protocol` },accessorFn: (record) => record.protocol,header: ({ column }) => <HeaderButton column={column} name={t`Protocol`} Icon={ArrowLeftRightIcon} />,- cell: ({ getValue }) => {+ cell: ({ row, getValue }) => {const protocol = getValue() as string+ if (row.original.skipTlsVerify) {+ return (+ <Badge className={cn("uppercase gap-1", protocolColors.insecure)}>+ {protocol}+ <ShieldOffIcon className="size-3" />+ </Badge>+ )+ }return <Badge className={cn("uppercase", protocolColors[protocol])}>{protocol}</Badge>},},diff --git a/internal/site/src/lib/use-network-monitors.ts b/internal/site/src/lib/use-network-monitors.tsindex 95e636eb4..00f7e1f31 100644--- a/internal/site/src/lib/use-network-monitors.ts+++ b/internal/site/src/lib/use-network-monitors.ts@@ -82,7 +82,7 @@ async function fetchMonitorStats(}const NETWORK_MONITOR_FIELDS =- "id,system,target,protocol,port,server,interval,res,resMin1h,resMax1h,resAvg1h,loss1h,enabled,certInfo,updated"+ "id,system,target,protocol,port,server,interval,skipTlsVerify,res,resMin1h,resMax1h,resAvg1h,loss1h,enabled,certInfo,updated"interface UseNetworkMonitorsProps {systemId?: stringdiff --git a/internal/site/src/types.d.ts b/internal/site/src/types.d.tsindex 45e3d0fab..38febbe6f 100644--- a/internal/site/src/types.d.ts+++ b/internal/site/src/types.d.ts@@ -694,6 +694,8 @@ export interface NetworkMonitorRecord {protocol: "icmp" | "tcp" | "http" | "dns"port: numberserver: string+ /** Skip TLS certificate verification for HTTPS targets. */+ skipTlsVerify: booleanres: numberresMin1h: numberresMax1h: number