package monitor
import (
"fmt"
"io"
"log"
"strings"
"testing"
"time"
)
type endDateFix struct {
now time.Time
tokens []EndingToken
reps []BoxCertReport
state map[string]time.Time
events []string
c *EndDateChecker
}
func newEndDateFix() *endDateFix {
f := &endDateFix{now: time.Date(2026, 11, 14, 12, 0, 0, 0, time.UTC), state: map[string]time.Time{}}
f.c = NewEndDateChecker(
func() ([]EndingToken, error) { return f.tokens, nil },
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))
f.c.now = func() time.Time { return f.now }
return f
}
// step moves the clock (past the hourly throttle) and runs the check.
func (f *endDateFix) step(d time.Duration) { f.now = f.now.Add(d); f.c.Check() }
func certReport(certs ...string) string { return `{"web_certs":[` + strings.Join(certs, ",") + `]}` }
func cert(domain string, at time.Time) string {
return fmt.Sprintf(`{"domain":%q,"not_after":%q,"issuer":"YR2"}`, domain, at.UTC().Format(time.RFC3339))
}
// R-1379 (D77): the operator is warned 14 days before an end date — not at 15, once at 14, not again every hour, once
// more (as an error) when the date passes with the same thing still there, and never for a token or certificate that
// was renewed. The stored effect asserted is the event. Both kinds, one test each way.
// COMPANION RED-PROOFS (observed, audits/night-build-2026-11-14/B/redproof-hub-end-dates.txt).
func TestEndDates_FourteenDaysOnceThenEndedOnce(t *testing.T) {
f := newEndDateFix()
day := 24 * time.Hour
tokEnd := f.now.Add(16*day + time.Hour)
certEnd := f.now.Add(16*day + 2*time.Hour)
f.tokens = []EndingToken{{ID: 7, Name: "CC hub token", ExpiresAt: tokEnd}, {ID: 8, Name: "fresh", ExpiresAt: f.now.Add(80 * day)}}
f.reps = []BoxCertReport{{CustomerID: "demo-hp", ReportJSON: certReport(cert("*.enkisfelhom.hu", certEnd))},
{CustomerID: "old-box", ReportJSON: `{"health":{"status":"ok"}}`}} // a controller that sends no web_certs
f.step(0)
f.step(day) // 15 days and a bit left
if len(f.events) != 0 {
t.Fatalf("at more than 14 days: %v", f.events)
}
f.step(2 * day) // 13 days and a bit left
for i := 0; i < 30; i++ {
f.step(2 * time.Hour)
}
if len(f.events) != 2 {
t.Fatalf("inside the 14 days, 31 hourly checks: %d event(s), want ONE per end date: %v", len(f.events), f.events)
}
all := strings.Join(f.events, "\n")
for _, want := range []string{"|operator_token_ends_soon|warning|", "„CC hub token”", tokEnd.Format("2006-01-02"), "401",
"demo-hp|web_cert_ends_soon|warning|", "*.enkisfelhom.hu", certEnd.Format("2006-01-02"), "renewal has FAILED", `"issuer":"YR2"`} {
if !strings.Contains(all, want) {
t.Errorf("the events lack %q:\n%s", want, all)
}
}
if !strings.HasPrefix(f.events[0], "|") {
t.Errorf("the token's event must carry no household: %s", f.events[0])
}
// the end dates pass, nothing was renewed: one ERROR each, once
f.now = certEnd.Add(time.Hour)
f.c.Check()
f.step(2 * time.Hour)
if len(f.events) != 4 || !strings.Contains(f.events[2]+f.events[3], "ENDED on") || strings.Count(f.events[2]+f.events[3], "|error|") != 2 {
t.Fatalf("after the end date: %v", f.events[2:])
}
}
// A renewed certificate has a new end date: nothing is told. A certificate that is renewed AFTER the warning needs no
// „all clear” — and a later failure of the new one is told again. Old things are no news: a token that ended months
// ago, and nobody replaced, raises nothing when the checker first runs.
func TestEndDates_RenewedAndLongGoneAreQuiet(t *testing.T) {
f := newEndDateFix()
day := 24 * time.Hour
f.tokens = []EndingToken{{ID: 1, Name: "old", ExpiresAt: f.now.Add(-120 * day)}}
f.reps = []BoxCertReport{{CustomerID: "n100", ReportJSON: certReport(cert("*.example.hu", f.now.Add(40*day)))}}
f.step(0)
f.step(2 * time.Hour)
if len(f.events) != 0 {
t.Fatalf("a token that ended 120 days ago and a certificate 40 days out: %v", f.events)
}
f.reps[0].ReportJSON = certReport(cert("*.example.hu", f.now.Add(10*day)))
f.step(2 * time.Hour)
if len(f.events) != 1 {
t.Fatalf("10 days left: %v", f.events)
}
f.reps[0].ReportJSON = certReport(cert("*.example.hu", f.now.Add(89*day))) // renewed
f.step(2 * time.Hour)
f.step(11 * day)
if len(f.events) != 1 {
t.Fatalf("after the renewal: %v", f.events[1:])
}
f.step(70 * day) // the NEW certificate is now 8 days from its end
if len(f.events) != 2 {
t.Fatalf("the new certificate's own warning: %d event(s)", len(f.events))
}
}
// The list is the box's. A name that is not a host name and a date that is not a date are dropped, more than eight
// entries are cut, and a token whose name is not plain text is named by its number.
func TestEndDates_TheBoxesWordsAreChecked(t *testing.T) {
f := newEndDateFix()
soon := f.now.Add(5 * 24 * time.Hour)
var many []string
for i := 0; i < 20; i++ {
many = append(many, cert(fmt.Sprintf("n%02d.example.hu", i), soon.Add(time.Duration(i)*time.Minute)))
}
f.reps = []BoxCertReport{
{CustomerID: "evil", ReportJSON: certReport(cert(``, soon), cert("a b.example.hu", soon),
`{"domain":"ok.example.hu","not_after":"tomorrow"}`, cert("fine.example.hu", soon))},
{CustomerID: "many", ReportJSON: certReport(many...)},
{CustomerID: "evil", ReportJSON: certReport(cert("second-report.example.hu", soon))}, // a duplicate row of the same household
}
// an issuer name that is not a plain name is dropped, the certificate is still told
f.reps = append(f.reps, BoxCertReport{CustomerID: "iss", ReportJSON: `{"web_certs":[{"domain":"x.example.hu","not_after":"` + soon.UTC().Format(time.RFC3339) + `","issuer":"CA"}]}`})
f.tokens = []EndingToken{{ID: 9, Name: "x", ExpiresAt: soon}}
f.step(0)
all := strings.Join(f.events, "\n")
if strings.Contains(all, "alert(1)") || strings.Contains(all, "a b.example") || strings.Contains(all, "") || strings.Contains(all, "second-report") {
t.Fatalf("an unchecked word of a box or a token name reached an event:\n%s", all)
}
if n := strings.Count(all, "evil|web_cert_ends_soon"); n != 1 || !strings.Contains(all, "fine.example.hu") {
t.Errorf("household „evil”: %d event(s), want one for fine.example.hu", n)
}
if n := strings.Count(all, "many|web_cert_ends_soon"); n != webCertsReadMax {
t.Errorf("household „many”: %d event(s), want the cap %d", n, webCertsReadMax)
}
if !strings.Contains(all, "iss|web_cert_ends_soon") || strings.Contains(all, "") || !strings.Contains(all, `"issuer":""`) {
t.Errorf("an issuer that is not a plain name must be dropped and the certificate still told:\n%s", all)
}
if !strings.Contains(all, "„token #9”") {
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)
}
}