Files
felhom.eu/hub/internal/monitor/own_names.go
T
admin c72ecf52b4 hub (unreleased): the end dates of the hub's own public names are read once a day; 14 days before, the operator is told (D85, R-1379)
The names are the setting HUB_OWN_NAMES; with no setting the hub makes no call. The setting is NOT in the manifest yet.

Claude-Session: https://claude.ai/code/session_0159rPz1ZhFKsS53msqPYxtS
2026-11-15 15:22:49 +01:00

165 lines
7.5 KiB
Go

package monitor
import (
"context"
"crypto/tls"
"encoding/json"
"fmt"
"log"
"net"
"regexp"
"strings"
"sync"
"time"
)
// OwnNameChecker (R-1379, D85, `09` §3 decision 310; `08-alarm-ladder.md` §12.3) reads, once a day, the end date of
// the certificate that each of the hub's OWN public names serves, and warns the operator 14 days before. The third
// source beside an operator token and a box's web certificate (EndDateChecker): if the hub's own name ends, every box
// fails to report and the hub then sees all of them as silent — and nothing in the product warned before that day.
//
// The names are CONFIGURATION (the hub's HUB_OWN_NAMES setting), never code and never a box's word: this checker
// opens connections from the hub to outside names, so the list is the operator's.
//
// Two things, kept apart:
// - an END DATE within 14 days (or passed): the operator-only alarm `hub_name_cert_ends_soon`, told once per
// (name, stage); a renewed certificate has a later date and is told again only when that one comes near.
// - a name that CANNOT BE REACHED: its own operator-only line `hub_name_unreachable`, told once per name while it
// lasts and cleared by the first good read (`hub_name_reachable`). It is never an end-date alarm: „the name did
// not answer” says nothing about its certificate.
//
// The certificate is read whatever its state (no chain check): a certificate that has ENDED must still give its date.
// State: the hub's time-by-key settings. Pinned by TestOwnNames_*.
type OwnNameChecker struct {
names []string
dial func(ctx context.Context, addr, serverName string) (notAfter time.Time, err error)
told func(key string) time.Time
setTold func(key string, t time.Time) error
onEvent EventNotifyFunc
logger *log.Logger
now func() time.Time
mu sync.Mutex
}
const (
EventHubNameEndsSoon = "hub_name_cert_ends_soon"
EventHubNameUnreachable = "hub_name_unreachable"
EventHubNameReachable = "hub_name_reachable"
ownNamesMax = 16
ownNameDialTimeout = 15 * time.Second
)
// a host name, with an optional port. Nothing else from the setting is ever dialled.
var ownNameRe = regexp.MustCompile(`^[a-z0-9]([a-z0-9.-]{0,251}[a-z0-9])?(:[0-9]{1,5})?$`)
// ParseOwnNames reads the setting: names separated by commas or spaces, each `host` or `host:port`. A name that is
// not a plain host name is dropped and returned in `bad`, so the start line can say so. At most ownNamesMax names.
func ParseOwnNames(setting string) (names, bad []string) {
seen := map[string]bool{}
for _, f := range strings.FieldsFunc(setting, func(r rune) bool { return r == ',' || r == ' ' || r == '\n' || r == '\t' }) {
n := strings.ToLower(strings.TrimSpace(f))
if n == "" || seen[n] {
continue
}
seen[n] = true
if !ownNameRe.MatchString(n) || strings.Contains(n, "..") || len(names) >= ownNamesMax {
bad = append(bad, f)
continue
}
names = append(names, n)
}
return names, bad
}
// DialCertEnd is the real read: one TLS handshake, the leaf's end date, nothing sent after it.
func DialCertEnd(ctx context.Context, addr, serverName string) (time.Time, error) {
d := &tls.Dialer{NetDialer: &net.Dialer{Timeout: ownNameDialTimeout},
// No chain check ON PURPOSE: the date of a certificate that has already ended is exactly what must be read.
// Nothing is trusted from this connection and nothing is sent over it.
Config: &tls.Config{ServerName: serverName, InsecureSkipVerify: true, MinVersion: tls.VersionTLS12}}
conn, err := d.DialContext(ctx, "tcp", addr)
if err != nil {
return time.Time{}, err
}
defer conn.Close()
certs := conn.(*tls.Conn).ConnectionState().PeerCertificates
if len(certs) == 0 {
return time.Time{}, fmt.Errorf("the name served no certificate")
}
return certs[0].NotAfter, nil
}
func NewOwnNameChecker(names []string, dial func(context.Context, string, string) (time.Time, error),
told func(string) time.Time, setTold func(string, time.Time) error, onEvent EventNotifyFunc, logger *log.Logger) *OwnNameChecker {
return &OwnNameChecker{names: names, dial: dial, told: told, setTold: setTold, onEvent: onEvent, logger: logger, now: time.Now}
}
// Names is the list the checker reads (for the start line).
func (c *OwnNameChecker) Names() []string { return append([]string(nil), c.names...) }
// CheckOnce reads every name once. It is the body of the hub's daily job „own-names-check” (the daily ledger tells
// the operator when that job was skipped).
func (c *OwnNameChecker) CheckOnce() {
c.mu.Lock()
defer c.mu.Unlock()
now := c.now()
warn := time.Duration(endDateWarnDays) * 24 * time.Hour
for _, name := range c.names {
host, addr := name, name
if h, _, err := net.SplitHostPort(name); err == nil {
host = h
} else {
addr = net.JoinHostPort(name, "443")
}
ctx, cancel := context.WithTimeout(context.Background(), ownNameDialTimeout)
end, err := c.dial(ctx, addr, host)
cancel()
downKey := "own_name:unreachable:" + name
if err != nil {
c.logger.Printf("[WARN] own-names check: %s did not answer: %v", name, err)
if c.told(downKey).IsZero() {
_ = c.setTold(downKey, now)
details, _ := json.Marshal(map[string]any{"name": name, "subject": name})
c.onEvent("", EventHubNameUnreachable, "warning",
fmt.Sprintf("The hub could not read the certificate of its own name %s today: the name did not answer a TLS connection from the hub. This is NOT an end-date warning — the end date of that certificate is not known today. Do: open the address in a browser; if it answers, the fault is on the hub's way out.", name),
string(details), "hub")
}
continue
}
if !c.told(downKey).IsZero() {
_ = c.setTold(downKey, time.Time{}) // a zero time deletes the mark
details, _ := json.Marshal(map[string]any{"name": name, "subject": name})
c.onEvent("", EventHubNameReachable, "info", fmt.Sprintf("The hub's own name %s answers again; its certificate ends on %s.", name, end.UTC().Format("2006-01-02")), string(details), "hub")
}
left := end.Sub(now)
stage := ""
switch {
case left > warn:
case left > 0:
stage = "soon"
default:
stage = "ended"
}
c.logger.Printf("[INFO] own-names check: %s ends %s (%d day(s) left)", name, end.UTC().Format("2006-01-02"), int(left/(24*time.Hour)))
if stage == "" {
continue
}
// The mark holds the END DATE that was told: the same certificate is told once per stage; a certificate with a
// later date (a renewal that is itself near its end, which does not happen with a 90-day certificate) again.
k := "end_date:hub_name:" + name + ":" + stage
if toldEnd := c.told(k); !toldEnd.IsZero() && !end.After(toldEnd.Add(24*time.Hour)) {
continue
}
_ = c.setTold(k, end)
sev, msg := "warning", fmt.Sprintf("The certificate of the hub's own name %s ends in %d day(s), on %s. It renews by itself about 30 days before the end, so the renewal has FAILED for about two weeks. On the end date every box that uses this name stops (for the hub's address: no report, no alarm, no update). Do: read the certificate's state on the machine that serves the name.",
name, int(left/(24*time.Hour)), end.UTC().Format("2006-01-02"))
if stage == "ended" {
sev, msg = "error", fmt.Sprintf("The certificate of the hub's own name %s ENDED on %s and is still served: every box that uses this name fails now. Do: renew the certificate on the machine that serves the name.",
name, end.UTC().Format("2006-01-02"))
}
details, _ := json.Marshal(map[string]any{"name": name, "not_after": end.UTC().Format(time.RFC3339), "stage": stage, "subject": name + ":" + stage})
c.onEvent("", EventHubNameEndsSoon, sev, msg, string(details), "hub")
}
}