hub + installer (unreleased): fixes after an independent review of the night's code — per-thing mail cooldown, a box's input bounded and checked, both off-site account types on a reset, a quiet first run, strict-mode installer

Claude-Session: https://claude.ai/code/session_0159rPz1ZhFKsS53msqPYxtS
This commit is contained in:
admin committed 2026-11-14 19:08:55 +01:00
1 parent a044eb8c16
commit f618c591eb
31 files changed
+796 -88

No files matched your search

+1 -1
View File
@@ -82,7 +82,7 @@ func (l *DailyLedger) Started(name string, now time.Time, hour, min int, loc *ti
msg := fmt.Sprintf("The hub's daily check „%s” did NOT run at %s: the hub was not running at that minute. It last ran at %s (%d slot(s) missed). The hub does not run it late. %s",
name, prev.Format("2006-01-02 15:04 MST"), last.In(loc).Format("2006-01-02 15:04 MST"), missed, dailySkipAdvice(name))
details, _ := json.Marshal(map[string]any{"job": name, "missed_slot": prev.UTC().Format(time.RFC3339),
"last_run": last.UTC().Format(time.RFC3339), "missed": missed})
"last_run": last.UTC().Format(time.RFC3339), "missed": missed, "subject": name})
if l.onEvent != nil {
l.onEvent("", EventDailyJobSkipped, "warning", msg, string(details), "hub")
}
+56 -24
View File
@@ -22,14 +22,15 @@ import (
// 0.352.1). Traefik renews 30 days before the end by itself — so 14 days left means the renewal has failed for
// two weeks (a Cloudflare token of the household that ended, a name check that fails).
//
// One event per (token) and per (household, name, end date): told once at 14 days, and once more — as an ERROR — if
// the date passes with the same certificate or token still there. A renewed certificate has a new end date, so
// nothing has to clear. State: the hub's time-by-key settings, no new table. Operator-only. Pinned by TestEndDates_*.
// One event per token and per (household, name): told once at 14 days, and once more — as an ERROR — if the date
// passes with the same certificate or token still there. A renewed certificate has a later end date and is told
// again only when THAT one comes within 14 days, so nothing has to clear. State: the hub's time-by-key settings, no new table. Operator-only. Pinned by TestEndDates_*.
type EndDateChecker struct {
tokens func() ([]EndingToken, error)
reports func() ([]BoxCertReport, error)
told func(key string) time.Time
setTold func(key string, t time.Time) error
keys func(prefix string) []string // the marks under a prefix (store.OSAlarmKeys)
onEvent EventNotifyFunc
logger *log.Logger
now func() time.Time
@@ -59,6 +60,7 @@ const (
endDateWarnDays = 14
endDateCheckEvery = time.Hour
webCertsReadMax = 8
webCertMaxMarks = 24 // per household: names × two stages
)
var endDateNameRe = regexp.MustCompile(`^[A-Za-z0-9*._-]{1,253}$`)
@@ -67,8 +69,8 @@ var endDateNameRe = regexp.MustCompile(`^[A-Za-z0-9*._-]{1,253}$`)
var endDateTokenNameRe = regexp.MustCompile(`^[A-Za-z0-9 ._-]{1,64}$`)
func NewEndDateChecker(tokens func() ([]EndingToken, error), reports func() ([]BoxCertReport, error),
told func(string) time.Time, setTold func(string, time.Time) error, onEvent EventNotifyFunc, logger *log.Logger) *EndDateChecker {
return &EndDateChecker{tokens: tokens, reports: reports, told: told, setTold: setTold, onEvent: onEvent, logger: logger,
told func(string) time.Time, setTold func(string, time.Time) error, keys func(string) []string, onEvent EventNotifyFunc, logger *log.Logger) *EndDateChecker {
return &EndDateChecker{tokens: tokens, reports: reports, told: told, setTold: setTold, keys: keys, onEvent: onEvent, logger: logger,
now: time.Now, every: endDateCheckEvery, warnDays: endDateWarnDays}
}
@@ -82,24 +84,19 @@ func (c *EndDateChecker) Check() {
}
c.lastRun = now
warn := time.Duration(c.warnDays) * 24 * time.Hour
// The FIRST run ever (a first deploy): a thing that has ALREADY ended is marked and not told — an old token that
// was replaced long ago and never revoked is no news. What ends within the 14 days is told as always.
baseline := c.told("end_date:baseline").IsZero()
// stage: "soon" inside the 14 days, "ended" from the end date on. Each stage is told once per key.
tell := func(key string, end time.Time) (stage string, ok bool) {
stageOf := func(end time.Time) string {
left := end.Sub(now)
switch {
case left > warn || left < -warn:
return "", false // not yet — or ended so long ago that it is no news (an old token nobody replaced)
return "" // not yet — or ended so long ago that it is no news
case left > 0:
stage = "soon"
default:
stage = "ended"
return "soon"
}
k := key + ":" + stage
if !c.told(k).IsZero() {
return stage, false
}
_ = c.setTold(k, now)
return stage, true
return "ended"
}
daysLeft := func(end time.Time) int { return int(end.Sub(now) / (24 * time.Hour)) }
@@ -107,8 +104,16 @@ func (c *EndDateChecker) Check() {
c.logger.Printf("[WARN] end-date check: cannot list the operator tokens: %v", err)
} else {
for _, t := range toks {
stage, ok := tell(fmt.Sprintf("end_date:token:%d", t.ID), t.ExpiresAt)
if !ok {
stage := stageOf(t.ExpiresAt)
if stage == "" {
continue
}
k := fmt.Sprintf("end_date:token:%d:%s", t.ID, stage)
if !c.told(k).IsZero() {
continue
}
_ = c.setTold(k, now)
if baseline && stage == "ended" {
continue
}
name := t.Name
@@ -118,11 +123,12 @@ func (c *EndDateChecker) Check() {
sev, msg := "warning", fmt.Sprintf("The operator access token „%s” ends in %d day(s), on %s. On that day every script that uses it gets 401 (for one: the release step that raises the floor). Do: make a new token on the hub's Tokens page and put it in the store of the program that uses it.",
name, daysLeft(t.ExpiresAt), t.ExpiresAt.UTC().Format("2006-01-02"))
if stage == "ended" {
sev, msg = "error", fmt.Sprintf("The operator access token „%s” ENDED on %s and is not replaced: every script that uses it gets 401. Do: make a new token on the hub's Tokens page.",
sev, msg = "error", fmt.Sprintf("The operator access token „%s” ENDED on %s and is not revoked: every script that still uses it gets 401. Do: if it was replaced, revoke it on the hub's Tokens page; if not, make a new token.",
name, t.ExpiresAt.UTC().Format("2006-01-02"))
}
c.logger.Printf("[WARN] end-date check: operator token %d (%s) %s — ends %s", t.ID, name, stage, t.ExpiresAt.UTC().Format(time.RFC3339))
details, _ := json.Marshal(map[string]any{"token_id": t.ID, "name": name, "expires_at": t.ExpiresAt.UTC().Format(time.RFC3339), "stage": stage})
details, _ := json.Marshal(map[string]any{"token_id": t.ID, "name": name, "expires_at": t.ExpiresAt.UTC().Format(time.RFC3339),
"stage": stage, "subject": fmt.Sprintf("token:%d:%s", t.ID, stage)})
c.onEvent("", EventTokenEndsSoon, sev, msg, string(details), "hub")
}
}
@@ -138,9 +144,31 @@ func (c *EndDateChecker) Check() {
continue
}
seen[r.CustomerID] = true
// The names and dates are the BOX's. Its marks are keyed per (household, name, stage) and hold the END DATE
// that was told, so a box cannot mint a new mark, or a new mail, by sending another date each hour: a name is
// told again only for an end date at least a day LATER than the one told (a real renewal moves it by weeks),
// and one household holds at most webCertMaxMarks marks. (Review, 2026-11-14.)
prefix := "end_date:web_cert:" + r.CustomerID + ":"
marks := len(c.keys(prefix))
for _, wc := range parseWebCerts(r.ReportJSON) {
stage, ok := tell("end_date:web_cert:"+r.CustomerID+":"+wc.Domain+":"+wc.NotAfter.UTC().Format("20060102T150405Z"), wc.NotAfter)
if !ok {
stage := stageOf(wc.NotAfter)
if stage == "" {
continue
}
k := prefix + wc.Domain + ":" + stage
toldEnd := c.told(k)
if !toldEnd.IsZero() && !wc.NotAfter.After(toldEnd.Add(24*time.Hour)) {
continue
}
if toldEnd.IsZero() {
if marks >= webCertMaxMarks {
c.logger.Printf("[WARN] end-date check: %s already holds %d web-certificate marks — %s is not told", r.CustomerID, marks, wc.Domain)
continue
}
marks++
}
_ = c.setTold(k, wc.NotAfter)
if baseline && stage == "ended" {
continue
}
sev, msg := "warning", fmt.Sprintf("The web certificate of %s for %s ends in %d day(s), on %s. The box renews it by itself 30 days before the end, so the renewal has FAILED for about two weeks. On the end date every app address of the household shows a browser warning. Do: read the Traefik log on the box for „acme”; the usual cause is the household's Cloudflare token.",
@@ -150,10 +178,14 @@ func (c *EndDateChecker) Check() {
r.CustomerID, wc.Domain, wc.NotAfter.UTC().Format("2006-01-02"))
}
c.logger.Printf("[WARN] end-date check: web certificate of %s for %s %s — ends %s", r.CustomerID, wc.Domain, stage, wc.NotAfter.UTC().Format(time.RFC3339))
details, _ := json.Marshal(map[string]any{"domain": wc.Domain, "not_after": wc.NotAfter.UTC().Format(time.RFC3339), "stage": stage, "issuer": wc.Issuer})
details, _ := json.Marshal(map[string]any{"domain": wc.Domain, "not_after": wc.NotAfter.UTC().Format(time.RFC3339), "stage": stage,
"issuer": wc.Issuer, "subject": wc.Domain + ":" + stage})
c.onEvent(r.CustomerID, EventWebCertEndsSoon, sev, msg, string(details), "hub")
}
}
if baseline {
_ = c.setTold("end_date:baseline", now)
}
}
type webCert struct {
+59
View File
@@ -25,6 +25,15 @@ func newEndDateFix() *endDateFix {
func() ([]BoxCertReport, error) { return f.reps, nil },
func(k string) time.Time { return f.state[k] },
func(k string, t time.Time) error { f.state[k] = t; return nil },
func(prefix string) []string {
var out []string
for k := range f.state {
if strings.HasPrefix(k, prefix) {
out = append(out, k)
}
}
return out
},
func(cust, typ, sev, msg, details, src string) {
f.events = append(f.events, cust+"|"+typ+"|"+sev+"|"+msg+"|"+details)
}, log.New(io.Discard, "", 0))
@@ -149,3 +158,53 @@ func TestEndDates_TheBoxesWordsAreChecked(t *testing.T) {
t.Errorf("a token with a name that is not plain text must be named by its number:\n%s", all)
}
}
// Found by review, 2026-11-14. (1) The FIRST run after a deploy: a token that already ended, was replaced long ago and
// never revoked, must not mail „ENDED” — it is marked, not told; a thing that ends within the 14 days is still told.
// (2) The marks are the hub's settings and the names and dates are the box's: a box that sends another end date every
// hour, or new names every hour, must not mint a mail or a mark each time.
func TestEndDates_FirstRunAndABoxCannotMintMarks(t *testing.T) {
day := 24 * time.Hour
f := newEndDateFix()
f.tokens = []EndingToken{{ID: 1, Name: "replaced", ExpiresAt: f.now.Add(-3 * day)}, {ID: 2, Name: "soon", ExpiresAt: f.now.Add(5 * day)}}
f.reps = []BoxCertReport{{CustomerID: "old", ReportJSON: certReport(cert("gone.example.hu", f.now.Add(-2*day)))}}
f.step(0)
if len(f.events) != 1 || !strings.Contains(f.events[0], "„soon”") {
t.Fatalf("the first run: %v — want only the token that ends in 5 days", f.events)
}
f.step(2 * time.Hour)
f.step(2 * time.Hour)
if len(f.events) != 1 {
t.Fatalf("the already-ended things were told at a later run: %v", f.events[1:])
}
// after the first run, a token that ends is told as ended (the normal rule)
f.tokens = append(f.tokens, EndingToken{ID: 3, Name: "third", ExpiresAt: f.now.Add(-time.Hour)})
f.step(2 * time.Hour)
if len(f.events) != 2 || !strings.Contains(f.events[1], "„third” ENDED") {
t.Fatalf("a token that ended after the first run: %v", f.events[1:])
}
// a box that sends ANOTHER end date at every report
g := newEndDateFix()
g.step(0) // the baseline run
for i := 0; i < 48; i++ {
g.reps = []BoxCertReport{{CustomerID: "evil", ReportJSON: certReport(cert("x.example.hu", g.now.Add(5*day+time.Duration(i)*time.Minute)))}}
g.step(61 * time.Minute)
}
if len(g.events) > 3 {
t.Fatalf("a box that moves its end date by a minute each hour got %d mails in two days (want at most a few: a new mail needs a date a day later)", len(g.events))
}
marksBefore := len(g.state)
// and a box that sends eight NEW names every hour
for i := 0; i < 24; i++ {
var cs []string
for n := 0; n < 8; n++ {
cs = append(cs, cert(fmt.Sprintf("h%dn%d.example.hu", i, n), g.now.Add(6*day)))
}
g.reps = []BoxCertReport{{CustomerID: "evil", ReportJSON: certReport(cs...)}}
g.step(61 * time.Minute)
}
if grew := len(g.state) - marksBefore; grew > webCertMaxMarks {
t.Fatalf("192 invented names made %d marks, want at most %d for one household", grew, webCertMaxMarks)
}
}
+2 -2
View File
@@ -65,10 +65,10 @@ func (c *SignedJobWaitChecker) Check() {
_ = c.setTold(key, now)
waited := now.Sub(j.CreatedAt).Round(time.Minute)
c.logger.Printf("[WARN] signed job %s for host %s was not taken (in the queue for %s)", j.JobID, j.HostID, waited)
msg := fmt.Sprintf("The signed job %s for %s is still in the queue after %s: the box did not take it. A box asks for its jobs every 15 minutes, so the box is off, cannot reach the hub, or its agent does not run. The job's validity has probably run out. Do: read why the box does not report, then sign a new job.",
msg := fmt.Sprintf("The signed job %s for %s is still in the queue after %s: the box did not take it. A box asks for its jobs every 15 minutes, so one of these is true: the box is off, it cannot reach the hub, its agent does not run — or its agent is too old to know this kind of job and leaves it in the queue on purpose. The job's validity has probably run out. Do: read the box's last report and its agent version, then sign a new job.",
j.JobID, j.HostID, waited)
details, _ := json.Marshal(map[string]any{"host_id": j.HostID, "job_id": j.JobID,
"queued_at": j.CreatedAt.UTC().Format(time.RFC3339), "waited_minutes": int(waited / time.Minute)})
"queued_at": j.CreatedAt.UTC().Format(time.RFC3339), "waited_minutes": int(waited / time.Minute), "subject": j.HostID + ":" + j.JobID})
if c.onEvent != nil {
c.onEvent(c.customer(j.HostID), EventSignedJobNotTaken, "warning", msg, string(details), "hub")
}