Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix subscription flow for Event ID integrity #119

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
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 relay.go
Original file line number Diff line number Diff line change
Expand Up @@ -223,6 +223,7 @@ func (r *Relay) Connect(ctx context.Context) error {
// InfoLogger.Printf("{%s} no subscription with id '%s'\n", r.URL, *env.SubscriptionID)
continue
} else {

// check if the event matches the desired filter, ignore otherwise
if !subscription.Filters.Match(&env.Event) {
InfoLogger.Printf("{%s} filter does not match: %v ~ %v\n", r.URL, subscription.Filters, env.Event)
Expand All @@ -231,6 +232,12 @@ func (r *Relay) Connect(ctx context.Context) error {

// check signature, ignore invalid, except from trusted (AssumeValid) relays
if !r.AssumeValid {

if env.Event.GetID() != env.Event.ID {
InfoLogger.Printf("bad event ID %s != %s\n", env.Event.ID, env.Event.GetID())
continue
}

if ok, err := env.Event.CheckSignature(); !ok {
errmsg := ""
if err != nil {
Expand Down
144 changes: 138 additions & 6 deletions relay_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/http/httptest"
Expand Down Expand Up @@ -171,6 +172,137 @@ func TestConnectWithOrigin(t *testing.T) {
}
}

func TestEventIDIntegrity(t *testing.T) {

priv, pub := makeKeyPair(t)

makeEvent := func(timestamp int) Event {
textNote := Event{
Kind: KindTextNote,
Content: "hello",
CreatedAt: Timestamp(timestamp),
Tags: Tags{[]string{"foo", "bar"}},
PubKey: pub,
}
if err := textNote.Sign(priv); err != nil {
t.Fatalf("textNote.Sign: %v", err)
}

return textNote
}

tests := []struct {
name string
event Event
shouldFail bool
modifyEvent func(event *Event)
}{
{
name: "Original event ID",
event: makeEvent(1672068534),
shouldFail: false,
modifyEvent: nil, // No modification needed for the original event
},
{
name: "Altered event ID",
event: makeEvent(1672068535),
shouldFail: true,
modifyEvent: func(event *Event) { event.ID = "fake_id" }, // Alter the ID to simulate failure
},
}

for _, tc := range tests {

t.Run(tc.name, func(t *testing.T) {

if tc.modifyEvent != nil {
tc.modifyEvent(&tc.event)
}

ctx, cancel := context.WithCancel(context.Background())
wg := sync.WaitGroup{}
wg.Add(1)

// fake relay server
ws := newWebsocketServer(func(conn *websocket.Conn) {

var raw []json.RawMessage
// handling publich event
if err := websocket.JSON.Receive(conn, &raw); err != nil {
t.Errorf("websocket.JSON.Receive: %v", err)
}

// send back an ok nip-20 command result
res := []any{"OK", tc.event.ID, true, ""}
if err := websocket.JSON.Send(conn, res); err != nil {
t.Errorf("websocket.JSON.Send: %v", err)
}

// handling subscription event
if err := websocket.JSON.Receive(conn, &raw); err != nil {
t.Errorf("websocket.JSON.Receive: %v", err)
}

subID, _, err := parseSubscriptionMessage(t, raw)
if err == nil {
res := EventEnvelope{
SubscriptionID: &subID,
Event: tc.event,
}
// senc back the EVENT packet
if err := websocket.JSON.Send(conn, res); err != nil {
t.Errorf("websocket.JSON.Send: %v", err)
}
}

wg.Wait()
})

rl := mustRelayConnect(ws.URL)

go func() {

defer cancel()

sub, err := rl.Subscribe(context.Background(), Filters{{Kinds: []int{KindTextNote}, Limit: 1}})

if err != nil {
t.Logf("subscription.err = %v", err)
return
}

select {
case event := <-sub.Events:
if tc.shouldFail && event != nil {
t.Errorf("Unexpected event received: ID=%v", event.ID)
}
if !tc.shouldFail && event == nil {
t.Error("Expected event not received")
}
case <-time.After(time.Second * 2):
if !tc.shouldFail {
t.Error("Event timeout")
}
}

wg.Done()

}()

// connect a client and send the text note
err := rl.Publish(context.Background(), tc.event)
if err != nil {
t.Errorf("publish should have succeeded. err=%v", err)
}

<-ctx.Done()
ws.Close()
})

}

}

func discardingHandler(conn *websocket.Conn) {
io.ReadAll(conn) // discard all input
}
Expand Down Expand Up @@ -224,27 +356,27 @@ func parseEventMessage(t *testing.T, raw []json.RawMessage) Event {
return event
}

func parseSubscriptionMessage(t *testing.T, raw []json.RawMessage) (subid string, filters []Filter) {
func parseSubscriptionMessage(t *testing.T, raw []json.RawMessage) (string, []Filter, error) {
t.Helper()
if len(raw) < 3 {
t.Fatalf("len(raw) = %d; want at least 3", len(raw))
return "", nil, fmt.Errorf("len(raw) = %d; want at least 3", len(raw))
}
var typ string
json.Unmarshal(raw[0], &typ)
if typ != "REQ" {
t.Errorf("typ = %q; want REQ", typ)
return "", nil, fmt.Errorf("typ = %q; want REQ", typ)
}
var id string
if err := json.Unmarshal(raw[1], &id); err != nil {
t.Errorf("json.Unmarshal sub id: %v", err)
return "", nil, fmt.Errorf("json.Unmarshal sub id: %v", err)
}
var ff []Filter
for i, b := range raw[2:] {
var f Filter
if err := json.Unmarshal(b, &f); err != nil {
t.Errorf("json.Unmarshal filter %d: %v", i, err)
return "", nil, fmt.Errorf("json.Unmarshal filter %d: %v", i, err)
}
ff = append(ff, f)
}
return id, ff
return id, ff, nil
}