83 lines
2.4 KiB
Go
83 lines
2.4 KiB
Go
package main
|
|
|
|
import (
|
|
"encoding/json"
|
|
"errors"
|
|
"os"
|
|
"path/filepath"
|
|
"testing"
|
|
"time"
|
|
)
|
|
|
|
func TestSMTPDenyActiveStateValidity(t *testing.T) {
|
|
now := time.Date(2026, 7, 29, 0, 0, 0, 0, time.UTC)
|
|
state := smtpDenyActiveState{
|
|
ActivatedAt: now,
|
|
Source: "current",
|
|
BundleGeneratedAt: now.Add(-time.Hour),
|
|
BundleExpiresAt: now.Add(23 * time.Hour),
|
|
LastRemoteCurrentAt: now,
|
|
}
|
|
if !state.validAt(now, 24*time.Hour) {
|
|
t.Fatal("valid current state was rejected")
|
|
}
|
|
for name, mutate := range map[string]func(*smtpDenyActiveState){
|
|
"expired": func(value *smtpDenyActiveState) {
|
|
value.BundleExpiresAt = now
|
|
},
|
|
"fail open": func(value *smtpDenyActiveState) {
|
|
value.Source = "fail-open"
|
|
},
|
|
"transition": func(value *smtpDenyActiveState) {
|
|
value.Source = "transition"
|
|
},
|
|
"future activation": func(value *smtpDenyActiveState) {
|
|
value.ActivatedAt = now.Add(6 * time.Minute)
|
|
},
|
|
"excess lifetime": func(value *smtpDenyActiveState) {
|
|
value.BundleExpiresAt = value.BundleGeneratedAt.Add(24*time.Hour + time.Second)
|
|
},
|
|
} {
|
|
t.Run(name, func(t *testing.T) {
|
|
candidate := state
|
|
mutate(&candidate)
|
|
if candidate.validAt(now, 24*time.Hour) {
|
|
t.Fatal("invalid active state was accepted")
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestCompleteSMTPDenyRefreshRecordsActiveSource(t *testing.T) {
|
|
directory := t.TempDir()
|
|
now := time.Date(2026, 7, 29, 0, 0, 0, 0, time.UTC)
|
|
active := smtpDenyActiveState{ActivatedAt: now, Source: "cache"}
|
|
contents, err := json.Marshal(active)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if err := os.WriteFile(filepath.Join(directory, smtpDenyActiveStateFile), contents, 0600); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
operationErr := errors.New("current download failed")
|
|
if err := completeSMTPDenyRefreshAt(directory, now, operationErr); !errors.Is(err, operationErr) {
|
|
t.Fatalf("unexpected completion error %v", err)
|
|
}
|
|
state, err := readSMTPDenyRefreshState(directory)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if state.Successful || state.ActiveSource != "cache" || !state.CompletedAt.Equal(now) {
|
|
t.Fatalf("unexpected refresh state %#v", state)
|
|
}
|
|
}
|
|
|
|
func TestReadStrictJSONRejectsUnknownFields(t *testing.T) {
|
|
path := filepath.Join(t.TempDir(), smtpDenyActiveStateFile)
|
|
if err := os.WriteFile(path, []byte(`{"source":"current","unexpected":true}`), 0600); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if _, err := readSMTPDenyActiveState(filepath.Dir(path)); err == nil {
|
|
t.Fatal("unknown active-state field was accepted")
|
|
}
|
|
}
|