From 1a97d0a2f5f9b51478204346dbd2400e2ae71f51 Mon Sep 17 00:00:00 2001 From: Tanguy Date: Fri, 14 Jan 2022 19:40:30 +0100 Subject: [PATCH] Validate pubsub subscriptions (#627) * Check topic before subscribing * Block subscribe to invalid topics --- libp2p/protocols/pubsub/pubsub.nim | 5 +++++ tests/pubsub/testgossipsub2.nim | 4 +++- 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/libp2p/protocols/pubsub/pubsub.nim b/libp2p/protocols/pubsub/pubsub.nim index 4c119ca97..30a30ed68 100644 --- a/libp2p/protocols/pubsub/pubsub.nim +++ b/libp2p/protocols/pubsub/pubsub.nim @@ -452,6 +452,11 @@ proc subscribe*(p: PubSub, ## on every received message ## + # Check that this is an allowed topic + if p.subscriptionValidator != nil and p.subscriptionValidator(topic) == false: + warn "Trying to subscribe to a topic not passing validation!", topic + return + p.topics.withValue(topic, handlers) do: # Already subscribed, just adding another handler handlers[].add(handler) diff --git a/tests/pubsub/testgossipsub2.nim b/tests/pubsub/testgossipsub2.nim index 62562c340..6e9c8913d 100644 --- a/tests/pubsub/testgossipsub2.nim +++ b/tests/pubsub/testgossipsub2.nim @@ -147,6 +147,9 @@ suite "GossipSub": nodes[1].start(), )) + # We must subscribe before setting the validator + nodes[0].subscribe("foobar", handler) + var gossip = GossipSub(nodes[0]) let invalidDetected = newFuture[void]() gossip.subscriptionValidator = @@ -162,7 +165,6 @@ suite "GossipSub": await subscribeNodes(nodes) - nodes[0].subscribe("foobar", handler) nodes[1].subscribe("foobar", handler) await invalidDetected.wait(10.seconds)