-
Notifications
You must be signed in to change notification settings - Fork 104
/
relay_test.go
237 lines (194 loc) · 5.76 KB
/
relay_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
package nostr
import (
"bytes"
"context"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"sync"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"golang.org/x/net/websocket"
)
func TestPublish(t *testing.T) {
// test note to be sent over websocket
priv, pub := makeKeyPair(t)
textNote := Event{
Kind: KindTextNote,
Content: "hello",
CreatedAt: Timestamp(1672068534), // random fixed timestamp
Tags: Tags{[]string{"foo", "bar"}},
PubKey: pub,
}
err := textNote.Sign(priv)
assert.NoError(t, err)
// fake relay server
var mu sync.Mutex // guards published to satisfy go test -race
var published bool
ws := newWebsocketServer(func(conn *websocket.Conn) {
mu.Lock()
published = true
mu.Unlock()
// verify the client sent exactly the textNote
var raw []json.RawMessage
err := websocket.JSON.Receive(conn, &raw)
assert.NoError(t, err)
event := parseEventMessage(t, raw)
assert.True(t, bytes.Equal(event.Serialize(), textNote.Serialize()))
// send back an ok nip-20 command result
res := []any{"OK", textNote.ID, true, ""}
err = websocket.JSON.Send(conn, res)
assert.NoError(t, err)
})
defer ws.Close()
// connect a client and send the text note
rl := mustRelayConnect(t, ws.URL)
err = rl.Publish(context.Background(), textNote)
assert.NoError(t, err)
assert.True(t, published, "fake relay server saw no event")
}
func TestPublishBlocked(t *testing.T) {
// test note to be sent over websocket
textNote := Event{Kind: KindTextNote, Content: "hello"}
textNote.ID = textNote.GetID()
// fake relay server
ws := newWebsocketServer(func(conn *websocket.Conn) {
// discard received message; not interested
var raw []json.RawMessage
err := websocket.JSON.Receive(conn, &raw)
assert.NoError(t, err)
// send back a not ok nip-20 command result
res := []any{"OK", textNote.ID, false, "blocked"}
websocket.JSON.Send(conn, res)
})
defer ws.Close()
// connect a client and send a text note
rl := mustRelayConnect(t, ws.URL)
err := rl.Publish(context.Background(), textNote)
assert.Error(t, err)
}
func TestPublishWriteFailed(t *testing.T) {
// test note to be sent over websocket
textNote := Event{Kind: KindTextNote, Content: "hello"}
textNote.ID = textNote.GetID()
// fake relay server
ws := newWebsocketServer(func(conn *websocket.Conn) {
// reject receive - force send error
conn.Close()
})
defer ws.Close()
// connect a client and send a text note
rl := mustRelayConnect(t, ws.URL)
// Force brief period of time so that publish always fails on closed socket.
time.Sleep(1 * time.Millisecond)
err := rl.Publish(context.Background(), textNote)
assert.Error(t, err)
}
func TestConnectContext(t *testing.T) {
// fake relay server
var mu sync.Mutex // guards connected to satisfy go test -race
var connected bool
ws := newWebsocketServer(func(conn *websocket.Conn) {
mu.Lock()
connected = true
mu.Unlock()
io.ReadAll(conn) // discard all input
})
defer ws.Close()
// relay client
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
r, err := RelayConnect(ctx, ws.URL)
assert.NoError(t, err)
defer r.Close()
mu.Lock()
defer mu.Unlock()
assert.True(t, connected, "fake relay server saw no client connect")
}
func TestConnectContextCanceled(t *testing.T) {
// fake relay server
ws := newWebsocketServer(discardingHandler)
defer ws.Close()
// relay client
ctx, cancel := context.WithCancel(context.Background())
cancel() // make ctx expired
_, err := RelayConnect(ctx, ws.URL)
assert.ErrorIs(t, err, context.Canceled)
}
func TestConnectWithOrigin(t *testing.T) {
// fake relay server
// default handler requires origin golang.org/x/net/websocket
ws := httptest.NewServer(websocket.Handler(discardingHandler))
defer ws.Close()
// relay client
r := NewRelay(context.Background(), NormalizeURL(ws.URL))
r.RequestHeader = http.Header{"origin": {"https://example.com"}}
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
err := r.Connect(ctx)
assert.NoError(t, err)
}
func discardingHandler(conn *websocket.Conn) {
io.ReadAll(conn) // discard all input
}
func newWebsocketServer(handler func(*websocket.Conn)) *httptest.Server {
return httptest.NewServer(&websocket.Server{
Handshake: anyOriginHandshake,
Handler: handler,
})
}
// anyOriginHandshake is an alternative to default in golang.org/x/net/websocket
// which checks for origin. nostr client sends no origin and it makes no difference
// for the tests here anyway.
var anyOriginHandshake = func(conf *websocket.Config, r *http.Request) error {
return nil
}
func makeKeyPair(t *testing.T) (priv, pub string) {
t.Helper()
privkey := GeneratePrivateKey()
pubkey, err := GetPublicKey(privkey)
assert.NoError(t, err)
return privkey, pubkey
}
func mustRelayConnect(t *testing.T, url string) *Relay {
t.Helper()
rl, err := RelayConnect(context.Background(), url)
require.NoError(t, err)
return rl
}
func parseEventMessage(t *testing.T, raw []json.RawMessage) Event {
t.Helper()
assert.Condition(t, func() (success bool) {
return len(raw) >= 2
})
var typ string
err := json.Unmarshal(raw[0], &typ)
assert.NoError(t, err)
assert.Equal(t, "EVENT", typ)
var event Event
err = json.Unmarshal(raw[1], &event)
require.NoError(t, err)
return event
}
func parseSubscriptionMessage(t *testing.T, raw []json.RawMessage) (subid string, filters []Filter) {
t.Helper()
assert.Greater(t, len(raw), 3)
var typ string
err := json.Unmarshal(raw[0], &typ)
assert.NoError(t, err)
assert.Equal(t, "REQ", typ)
var id string
err = json.Unmarshal(raw[1], &id)
assert.NoError(t, err)
var ff []Filter
for _, b := range raw[2:] {
var f Filter
err := json.Unmarshal(b, &f)
assert.NoError(t, err)
ff = append(ff, f)
}
return id, ff
}