Skip to content
Merged
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
7 changes: 7 additions & 0 deletions .changeset/wot-graph-votes-and-settings-key.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
'nostream': patch
---

fix(wot): count one vote per follower and stop serving a trust graph built for other settings

Two gaps in the Web of Trust graph could grant a proof-of-work discount to an account that should not have it. A contact list (kind 3) that repeated the same `p` tag counted once per repetition towards `wot.minimumFollowers` when its follow list was read from the database, so one account could satisfy a threshold meant for several. Each follower now counts once. The built graph also stayed in use after `wot.seedPubkey`, `wot.maxDepth` or `wot.minimumFollowers` changed through a settings reload, so the old distances kept granting discounts until another event happened to trigger a rebuild. The graph now remembers the settings it was built for, is rebuilt when they change, and grants nothing while a rebuild for the new settings has not completed or has failed.
37 changes: 33 additions & 4 deletions src/services/wot-graph-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,14 @@ const SEED_PUBKEY_PATTERN = /^[0-9a-f]{64}$/i

const followSetKey = (pubkey: Pubkey): string => `wot:follows:${pubkey}`

// The settings a built graph depends on. A graph built for one key must not
// answer for another: a hot-reloaded seed, depth or follower threshold would
// otherwise keep granting distances computed under the old values.
type WotSettings = NonNullable<Settings['wot']>

const graphKey = (wot: WotSettings | undefined): string =>
JSON.stringify([Boolean(wot?.enabled), wot?.seedPubkey ?? null, wot?.maxDepth ?? 2, wot?.minimumFollowers ?? 1])

const extractFollowedPubkeys = (tags: Tag[]): Pubkey[] =>
tags
.filter((tag) => tag[0] === EventTags.Pubkey && typeof tag[1] === 'string' && tag[1].length > 0)
Expand All @@ -23,6 +31,8 @@ export class WotGraphService implements IWotGraphService {

private ready = false

private builtKey: string | undefined

private building: Promise<void> | undefined

private rebuildQueued = false
Expand Down Expand Up @@ -62,6 +72,12 @@ export class WotGraphService implements IWotGraphService {

await this.ensureBuilt()

// Fail closed: if the settings changed and the rebuild for them did not
// finish (it failed), do not answer from a graph built for other settings.
if (this.builtKey !== graphKey(this.settings().wot)) {
return undefined
}

return this.distances.get(pubkey)
}

Expand Down Expand Up @@ -91,10 +107,17 @@ export class WotGraphService implements IWotGraphService {
}

private async ensureBuilt(): Promise<void> {
if (this.ready) {
return
// scheduleRebuild() hands back a rebuild that may already be in flight for
// the previous settings, so check the key again once it finishes; a
// second pass builds for the current settings. Two passes are enough: a
// third settings change during the second pass is picked up by the next
// call.
for (let attempt = 0; attempt < 2; attempt++) {
if (this.ready && this.builtKey === graphKey(this.settings().wot)) {
return
}
await this.scheduleRebuild()
}
await this.scheduleRebuild()
}

// Ensures at most one rebuild runs at a time. A trigger that lands while a
Expand Down Expand Up @@ -127,15 +150,18 @@ export class WotGraphService implements IWotGraphService {

private async rebuild(): Promise<void> {
const wot = this.settings().wot
const key = graphKey(wot)
if (!wot?.enabled || !wot.seedPubkey) {
this.distances = new Map()
this.builtKey = key
this.ready = true
return
}

if (!SEED_PUBKEY_PATTERN.test(wot.seedPubkey)) {
logger.error('wot.seedPubkey %o is not a 64-character hex pubkey; trust graph will be empty', wot.seedPubkey)
this.distances = new Map()
this.builtKey = key
this.ready = true
return
}
Expand All @@ -156,7 +182,9 @@ export class WotGraphService implements IWotGraphService {

for (const pubkey of frontier) {
const follows = await this.getFollows(pubkey)
for (const followed of follows) {
// One account is one vote: a contact list that repeats a `p` tag must
// not count more than once towards minimumFollowers.
for (const followed of new Set(follows)) {
if (followed === wot.seedPubkey || distances.has(followed)) {
continue
}
Expand All @@ -180,6 +208,7 @@ export class WotGraphService implements IWotGraphService {
}

this.distances = distances
this.builtKey = key
this.ready = true
logger('rebuilt wot graph: %d pubkeys within %d hops of %s', distances.size, maxDepth, wot.seedPubkey)
}
Expand Down
90 changes: 90 additions & 0 deletions test/unit/services/wot-graph-service.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -216,6 +216,96 @@ describe('WotGraphService', () => {
expect(await service().getDistance('x')).to.equal(3)
})

it('counts a follow list that repeats a p tag as one vote', async () => {
settings.wot!.minimumFollowers = 2
followsOf[seedPubkey] = ['a']
followsOf.a = ['x', 'x', 'x'] // one account naming x three times is still one follower

expect(await service().getDistance('x')).to.be.undefined
})

it('counts a repeated p tag once when the follow list comes from the database', async () => {
settings.wot!.minimumFollowers = 2
followsOf[seedPubkey] = ['a']
findByFiltersStub.callsFake(async (filters: any[]) =>
filters[0].authors[0] === 'a'
? [
dbEventWithFollows([
['p', 'x'],
['p', 'x'],
]),
]
: [],
)

expect(await service().getDistance('x')).to.be.undefined
})

it('withholds a distance built for other settings until the graph is rebuilt for the new ones', async () => {
followsOf[seedPubkey] = ['a', 'b']
followsOf.a = ['x']
const wot = service()
expect(await wot.getDistance('x')).to.equal(2) // minimumFollowers 1

settings.wot!.minimumFollowers = 2
expect(await wot.getDistance('x')).to.be.undefined // only one follower of x
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved

followsOf.b = ['x']
await wot.updateFollowList('b', ['x'])
await (wot as any).building
expect(await wot.getDistance('x')).to.equal(2)
})

it('waits for a rebuild under the new settings when a lookup joins one started under the old', async () => {
settings.wot!.maxDepth = 1 // x is two hops away, so the first build leaves it out
followsOf[seedPubkey] = ['a']
followsOf.a = ['x']
const gates: Array<{ promise: Promise<void>; release: () => void }> = [0, 1].map(() => {
let release!: () => void
const promise = new Promise<void>((resolve) => {
release = resolve
})
return { promise, release }
})
let builds = 0
getSetMembersStub.callsFake(async (key: string) => {
if (key === `wot:follows:${seedPubkey}`) {
await gates[builds++]?.promise // each build stops on its first read, the seed's follows
}
return followsOf[key.replace('wot:follows:', '')] ?? []
})
const tick = () => new Promise((resolve) => setImmediate(resolve))

const wot = service()
const first = wot.getDistance('x') // starts a build under maxDepth 1 and pauses in it
await tick()
settings.wot!.maxDepth = 2
let secondSettled = false
const second = wot.getDistance('x').then((distance) => {
secondSettled = true
return distance
}) // joins the build in flight, built for the old settings

gates[0].release()
await tick()
expect(secondSettled).to.equal(false) // it waits for the build under the new settings

gates[1].release()
expect(await second).to.equal(2)
expect(await first).to.equal(2)
})

it('does not answer from a graph built for other settings when the rebuild fails', async () => {
followsOf[seedPubkey] = ['a']
const wot = service()
expect(await wot.getDistance('a')).to.equal(1)

settings.wot!.maxDepth = 3
getSetMembersStub.rejects(new Error('cache unavailable'))

expect(await wot.getDistance('a')).to.be.undefined
})

it('treats an invalid seedPubkey as an empty graph instead of throwing', async () => {
settings.wot!.seedPubkey = 'not-a-valid-hex-pubkey'

Expand Down
Loading