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
This commit is contained in:
admin committed 2026-11-15 15:22:49 +01:00
1 parent c616727d84
commit c72ecf52b4
8 files changed
+616 -5

No files matched your search

+164
View File
@@ -0,0 +1,164 @@
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")
}
}
+236
View File
@@ -0,0 +1,236 @@
package monitor
import (
"context"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/tls"
"crypto/x509"
"crypto/x509/pkix"
"errors"
"io"
"log"
"math/big"
"net"
"strings"
"testing"
"time"
)
// ownBox is the checker with the hub's settings in a map and its events in a list.
type ownBox struct {
marks map[string]time.Time
events []string // "type|severity|message|details"
ends map[string]time.Time
down map[string]bool
dials []string
now time.Time
c *OwnNameChecker
}
func newOwnBox(names ...string) *ownBox {
b := &ownBox{marks: map[string]time.Time{}, ends: map[string]time.Time{}, down: map[string]bool{},
now: time.Date(2026, 11, 15, 6, 0, 0, 0, time.UTC)}
b.c = NewOwnNameChecker(names,
func(_ context.Context, addr, server string) (time.Time, error) {
b.dials = append(b.dials, addr+"|"+server)
if b.down[server] {
return time.Time{}, errors.New("dial tcp: connection refused")
}
return b.ends[server], nil
},
func(k string) time.Time { return b.marks[k] },
func(k string, t time.Time) error {
if t.IsZero() {
delete(b.marks, k)
} else {
b.marks[k] = t
}
return nil
},
func(customer, typ, sev, msg, details, source string) {
b.events = append(b.events, typ+"|"+sev+"|"+customer+"|"+source+"|"+msg+"|"+details)
}, log.New(io.Discard, "", 0))
b.c.now = func() time.Time { return b.now }
return b
}
func (b *ownBox) count(typ string) int {
n := 0
for _, e := range b.events {
if strings.HasPrefix(e, typ+"|") {
n++
}
}
return n
}
// The consequence: 14 days before a name's certificate ends the operator gets ONE warning that names the name and
// the day; a name that is far from its end gets none; the next day's run does not tell it again.
func TestOwnNames_WarnsOncePerNameFourteenDaysBefore(t *testing.T) {
b := newOwnBox("hub.example.test", "iso.example.test", "far.example.test")
b.ends["hub.example.test"] = b.now.Add(13*24*time.Hour + time.Hour)
b.ends["iso.example.test"] = b.now.Add(3 * 24 * time.Hour)
b.ends["far.example.test"] = b.now.Add(60 * 24 * time.Hour)
b.c.CheckOnce()
if b.count(EventHubNameEndsSoon) != 2 {
t.Fatalf("want one warning for each of the two near names, got %d: %v", b.count(EventHubNameEndsSoon), b.events)
}
for _, e := range b.events {
if strings.Contains(e, "far.example.test") {
t.Fatalf("a name 60 days from its end was told: %s", e)
}
if !strings.HasPrefix(e, EventHubNameEndsSoon+"|warning||hub|") {
t.Fatalf("not an operator-level warning from the hub with no household: %s", e)
}
}
if !strings.Contains(b.events[0], "hub.example.test ends in 13 day(s), on 2026-11-28") || !strings.Contains(b.events[0], `"subject":"hub.example.test:soon"`) {
t.Fatalf("the warning does not name the name, the days and the day, or has no subject: %s", b.events[0])
}
b.now = b.now.Add(24 * time.Hour)
b.c.CheckOnce()
if b.count(EventHubNameEndsSoon) != 2 {
t.Fatalf("the same certificate was told again the next day: %v", b.events)
}
}
// Exactly on the line: 14 days and one second is not told; 14 days is.
func TestOwnNames_TheLineIsFourteenDays(t *testing.T) {
b := newOwnBox("a.example.test")
b.ends["a.example.test"] = b.now.Add(14*24*time.Hour + time.Second)
b.c.CheckOnce()
if len(b.events) != 0 {
t.Fatalf("told at 14 days and one second: %v", b.events)
}
b.ends["a.example.test"] = b.now.Add(14 * 24 * time.Hour)
b.c.CheckOnce()
if b.count(EventHubNameEndsSoon) != 1 {
t.Fatalf("not told at 14 days: %v", b.events)
}
}
// A certificate that has ended and is still served is told once more, as an ERROR — and a renewal ends the matter:
// the renewed certificate is told only when IT comes near its end.
func TestOwnNames_EndedIsAnErrorAndARenewalIsNewNews(t *testing.T) {
b := newOwnBox("a.example.test")
b.ends["a.example.test"] = b.now.Add(5 * 24 * time.Hour)
b.c.CheckOnce()
b.now = b.now.Add(6 * 24 * time.Hour) // the date passed, the same certificate is served
b.c.CheckOnce()
b.c.CheckOnce()
if b.count(EventHubNameEndsSoon) != 2 || !strings.HasPrefix(b.events[1], EventHubNameEndsSoon+"|error|") || !strings.Contains(b.events[1], "ENDED on 2026-11-20") {
t.Fatalf("want one warning then one error for the ended certificate: %v", b.events)
}
b.ends["a.example.test"] = b.now.Add(90 * 24 * time.Hour) // renewed
b.c.CheckOnce()
if b.count(EventHubNameEndsSoon) != 2 {
t.Fatalf("a renewed certificate was told: %v", b.events)
}
b.now = b.now.Add(80 * 24 * time.Hour) // the RENEWED one is 10 days from its end
b.c.CheckOnce()
if b.count(EventHubNameEndsSoon) != 3 || !strings.Contains(b.events[2], "|warning|") {
t.Fatalf("the renewed certificate's own end was not told: %v", b.events)
}
}
// A name that does not answer is its OWN line — never an end-date alarm — told once while it lasts, and cleared by
// the first good read. And a name that is down does not stop the names after it.
func TestOwnNames_ANameThatDoesNotAnswerIsNotAnEndDateAlarm(t *testing.T) {
b := newOwnBox("down.example.test", "near.example.test")
b.down["down.example.test"] = true
b.ends["near.example.test"] = b.now.Add(2 * 24 * time.Hour)
b.c.CheckOnce()
b.c.CheckOnce()
if b.count(EventHubNameUnreachable) != 1 {
t.Fatalf("want ONE unreachable line for two runs, got %d: %v", b.count(EventHubNameUnreachable), b.events)
}
for _, e := range b.events {
if strings.HasPrefix(e, EventHubNameEndsSoon) && strings.Contains(e, "down.example.test") {
t.Fatalf("a name that did not answer raised an END-DATE alarm: %s", e)
}
}
if b.count(EventHubNameEndsSoon) != 1 {
t.Fatalf("the name after the dead one was not read: %v", b.events)
}
// it answers again, with a certificate far from its end: one „answers again”, no end-date alarm, and a later
// outage is told again
b.down["down.example.test"] = false
b.ends["down.example.test"] = b.now.Add(60 * 24 * time.Hour)
b.c.CheckOnce()
if b.count(EventHubNameReachable) != 1 || len(b.marks) != 1 {
t.Fatalf("the recovery was not told once, or its mark stayed: events %v marks %v", b.events, b.marks)
}
b.down["down.example.test"] = true
b.c.CheckOnce()
if b.count(EventHubNameUnreachable) != 2 {
t.Fatalf("a second outage was not told: %v", b.events)
}
}
// The setting is the only source of names, and only plain host names are ever dialled: `host` goes to port 443 with
// the host as the TLS name; `host:port` keeps its port.
func TestOwnNames_OnlyPlainHostNamesFromTheSettingAreDialled(t *testing.T) {
names, bad := ParseOwnNames("hub.example.test, ISO.example.test:8443 ,https://evil.example/x, a..b, user@host, ,hub.example.test, 10.0.0.1")
if strings.Join(names, " ") != "hub.example.test iso.example.test:8443 10.0.0.1" {
t.Fatalf("names = %q", names)
}
if len(bad) != 3 {
t.Fatalf("want three refused entries (a URL, a double dot, a user@), got %q", bad)
}
b := newOwnBox(names...)
for _, n := range []string{"hub.example.test", "iso.example.test", "10.0.0.1"} {
b.ends[n] = b.now.Add(60 * 24 * time.Hour)
}
b.c.CheckOnce()
if strings.Join(b.dials, " ") != "hub.example.test:443|hub.example.test iso.example.test:8443|iso.example.test 10.0.0.1:443|10.0.0.1" {
t.Fatalf("dialled %q", b.dials)
}
many, bad2 := ParseOwnNames(strings.Repeat("a.example.test b.example.test c.example.test ", 1) + "d1.t d2.t d3.t d4.t d5.t d6.t d7.t d8.t d9.t d10.t d11.t d12.t d13.t d14.t")
if len(many) != 16 || len(bad2) != 1 {
t.Fatalf("the list is not capped at 16: %d names, %d refused", len(many), len(bad2))
}
if n, _ := ParseOwnNames(""); len(n) != 0 {
t.Fatalf("an empty setting gave names: %q", n)
}
}
// The real read against a real TLS server on this machine: the end date that comes back is the served certificate's
// — also for a certificate that has ALREADY ended (a verified handshake would refuse it and give no date).
func TestOwnNames_DialCertEndReadsTheServedDate_AlsoOfAnEndedCertificate(t *testing.T) {
for _, end := range []time.Time{time.Now().Add(9 * 24 * time.Hour), time.Now().Add(-3 * 24 * time.Hour)} {
end = end.UTC().Truncate(time.Second)
key, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
tmpl := &x509.Certificate{SerialNumber: big.NewInt(1), Subject: pkix.Name{CommonName: "own.example.test"},
NotBefore: end.Add(-90 * 24 * time.Hour), NotAfter: end, DNSNames: []string{"own.example.test"}}
der, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, &key.PublicKey, key)
if err != nil {
t.Fatal(err)
}
ln, err := tls.Listen("tcp", "127.0.0.1:0", &tls.Config{Certificates: []tls.Certificate{{Certificate: [][]byte{der}, PrivateKey: key}}})
if err != nil {
t.Fatal(err)
}
go func() {
for {
c, err := ln.Accept()
if err != nil {
return
}
go func() { _ = c.(*tls.Conn).Handshake(); c.Close() }()
}
}()
got, err := DialCertEnd(context.Background(), ln.Addr().String(), "own.example.test")
ln.Close()
if err != nil || !got.Equal(end) {
t.Fatalf("served end %s, read %s (err %v)", end, got, err)
}
}
// nothing listens: an error, not a date
ln, _ := net.Listen("tcp", "127.0.0.1:0")
addr := ln.Addr().String()
ln.Close()
if got, err := DialCertEnd(context.Background(), addr, "own.example.test"); err == nil {
t.Fatalf("a dead address gave a date: %s", got)
}
}