Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ COPY internal/copdem/ ../../internal/copdem/
COPY internal/heritage/ ../../internal/heritage/
COPY internal/buildings/ ../../internal/buildings/
COPY internal/skraafoto/ ../../internal/skraafoto/
COPY internal/scopeguide/ ../../internal/scopeguide/
RUN go mod download
COPY cmd/server/ ./
RUN CGO_ENABLED=0 GOOS=${TARGETOS} GOARCH=${TARGETARCH} \
Expand Down
41 changes: 41 additions & 0 deletions cmd/ingestor/main_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1238,3 +1238,44 @@ func TestHandleMessageAdvert_MatchedScopeUpdatesDefaultScope(t *testing.T) {
t.Errorf("default_scope after matched-scope advert = %q (valid=%v), want #de", got.String, got.Valid)
}
}

// TestHandleMessageAdvert_UndecodableScopeRowShape pins the row shape the
// server's node scope check (#1035 M2, cmd/server/node_scope_check.go,
// nodeFloodAdvertSQL) reads for "the scope cannot be decoded here": a real
// transport-flood ADVERT whose Code1 matches no configured region is stored
// as route_type 0, payload_type 4, from_pubkey = the advertiser and
// scope_name '' (scopeNameForDB), while nodes.default_scope of a node
// without an earlier named scope stays NULL (#1534 guard). The ingestor
// never writes '' to nodes.default_scope, so the server must take this
// state from transmissions (review F1 on #1106). The E2E seed
// test-fixtures/seed-1035-scope-check-nodes.sql writes rows of this shape.
func TestHandleMessageAdvert_UndecodableScopeRowShape(t *testing.T) {
store := newTestStore(t)
const rawHex = "10AABB00000046D62DE27D4C5194D7821FC5A34A45565DCC2537B300B9AB6275255CEFB65D840CE5C169C94C9AED39E8BCB6CB6EB0335497A198B33A1A610CD3B03D8DCFC160900E5244280323EE0B44CACAB8F02B5B38B91CFA18BD067B0B5E63E94CFC85F758A8530B9240933402E0E6B8F84D5252322D52"
const pubkey = "46d62de27d4c5194d7821fc5a34a45565dcc2537b300b9ab6275255cefb65d84"
if _, err := store.db.Exec(`INSERT INTO nodes (public_key, name) VALUES (?, 'Node1')`, pubkey); err != nil {
t.Fatalf("seed node: %v", err)
}
handleMessage(store, "test", MQTTSource{Name: "test"}, &mockMessage{
topic: "meshcore/SJC/obs1/packets",
payload: []byte(`{"raw":"` + rawHex + `"}`),
}, nil, map[string][]byte{"#de": []byte("0123456789abcdef")}, &Config{})

var route, ptype int
var from, scope sql.NullString
if err := store.db.QueryRow(`SELECT route_type, payload_type, from_pubkey, scope_name FROM transmissions
WHERE from_pubkey = ? ORDER BY id DESC LIMIT 1`, pubkey).Scan(&route, &ptype, &from, &scope); err != nil {
t.Fatalf("read advert: %v", err)
}
if route != 0 || ptype != 4 || from.String != pubkey || !scope.Valid || scope.String != "" {
t.Errorf("undecodable flood advert stored as route=%d payload=%d from=%q scope=%q (valid=%v); want 0, 4, %s, '' (not NULL)",
route, ptype, from.String, scope.String, scope.Valid, pubkey)
}
var def sql.NullString
if err := store.db.QueryRow(`SELECT default_scope FROM nodes WHERE public_key = ?`, pubkey).Scan(&def); err != nil {
t.Fatalf("read default_scope: %v", err)
}
if def.Valid {
t.Errorf("nodes.default_scope = %q after an undecodable advert; want NULL", def.String)
}
}
6 changes: 6 additions & 0 deletions cmd/server/go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -131,3 +131,9 @@ replace github.com/meshcore-analyzer/skraafoto => ../../internal/skraafoto
require github.com/meshcore-analyzer/configkey v0.0.0

replace github.com/meshcore-analyzer/configkey => ../../internal/configkey

// internal/scopeguide (#1035): meshguide.dk's scope rules (vendored) and
// the neutral verdict, served by GET /api/nodes/{pubkey}/scope-check (M2).
require github.com/meshcore-analyzer/scopeguide v0.0.0

replace github.com/meshcore-analyzer/scopeguide => ../../internal/scopeguide
266 changes: 266 additions & 0 deletions cmd/server/node_scope_check.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,266 @@
package main

import (
"database/sql"
"net/http"
"strings"

"github.com/gorilla/mux"
"github.com/meshcore-analyzer/scopeguide"
)

// #1035 M2: GET /api/nodes/{pubkey}/scope-check — the scopes meshguide.dk
// recommends for where a repeater or room stands, next to what the node
// has: its default scope (see nodeDefaultEvidence) and, when an observer
// reported it, its configured allow-list (nodes.configured_scope).
//
// The recommendation and the comparison are M1's engine
// (internal/scopeguide, Recommend + Compare), unchanged. Everything is
// information, never a warning (owner decision 5 on #1035).
//
// Cost per request: one node row by primary key, the node's newest flood
// advert (one probe of idx_transmissions_from_pubkey), one DAGI point lookup on
// the in-memory index and M1's Recommend + Compare on the embedded table
// (TestScopeCheckComputeBudget). Nothing scales with nodes or packets, so
// there is no cache. Read-only (#1283). Gated by dagi.enabled, like every
// DAGI feature; public, like the node page itself.

// meshguideScopesURL is meshguide.dk's region-scope recommendation page; it
// has no per-location deep link. Config later (#1035 M4).
const meshguideScopesURL = "https://meshguide.dk/#/defaults/region-scopes"

// NotApplicablePosition: a repeater or room without a usable advertised
// position (estimated positions are never used).
const NotApplicablePosition = "position"

// Where the default scope shown comes from (NodeScopeCheckResponse.DefaultSource).
const (
// DefaultSourceConfirmed: the firmware reported its default scope
// (nodes.default_scope_confirmed_at); "*" there is "no default set".
DefaultSourceConfirmed = "confirmed"
// DefaultSourceAdvert: the node's newest flood advert stored here.
DefaultSourceAdvert = "advert"
// DefaultSourceInferred: nodes.default_scope, which the ingestor infers
// from a scoped advert it could name (#1534), when no flood advert of
// the node is stored any more.
DefaultSourceInferred = "inferred"
)

// NodeScopeCheckSource names where the rules come from.
type NodeScopeCheckSource struct {
Name string `json:"name"`
URL string `json:"url"`
Repo string `json:"repo"`
Commit string `json:"commit"`
}

// NodeScopeCheckResponse is the endpoint's answer: M1's Verdict plus the
// times of the node-side evidence.
type NodeScopeCheckResponse struct {
Pubkey string `json:"pubkey"`
scopeguide.Verdict
// DefaultSource is where Default comes from (DefaultSource*); empty
// when nothing is known about the node's default scope.
DefaultSource string `json:"defaultSource,omitempty"`
// DefaultConfirmedAt is set when the firmware itself reported the
// default scope (nodes.default_scope_confirmed_at).
DefaultConfirmedAt string `json:"defaultConfirmedAt,omitempty"`
// DefaultAdvertAt is when the newest flood advert was first heard,
// with DefaultSource "advert".
DefaultAdvertAt string `json:"defaultAdvertAt,omitempty"`
// ListReportedAt is when an observer last reported the allow-list.
ListReportedAt string `json:"listReportedAt,omitempty"`
Source NodeScopeCheckSource `json:"source"`
}

// nodeScopeRow is what the check reads about one node, typed at the
// boundary from its nodes row and its newest flood advert.
type nodeScopeRow struct {
Role string
Lat, Lon float64
HasPosition bool
// DefaultScope is nodes.default_scope. The ingestor only ever writes a
// scope it could name there (shouldUpdateDefaultScope and
// UpdateNodeDefaultScope skip "", #1534), or the firmware's own report
// (DefaultConfirmedAt set, "*" = no default). It never holds the
// "cannot be decoded" state: that lives in transmissions.scope_name.
DefaultScope string
DefaultConfirmedAt string
// Advert is the node's newest flood advert, when one is stored.
Advert nodeFloodAdvert
// ListKnown: nodes.configured_scope is not NULL (an observer report).
ListKnown bool
List string
ListAt string
}

// nodeFloodAdvert is a node's newest flood advert (route TRANSPORT_FLOOD or
// FLOOD, payload ADVERT). Its transmissions.scope_name is the ingestor's
// scopeNameForDB: NULL for an unscoped flood, "" for a transport code this
// instance has no region name for, "#name" for a named one.
type nodeFloodAdvert struct {
Seen bool
Scoped bool // scope_name not NULL
Scope string // scope_name ("" = cannot be decoded here)
At string // first_seen
}

// nodeFloodAdvertSQL reads a node's newest flood advert. The "+" keeps the
// planner on idx_transmissions_from_pubkey (only ADVERTs carry from_pubkey,
// #1143) instead of the payload_type index, which would walk every advert.
// Ordered by ingest id, not first_seen (#1345).
const nodeFloodAdvertSQL = `SELECT scope_name, first_seen FROM transmissions
WHERE from_pubkey = ? AND +payload_type = 4 AND +route_type IN (0, 1)
ORDER BY id DESC LIMIT 1`

// nodeFloodAdvert returns the newest flood advert of pubkey. A DB without
// transmissions.scope_name (#899) cannot tell, so it reads as none seen.
func (db *DB) nodeFloodAdvert(pubkey string) (nodeFloodAdvert, error) {
var a nodeFloodAdvert
if !db.hasScopeName() {
return a, nil
}
var scope, at sql.NullString
err := db.conn.QueryRow(nodeFloodAdvertSQL, pubkey).Scan(&scope, &at)
if err == sql.ErrNoRows {
return a, nil
}
if err != nil {
return a, err
}
a.Seen, a.Scoped, a.Scope, a.At = true, scope.Valid, scope.String, at.String
return a, nil
}

// nodeDefaultEvidence picks the evidence for a node's default scope,
// strongest first (owner decision 9 on #1035, review F1 on #1106):
// 1. the firmware's own report (default_scope_confirmed_at): the ingestor
// never lets inference overwrite it, and neither does this;
// 2. the newest flood advert: unscoped = no default, scoped with a code
// this instance cannot name = "cannot be decoded", else its name;
// 3. nodes.default_scope, inferred from an older named advert;
// 4. nothing known (source "").
func nodeDefaultEvidence(row nodeScopeRow) (node scopeguide.Node, source string) {
switch {
case strings.TrimSpace(row.DefaultConfirmedAt) != "":
node.DefaultScope, source = row.DefaultScope, DefaultSourceConfirmed
case row.Advert.Seen:
source = DefaultSourceAdvert
if row.Advert.Scoped {
node.DefaultScope = row.Advert.Scope
node.DefaultUndecoded = strings.TrimSpace(row.Advert.Scope) == ""
}
case strings.TrimSpace(row.DefaultScope) != "":
node.DefaultScope, source = row.DefaultScope, DefaultSourceInferred
}
return node, source
}

// nodeScopeRow reads one node's row by primary key, typed at the
// boundary. The scope columns are optional (#899, #1865): a DB without them
// reads as "not known". ok is false when there is no such node.
func (db *DB) nodeScopeRow(pubkey string) (row nodeScopeRow, name string, ok bool, err error) {
cols := "name, role, lat, lon"
var nm, role, def, list, listAt, defAt sql.NullString
var lat, lon sql.NullFloat64
args := []interface{}{&nm, &role, &lat, &lon}
if db.hasDefaultScope() {
cols += ", default_scope"
args = append(args, &def)
}
if db.hasConfiguredScope() {
cols += ", configured_scope, configured_scope_at"
args = append(args, &list, &listAt)
}
if db.hasDefaultScopeConfirmedAt() {
cols += ", default_scope_confirmed_at"
args = append(args, &defAt)
}
err = db.conn.QueryRow("SELECT "+cols+" FROM nodes WHERE public_key = ?", pubkey).Scan(args...)
if err == sql.ErrNoRows {
return row, "", false, nil
}
if err != nil {
return row, "", false, err
}
row.Role = role.String
if lat.Valid && lon.Valid && isValidNodePosition(lat.Float64, lon.Float64) {
row.Lat, row.Lon, row.HasPosition = lat.Float64, lon.Float64, true
}
row.DefaultScope = def.String
row.DefaultConfirmedAt = defAt.String
row.List, row.ListKnown = list.String, list.Valid
row.ListAt = listAt.String
return row, nm.String, true, nil
}

// buildNodeScopeCheck is the pure part of the endpoint.
func buildNodeScopeCheck(g *scopeguide.Guide, idx *dagiIndex, pubkey string, row nodeScopeRow) NodeScopeCheckResponse {
var rec scopeguide.Recommendation
if row.HasPosition {
if p := idx.Lookup(row.Lat, row.Lon).Postnummer; p != nil {
rec = g.Recommend(row.Lat, row.Lon, p.Code)
}
}
node, source := nodeDefaultEvidence(row)
node.Role, node.Configured, node.ConfiguredReported = row.Role, row.List, row.ListKnown
v := g.Compare(rec, node)
if v.NotApplicable == scopeguide.NotApplicableOutside && !row.HasPosition {
v.NotApplicable = NotApplicablePosition
}
up := g.Upstream()
out := NodeScopeCheckResponse{
Pubkey: pubkey,
Verdict: v,
Source: NodeScopeCheckSource{Name: "meshguide.dk", URL: meshguideScopesURL, Repo: up.Repo, Commit: up.Commit},
}
if v.Applicable {
out.DefaultSource = source
switch source {
case DefaultSourceConfirmed:
out.DefaultConfirmedAt = row.DefaultConfirmedAt
case DefaultSourceAdvert:
out.DefaultAdvertAt = row.Advert.At
}
if v.List.Reported {
out.ListReportedAt = row.ListAt
}
}
return out
}

func (s *Server) handleNodeScopeCheck(w http.ResponseWriter, r *http.Request) {
idx := s.dagiIndex()
if idx == nil {
writeError(w, http.StatusNotFound, "Not found")
return
}
pubkey := strings.ToLower(mux.Vars(r)["pubkey"])
if !isHexPubkey(pubkey) {
writeError(w, http.StatusBadRequest, "invalid pubkey: expected 64 hex chars")
return
}
if s.cfg.IsBlacklisted(pubkey) {
writeError(w, http.StatusNotFound, "Not found")
return
}
g, err := scopeguide.Load()
if err != nil {
writeError(w, http.StatusServiceUnavailable, "scope guide unavailable")
return
}
row, name, found, err := s.db.nodeScopeRow(pubkey)
if err != nil {
writeError(w, http.StatusInternalServerError, "query failed")
return
}
if !found || s.cfg.IsNameHidden(name) {
writeError(w, http.StatusNotFound, "Not found")
return
}
if row.Advert, err = s.db.nodeFloodAdvert(pubkey); err != nil {
writeError(w, http.StatusInternalServerError, "query failed")
return
}
writeJSON(w, buildNodeScopeCheck(g, idx, pubkey, row))
}
Loading
Loading