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
68 changes: 53 additions & 15 deletions cmd/server/db.go
Original file line number Diff line number Diff line change
Expand Up @@ -863,6 +863,7 @@ func (db *DB) QueryGroupedPackets(q PacketQuery) (*PacketResult, error) {
if q.Limit <= 0 {
q.Limit = 50
}
hops := hiddenKeysPredicate(q.HiddenSenders) // #1023 M2

where, args := db.buildTransmissionWhere(q)
w := ""
Expand Down Expand Up @@ -976,9 +977,10 @@ func (db *DB) QueryGroupedPackets(q PacketQuery) (*PacketResult, error) {
}
// #165 — the displayed observation's resolved_path, as the in-memory
// store sends it (groupedPageWithRP).
// #1023 M2: a hidden identity's hop is served as null.
if resolvedPath.Valid {
if rp := resolvedPathRaw(resolvedPath.String); rp != nil {
row["resolved_path"] = rp
row["resolved_path"] = hops.redactRaw(rp)
}
}
packets = append(packets, row)
Expand Down Expand Up @@ -2983,6 +2985,15 @@ func buildPacketPathResponseFromReduction(
// deliberately no always-estimating exported wrapper: a caller that did
// not state a policy would bypass the operator's #315 setting.
func (db *DB) getPacketPath(hash string, maxEdgeKm float64, estimatesEnabled bool) (*PacketPathResponse, error) {
return db.getVisiblePacketPath(hash, maxEdgeKm, estimatesEnabled, nil)
}

// getVisiblePacketPath is getPacketPath for /api/packets/{hash}/path (#1023
// M2): a hidden identity's hop is left out like a hop that did not resolve
// (the branch keeps its hop count), an observation heard by a hidden
// identity is left out whole, and a visible hop's estimated position is
// not taken from a hidden neighbour. A nil hidden keeps everything.
func (db *DB) getVisiblePacketPath(hash string, maxEdgeKm float64, estimatesEnabled bool, hidden *hiddenPredicate) (*PacketPathResponse, error) {
if !db.hasResolvedPath() {
return nil, fmt.Errorf("resolved_path not available on this server")
}
Expand Down Expand Up @@ -3022,6 +3033,13 @@ func (db *DB) getPacketPath(hash string, maxEdgeKm float64, estimatesEnabled boo
if !ok {
continue
}
// A hidden identity that is also an observer is left out whole,
// as filterPingScorePath drops its branch: its key and exact
// position must not be served as the observer.
if hidden.hidesIdentity(branch.observerPubkey, branch.observerName) {
continue
}
branch.resolvedPath = hidden.redactPath(branch.resolvedPath)
red.fold(key, branch, ts.Valid, ts.Int64)
}
if err := rows.Err(); err != nil {
Expand All @@ -3031,6 +3049,7 @@ func (db *DB) getPacketPath(hash string, maxEdgeKm float64, estimatesEnabled boo
if len(red.best) == 0 {
return &PacketPathResponse{Hash: hash, Branches: []PacketPathBranch{}, TxID: red.txID}, nil
}
hiddenNeighbour := hidden.hidesNeighbour()

pubkeySet := collectPacketPathPubkeys(red.first, red.best)
pubkeys := make([]string, 0, len(pubkeySet))
Expand All @@ -3054,7 +3073,7 @@ func (db *DB) getPacketPath(hash string, maxEdgeKm float64, estimatesEnabled boo
if !estimatesEnabled {
return neighborEstimate{}, false
}
_, nLat, nLon, nCount, nSpread, ok := db.nearestPositionedNeighbor(pk, maxEdgeKm)
_, nLat, nLon, nCount, nSpread, ok := db.nearestVisiblePositionedNeighbor(pk, maxEdgeKm, hiddenNeighbour)
if !ok {
return neighborEstimate{}, false
}
Expand Down Expand Up @@ -3619,17 +3638,26 @@ func pingBotReply(hops int, snr sql.NullFloat64, observer string, repeaterNames
}

func (db *DB) GetChannelMessages(channelHash string, limit, offset int, region ...string) ([]map[string]interface{}, int, error) {
r := ""
if len(region) > 0 {
r = region[0]
}
return db.getVisibleChannelMessages(channelHash, limit, offset, r, nil)
}

// getVisibleChannelMessages is GetChannelMessages for
// /api/channels/{hash}/messages (#1023 M2): the ping-bot reply does not
// name a hidden relay. Its hop is shown by its raw path prefix, as the
// Packets page shows a hop that did not resolve, and its key is not
// looked up. A nil hidden names every relay.
func (db *DB) getVisibleChannelMessages(channelHash string, limit, offset int, regionParam string, hidden *hiddenPredicate) ([]jsonObject, int, error) {
if limit <= 0 {
limit = 100
}
if offset < 0 {
offset = 0
}

regionParam := ""
if len(region) > 0 {
regionParam = region[0]
}
regionCodes := normalizeRegionCodes(regionParam)
regionArgs := make([]interface{}, 0, len(regionCodes))
regionPlaceholders := ""
Expand Down Expand Up @@ -3790,6 +3818,7 @@ func (db *DB) GetChannelMessages(channelHash string, limit, offset int, region .
hops int
snr sql.NullFloat64
resolvedPath []*string
pathHops []string // the raw path prefixes, for a hidden relay (#1023 M2)
observers map[string]bool
// observerPubkeys/firstPubkey/firstTS feed the "spread up to Nkm"
// reply text -- the same farthest-from-first-hearer distance View
Expand Down Expand Up @@ -3828,12 +3857,12 @@ func (db *DB) GetChannelMessages(channelHash string, limit, offset int, region .
// reach can be tracked across every station that heard it.
var hops int
var entryPrefix string
var pathHops []string
if pathJSON.Valid {
var h []string
if json.Unmarshal([]byte(pathJSON.String), &h) == nil {
hops = len(h)
if len(h) > 0 {
entryPrefix = h[0]
if json.Unmarshal([]byte(pathJSON.String), &pathHops) == nil {
hops = len(pathHops)
if len(pathHops) > 0 {
entryPrefix = pathHops[0]
}
}
}
Expand Down Expand Up @@ -3869,7 +3898,7 @@ func (db *DB) GetChannelMessages(channelHash string, limit, offset int, region .
}
}
if hops > agg.hops {
agg.hops, agg.snr, agg.resolvedPath = hops, snr, resolvedPath
agg.hops, agg.snr, agg.resolvedPath, agg.pathHops = hops, snr, resolvedPath, pathHops
}
}
continue
Expand Down Expand Up @@ -3937,7 +3966,7 @@ func (db *DB) GetChannelMessages(channelHash string, limit, offset int, region .
}
if isPingTrigger(displayText) {
agg := &pendingPing{
hops: hops, snr: snr, resolvedPath: resolvedPath,
hops: hops, snr: snr, resolvedPath: resolvedPath, pathHops: pathHops,
observers: map[string]bool{}, observerPubkeys: map[string]bool{},
}
if observerName != "" {
Expand Down Expand Up @@ -3965,7 +3994,7 @@ func (db *DB) GetChannelMessages(channelHash string, limit, offset int, region .
pubkeySet := map[string]bool{}
for _, p := range pendingPings {
for _, pk := range p.resolvedPath {
if pk != nil && *pk != "" {
if pk != nil && *pk != "" && !hidden.hidesKey(*pk) {
pubkeySet[*pk] = true
}
}
Expand Down Expand Up @@ -4025,10 +4054,19 @@ func (db *DB) GetChannelMessages(channelHash string, limit, offset int, region .

for txID, p := range pendingPings {
var repeaterNames []string
for _, pk := range p.resolvedPath {
for i, pk := range p.resolvedPath {
if pk == nil || *pk == "" {
continue
}
if hidden.hidesKey(*pk) {
// #1023 M2: the raw prefix, never the name or key.
prefix := "?"
if i < len(p.pathHops) && p.pathHops[i] != "" {
prefix = p.pathHops[i]
}
repeaterNames = append(repeaterNames, prefix)
continue
}
if name := names[*pk]; name != "" {
repeaterNames = append(repeaterNames, name)
} else {
Expand Down
173 changes: 173 additions & 0 deletions cmd/server/hidden_hops.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,173 @@
package main

import (
"encoding/json"
"math"
"net/http"
"slices"
"strings"
)

// Hidden identities as hops (#1023 M2).
//
// M1 leaves a hidden identity's own ADVERT and ANON_REQ packets out. The
// packets it relayed or sent stay served, but its full key must not appear
// in them: a resolved_path entry that names a hidden identity is served as
// null, exactly like a hop that did not resolve, and the packet-path and
// resolve-hops endpoints neither name, key nor position it. The rule and
// the set are M1's (hiddenPredicate over the hiddenPK snapshot, plus the
// live config's blacklists), so hiding still follows the identity's
// current state: renamed back, its hops are served again. The cost is one
// map lookup per hop of a served packet, nothing when no key is hidden,
// and a copy only of a path that has a hidden hop (resolved paths are
// shared with the LRU and must never be written).

// hidesKey reports whether the full key of a hop, a path point or a
// resolve candidate belongs to a hidden identity: in hiddenPK or hidden by
// the live config (both blacklists). Any case.
func (p *hiddenPredicate) hidesKey(key string) bool {
if p == nil || key == "" {
return false
}
// Stored keys are lower-case (the ingestor normalises them), so the
// common lookup needs no strings.ToLower, which was 30 % of the cost.
if _, ok := p.snap.pk[key]; ok {
return true
}
if hasUpperASCII(key) {
if _, ok := p.snap.pk[strings.ToLower(key)]; ok {
return true
}
}
return identityHidden(p.cfg, key)
}

// redactPath returns rp with every hidden hop set to nil. It returns rp
// itself when no hop is hidden, a new slice otherwise: rp may be shared.
func (p *hiddenPredicate) redactPath(rp []*string) []*string {
if p == nil {
return rp
}
for i, h := range rp {
if h != nil && p.hidesKey(*h) {
out := slices.Clone(rp)
for j := i; j < len(out); j++ {
if out[j] != nil && p.hidesKey(*out[j]) {
out[j] = nil
}
}
return out
}
}
return rp
}

// redactRaw is redactPath for a stored resolved_path served as raw JSON
// (the grouped list and its SQL fallback): rm itself unless a hop is
// hidden, else the redacted list.
func (p *hiddenPredicate) redactRaw(rm json.RawMessage) interface{} {
if p == nil {
return rm
}
rp := unmarshalResolvedPath(string(rm))
if out := p.redactPath(rp); len(out) > 0 && &out[0] != &rp[0] {
return out
}
return rm
}

// redactBroadcast redacts a WebSocket message's resolved_path, top-level
// and in its nested packet. It reads the store's existing message shape
// (the poller builds each message fresh) through the jsonObject alias and
// adds no new untyped structure.
func (p *hiddenPredicate) redactBroadcast(m jsonObject) {
if p == nil {
return
}
if rp, ok := m["resolved_path"].([]*string); ok {
m["resolved_path"] = p.redactPath(rp)
}
if pkt, ok := m["packet"].(jsonObject); ok {
if rp, ok := pkt["resolved_path"].([]*string); ok {
pkt["resolved_path"] = p.redactPath(rp)
}
}
}

// hidesIdentity reports whether a key or a name (a neighbour, an observer,
// a node filter) is a hidden identity: hidesKey, or a hidden-name prefix.
func (p *hiddenPredicate) hidesIdentity(pubkey, name string) bool {
return p != nil && (p.hidesKey(pubkey) || (p.cfg != nil && p.cfg.IsNameHidden(name)))
}

// hidesNeighbour is the hidden test nearestVisiblePositionedNeighbor
// takes; nil when nothing is hidden.
func (p *hiddenPredicate) hidesNeighbour() func(pubkey, name string) bool {
if p == nil {
return nil
}
return p.hidesIdentity
}

// hiddenHopPredicate is the store's predicate for hops: M1's row predicate,
// or nil when no key can be hidden (an empty hiddenPK and no blacklist),
// so serving a path then costs one pointer test.
func (s *PacketStore) hiddenHopPredicate() *hiddenPredicate {
p := s.hiddenRowPredicate()
if p == nil || len(p.snap.pk) > 0 || (p.cfg != nil && (p.cfg.HasNodeBlacklist() || len(p.cfg.obsBlacklistSet()) > 0)) {
return p
}
return nil
}

// hiddenHops is the hop predicate of a request: the store's, or without a
// store the DB and config rule read now (an error fails the request).
func (s *Server) hiddenHops() (*hiddenPredicate, error) {
if s.store != nil {
return s.store.hiddenHopPredicate(), nil
}
return dbHiddenPredicate(s.db, s.cfg)
}

// hiddenKeysPredicate is the hop predicate of the SQL fallbacks, built
// from the keys the caller resolved (PacketQuery.HiddenSenders); nil when
// there are none.
func hiddenKeysPredicate(keys []string) *hiddenPredicate {
if len(keys) == 0 {
return nil
}
pk := make(map[string]struct{}, len(keys))
for _, k := range keys {
pk[strings.ToLower(k)] = struct{}{}
}
return &hiddenPredicate{snap: &hiddenIdentitySnapshot{pk: pk}, from: math.MinInt}
}

// visibleNodeFilters drops the packet-list node filters (a key or a name,
// as resolveNodePubkey reads them) that name a hidden identity: listing a
// hidden node's packets would re-link the hops M2 serves as null, as M1's
// node detail answers 404 (#1023). Nothing hidden costs nothing; else one
// indexed nodes lookup per filter. ok is false when the error is written.
func (s *Server) visibleNodeFilters(w http.ResponseWriter, filters []string) (visible []string, ok bool) {
hops, err := s.hiddenHops()
if err != nil {
writeError(w, 500, err.Error())
return nil, false
}
if hops == nil {
return filters, true
}
visible = filters[:0:0]
for _, f := range filters {
if hops.hidesIdentity(f, f) {
continue
}
if s.db != nil {
if pk := s.db.resolveNodePubkey(f); pk != f && hops.hidesKey(pk) {
continue
}
}
visible = append(visible, f)
}
return visible, true
}
Loading