// Copyright 2026 Beacon Contributors // SPDX-License-Identifier: AGPL-3.0-or-later package polling import ( "context" "crypto/ed25519" "crypto/sha256" "encoding/hex" "encoding/json" "sort" "strings" "testing" "time" "github.com/MeshCore-Beacon/beacon-server/internal/config" ) const ( thisHost = "beacon.example.com" ownBroker = "mqtt.example" ) func newCheckSvc(t *testing.T) (*Service, *fakeStore, *clock) { t.Helper() s, st, ck := newSvc(t, true) s.cfg.ForeignCheck, s.cfg.PublicHost = true, thisHost return s, st, ck } // testKey is a repeatable observer key pair. func testKey(seed byte) (ed25519.PublicKey, ed25519.PrivateKey) { sum := sha256.Sum256([]byte{seed}) priv := ed25519.NewKeyFromSeed(sum[:]) return priv.Public().(ed25519.PublicKey), priv } // signedClaim is a claim as current firmware sends it, naming pollURL and signed with the observer's key. func signedClaim(priv ed25519.PrivateKey, pollURL string, at time.Time, targets ...[]byte) []byte { id := hex.EncodeToString(priv.Public().(ed25519.PublicKey)) ts := at.UTC().Format("2006-01-02T15:04:05.000000+00:00") nodes := []map[string]any{} var parts []string for _, tg := range targets { nodes = append(nodes, map[string]any{"node_id": hx(tg), "key": "own", "state": "ok", "misses": 0}) parts = append(parts, hx(tg)+":ok:0:0") } sort.Strings(parts) msg := strings.Join([]string{"corescope-claim/v1", id, pollURL, ts, "false", "false", "0", "8", strings.Join(parts, ",")}, "|") b, _ := json.Marshal(map[string]any{"v": 2, "origin": "obs", "origin_id": id, "timestamp": ts, "plugin": "fw", "community": false, "accepts_requests": false, "request_slots": 0, "max_slots": 8, "poll_url": pollURL, "nodes": nodes, "sig": hex.EncodeToString(ed25519.Sign(priv, []byte(msg)))}) return b } func (f *fakeStore) standingOf(obs []byte) string { f.mu.Lock() defer f.mu.Unlock() _, own := f.claims[hx(obs)] _, foreign := f.foreign[hx(obs)] switch { case own && foreign: return "both" case own: return "own" case foreign: return "foreign" } return "none" } func TestCheckSignedClaimNamesItsServer(t *testing.T) { s, st, ck := newCheckSvc(t) pub, priv := testKey(1) ctx := context.Background() s.HandleClaim(ctx, hx(pub), "", signedClaim(priv, thisHost, ck.now(), k32(9))) if got := st.standingOf(pub); got != "own" { t.Fatalf("a claim naming this server: %s", got) } // A port in poll_url does not change whose it is. ck.t = ck.t.Add(time.Minute) s.HandleClaim(ctx, hx(pub), "", signedClaim(priv, thisHost+":8443", ck.now(), k32(9))) if got := st.standingOf(pub); got != "own" { t.Fatalf("with a port: %s", got) } // The same observer now names another server: it leaves the elections and its old target is elected again. ck.t = ck.t.Add(time.Minute) before := st.electCalls[hx(k32(9))] s.HandleClaim(ctx, hx(pub), ownBroker, signedClaim(priv, "other.example.com", ck.now(), k32(9))) if got := st.standingOf(pub); got != "foreign" { t.Fatalf("a claim naming another server: %s", got) } if st.electCalls[hx(k32(9))] == before { t.Fatal("the target the observer held was not elected again") } if len(st.assigns[hx(k32(9))]) != 0 { t.Fatalf("a foreign observer kept its place: %+v", st.assigns[hx(k32(9))]) } // And back: a claim of this server's own replaces the foreign one. ck.t = ck.t.Add(time.Minute) s.HandleClaim(ctx, hx(pub), "", signedClaim(priv, thisHost, ck.now(), k32(9))) if got := st.standingOf(pub); got != "own" { t.Fatalf("back to this server: %s", got) } } func TestCheckUnsignedClaimGoesByItsBroker(t *testing.T) { s, st, ck := newCheckSvc(t) ctx := context.Background() s.HandleClaim(ctx, hx(k32(1)), ownBroker, claimJSON(k32(1), ck.now(), k32(9))) s.HandleClaim(ctx, hx(k32(2)), "mqtt.elsewhere.example", claimJSON(k32(2), ck.now(), k32(9))) s.HandleClaim(ctx, hx(k32(3)), "", claimJSON(k32(3), ck.now(), k32(9))) for obs, want := range map[byte]string{1: "own", 2: "foreign", 3: "none"} { if got := st.standingOf(k32(obs)); got != want { t.Errorf("observer %d: %s, want %s", obs, got, want) } } } // The same unsigned claim can reach a rebroadcaster by two brokers. Whichever copy arrives first, it is this // server's own if either route was. func TestCheckSameClaimByTwoRoutes(t *testing.T) { for _, ownFirst := range []bool{true, false} { s, st, ck := newCheckSvc(t) ctx := context.Background() raw := claimJSON(k32(1), ck.now(), k32(9)) hosts := []string{ownBroker, "mqtt.elsewhere.example"} if !ownFirst { hosts[0], hosts[1] = hosts[1], hosts[0] } s.HandleClaim(ctx, hx(k32(1)), hosts[0], raw) ck.t = ck.t.Add(ClaimMinInterval) s.HandleClaim(ctx, hx(k32(1)), hosts[1], raw) if got := st.standingOf(k32(1)); got != "own" { t.Errorf("own route first=%v: %s", ownFirst, got) } } } // A signed claim of this server's own that arrives late, after the observer has moved to another server, does not // bring it back. func TestCheckDelayedOlderClaimDoesNotUndoANewerOne(t *testing.T) { s, st, ck := newCheckSvc(t) pub, priv := testKey(1) ctx := context.Background() older := signedClaim(priv, thisHost, ck.now(), k32(9)) newer := signedClaim(priv, "other.example.com", ck.now().Add(2*time.Minute), k32(9)) ck.t = ck.t.Add(3 * time.Minute) s.HandleClaim(ctx, hx(pub), "", newer) ck.t = ck.t.Add(time.Minute) s.HandleClaim(ctx, hx(pub), "", older) if got := st.standingOf(pub); got != "foreign" { t.Fatalf("after the delayed older claim: %s", got) } } // An observer cannot get past the claim spacing by alternating servers. func TestCheckSpacingHoldsAcrossSides(t *testing.T) { s, st, ck := newCheckSvc(t) pub, priv := testKey(1) ctx := context.Background() s.HandleClaim(ctx, hx(pub), "", signedClaim(priv, "other.example.com", ck.now(), k32(9))) ck.t = ck.t.Add(5 * time.Second) s.HandleClaim(ctx, hx(pub), "", signedClaim(priv, thisHost, ck.now(), k32(9))) if got := st.standingOf(pub); got != "foreign" { t.Fatalf("a second claim 5 s later was taken: %s", got) } ck.t = ck.t.Add(ClaimMinInterval) s.HandleClaim(ctx, hx(pub), "", signedClaim(priv, thisHost, ck.now(), k32(9))) if got := st.standingOf(pub); got != "own" { t.Fatalf("after the spacing: %s", got) } } // With authority approved the store is told to trust a claimless reading only from an approved observer; a claim // taken as this server's own records the settings it was placed under. func TestCheckPassesAuthorityAndPolicyToTheStore(t *testing.T) { s, st, ck := newCheckSvc(t) ctx := context.Background() s.HandleReading(ctx, hx(k32(1)), readingJSON(k32(1), k32(9), ck.now())) s.cfg.Authority = config.PollingAuthorityApproved s.HandleReading(ctx, hx(k32(2)), readingJSON(k32(2), k32(9), ck.now())) for _, r := range st.readings { if r.approvedOnly != (r.observer == hx(k32(2))) { t.Errorf("observer %s approvedOnly %v", r.observer[:2], r.approvedOnly) } } s.HandleClaim(ctx, hx(k32(3)), ownBroker, claimJSON(k32(3), ck.now(), k32(9))) if got := st.claims[hx(k32(3))].policy; got == "" || got != s.cfg.ClaimPolicy() { t.Fatalf("claim policy %q, want %q", got, s.cfg.ClaimPolicy()) } } func TestCheckRefusesWhatItCannotPlace(t *testing.T) { s, st, ck := newCheckSvc(t) pub, priv := testKey(1) ctx := context.Background() // A signature older than a claim lives. s.HandleClaim(ctx, hx(pub), ownBroker, signedClaim(priv, thisHost, ck.now().Add(-ClaimTTL-time.Minute), k32(9))) if got := st.standingOf(pub); got != "none" { t.Fatalf("stale signed claim: %s", got) } // Once an observer signs, a claim with the poll_url and signature taken off is not its word. s.HandleClaim(ctx, hx(pub), ownBroker, signedClaim(priv, "other.example.com", ck.now(), k32(9))) ck.t = ck.t.Add(time.Minute) s.HandleClaim(ctx, hx(pub), ownBroker, claimJSON(pub, ck.now(), k32(9))) if got := st.standingOf(pub); got != "foreign" { t.Fatalf("stripped claim turned a foreign observer into %s", got) } } // A wrong signature is refused whatever the setting; with it off a valid one naming another server is still taken // as this server's own, as every claim is. func TestSignatureIsCheckedWithForeignClaimsOff(t *testing.T) { s, st, ck := newSvc(t, true) pub, priv := testKey(1) ctx := context.Background() raw := signedClaim(priv, "other.example.com", ck.now(), k32(9)) var m map[string]any _ = json.Unmarshal(raw, &m) m["community"] = true tampered, _ := json.Marshal(m) s.HandleClaim(ctx, hx(pub), "", tampered) if got := st.standingOf(pub); got != "none" { t.Fatalf("tampered claim: %s", got) } s.HandleClaim(ctx, hx(pub), "", raw) if got := st.standingOf(pub); got != "own" || !st.claims[hx(pub)].signed { t.Fatalf("valid claim with the setting off: %s", got) } } func TestReadingWithoutAClaim(t *testing.T) { ctx := context.Background() foreignReadings := func(st *fakeStore) (n int) { for _, r := range st.readings { if r.foreign { n++ } } return n } // Off: dropped, as before. s, st, ck := newSvc(t, true) s.HandleReading(ctx, hx(k32(1)), readingJSON(k32(1), k32(9), ck.now())) if st.readingCount() != 0 { t.Fatal("a reading without a claim was stored with foreign_claims off") } // Check: kept as foreign. A reading under a claim of this server's own is not. s, st, ck = newCheckSvc(t) s.HandleReading(ctx, hx(k32(1)), readingJSON(k32(1), k32(9), ck.now())) if st.readingCount() != 1 || foreignReadings(st) != 1 { t.Fatalf("readings %d, foreign %d", st.readingCount(), foreignReadings(st)) } s.HandleClaim(ctx, hx(k32(2)), ownBroker, claimJSON(k32(2), ck.now(), k32(9))) s.HandleReading(ctx, hx(k32(2)), readingJSON(k32(2), k32(9), ck.now())) if st.readingCount() != 2 || foreignReadings(st) != 1 { t.Fatalf("after an own reading: readings %d, foreign %d", st.readingCount(), foreignReadings(st)) } // A blocked observer's reading is dropped either way. st.blocked[hx(k32(3))] = true s.HandleReading(ctx, hx(k32(3)), readingJSON(k32(3), k32(9), ck.now())) if st.readingCount() != 2 { t.Fatal("a blocked observer's reading was stored") } } func TestRefusedClaimsAreLoggedSparingly(t *testing.T) { s, _, ck := newCheckSvc(t) logged := func() int { s.dropMu.Lock() defer s.dropMu.Unlock() return len(s.dropped) } ctx := context.Background() for range 5 { s.HandleClaim(ctx, hx(k32(3)), "", claimJSON(k32(3), ck.now(), k32(9))) } first := s.dropped[short(k32(3))] ck.t = ck.t.Add(dropLogEvery) s.HandleClaim(ctx, hx(k32(3)), "", claimJSON(k32(3), ck.now(), k32(9))) if logged() != 1 || !s.dropped[short(k32(3))].After(first) { t.Fatalf("entries %d", logged()) } }