-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathzz_fuzz_webhook_test.go
More file actions
391 lines (342 loc) · 10.2 KB
/
Copy pathzz_fuzz_webhook_test.go
File metadata and controls
391 lines (342 loc) · 10.2 KB
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
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
// SPDX-License-Identifier: AGPL-3.0-or-later
package webhook_test
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/pilot-protocol/handshake"
"github.com/pilot-protocol/webhook"
)
// ---------------------------------------------------------------------------
// WebhookClient: nil-safety
// ---------------------------------------------------------------------------
func TestWebhookClientNilEmit(t *testing.T) {
t.Parallel()
var wc *webhook.Client
wc.Emit("test_event", nil) // should not panic
}
func TestWebhookClientNilClose(t *testing.T) {
t.Parallel()
var wc *webhook.Client
wc.Close() // should not panic
}
func TestWebhookClientEmptyURL(t *testing.T) {
t.Parallel()
wc := webhook.NewClient("", func() uint32 { return 1 })
if wc != nil {
t.Fatal("expected nil for empty URL")
}
}
// ---------------------------------------------------------------------------
// WebhookClient: lifecycle
// ---------------------------------------------------------------------------
func TestWebhookClientCreateAndClose(t *testing.T) {
t.Parallel()
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(200)
}))
defer ts.Close()
wc := webhook.NewClient(ts.URL, func() uint32 { return 42 })
if wc == nil {
t.Fatal("expected non-nil webhook client")
}
wc.Close()
}
func TestWebhookClientCloseIdempotent(t *testing.T) {
t.Parallel()
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(200)
}))
defer ts.Close()
wc := webhook.NewClient(ts.URL, func() uint32 { return 1 })
wc.Close()
wc.Close() // second close should not panic
}
// ---------------------------------------------------------------------------
// WebhookClient: emit
// ---------------------------------------------------------------------------
func TestWebhookClientEmitReceived(t *testing.T) {
t.Parallel()
var received atomic.Int32
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
body, _ := io.ReadAll(r.Body)
var ev webhook.Event
if err := json.Unmarshal(body, &ev); err != nil {
t.Errorf("bad webhook payload: %v", err)
return
}
if ev.Event != "node_connected" {
t.Errorf("unexpected event: %s", ev.Event)
}
if ev.NodeID != 42 {
t.Errorf("unexpected node_id: %d", ev.NodeID)
}
received.Add(1)
w.WriteHeader(200)
}))
defer ts.Close()
wc := webhook.NewClient(ts.URL, func() uint32 { return 42 })
wc.Emit("node_connected", map[string]string{"peer": "123"})
// Wait for delivery
wc.Close()
if received.Load() != 1 {
t.Fatalf("expected 1 event received, got %d", received.Load())
}
}
func TestWebhookClientEmitAfterClose(t *testing.T) {
t.Parallel()
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(200)
}))
defer ts.Close()
wc := webhook.NewClient(ts.URL, func() uint32 { return 1 })
wc.Close()
wc.Emit("test", nil) // should not panic (no-op after close)
}
func TestWebhookClientEmitMultiple(t *testing.T) {
t.Parallel()
var count atomic.Int32
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
count.Add(1)
w.WriteHeader(200)
}))
defer ts.Close()
wc := webhook.NewClient(ts.URL, func() uint32 { return 1 })
for i := 0; i < 10; i++ {
wc.Emit("event", nil)
}
wc.Close()
if count.Load() != 10 {
t.Fatalf("expected 10 events, got %d", count.Load())
}
}
func TestWebhookClientEmitWithData(t *testing.T) {
t.Parallel()
var received atomic.Value
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
body, _ := io.ReadAll(r.Body)
received.Store(string(body))
w.WriteHeader(200)
}))
defer ts.Close()
wc := webhook.NewClient(ts.URL, func() uint32 { return 1 })
wc.Emit("data_event", map[string]interface{}{"key": "value", "count": 42})
wc.Close()
raw, ok := received.Load().(string)
if !ok || raw == "" {
t.Fatal("expected webhook payload")
}
var ev webhook.Event
if err := json.Unmarshal([]byte(raw), &ev); err != nil {
t.Fatalf("unmarshal: %v", err)
}
if ev.Event != "data_event" {
t.Fatalf("expected data_event, got %s", ev.Event)
}
}
func TestWebhookClientEmitConcurrent(t *testing.T) {
t.Parallel()
var count atomic.Int32
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
count.Add(1)
w.WriteHeader(200)
}))
defer ts.Close()
wc := webhook.NewClient(ts.URL, func() uint32 { return 1 })
var wg sync.WaitGroup
for i := 0; i < 20; i++ {
wg.Add(1)
go func(id int) {
defer wg.Done()
wc.Emit("concurrent", map[string]int{"id": id})
}(i)
}
wg.Wait()
wc.Close()
if count.Load() != 20 {
t.Fatalf("expected 20 events, got %d", count.Load())
}
}
// ---------------------------------------------------------------------------
// WebhookClient: error handling
// ---------------------------------------------------------------------------
func TestWebhookClientServerError(t *testing.T) {
t.Parallel()
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(500)
}))
defer ts.Close()
wc := webhook.NewClient(ts.URL, func() uint32 { return 1 },
webhook.WithRetryBackoff(10*time.Millisecond))
wc.Emit("test", nil) // server error should not crash
wc.Close()
}
func TestWebhookClientBadURL(t *testing.T) {
t.Parallel()
wc := webhook.NewClient("http://127.0.0.1:1", func() uint32 { return 1 },
webhook.WithHTTPTimeout(200*time.Millisecond),
webhook.WithRetryBackoff(10*time.Millisecond))
wc.Emit("test", nil) // connection refused should not crash
wc.Close()
}
// ---------------------------------------------------------------------------
// WebhookEvent: JSON
// ---------------------------------------------------------------------------
func TestWebhookEventJSON(t *testing.T) {
t.Parallel()
ev := webhook.Event{
Event: "node_connected",
NodeID: 42,
Timestamp: time.Now().UTC(),
Data: map[string]string{"peer": "100"},
}
data, err := json.Marshal(ev)
if err != nil {
t.Fatalf("marshal: %v", err)
}
var decoded webhook.Event
if err := json.Unmarshal(data, &decoded); err != nil {
t.Fatalf("unmarshal: %v", err)
}
if decoded.Event != "node_connected" || decoded.NodeID != 42 {
t.Fatal("event JSON round-trip mismatch")
}
}
func TestWebhookEventEmptyData(t *testing.T) {
t.Parallel()
ev := webhook.Event{
Event: "test",
NodeID: 1,
}
data, _ := json.Marshal(ev)
// "data" should be omitted (omitempty)
var m map[string]interface{}
json.Unmarshal(data, &m)
if _, ok := m["data"]; ok {
t.Fatal("data should be omitted when nil")
}
}
// ---------------------------------------------------------------------------
// Handshake types: JSON round-trip
// ---------------------------------------------------------------------------
func TestHandshakeMsgJSON(t *testing.T) {
t.Parallel()
msg := handshake.HandshakeMsg{
Type: handshake.HandshakeRequest,
NodeID: 42,
PublicKey: "base64pubkey==",
Justification: "need compute access",
Signature: "base64sig==",
Reason: "",
Timestamp: time.Now().Unix(),
}
data, err := json.Marshal(msg)
if err != nil {
t.Fatalf("marshal: %v", err)
}
var decoded handshake.HandshakeMsg
if err := json.Unmarshal(data, &decoded); err != nil {
t.Fatalf("unmarshal: %v", err)
}
if decoded.Type != handshake.HandshakeRequest {
t.Fatalf("expected %s, got %s", handshake.HandshakeRequest, decoded.Type)
}
if decoded.NodeID != 42 {
t.Fatal("node_id mismatch")
}
}
func TestHandshakeConstants(t *testing.T) {
t.Parallel()
if handshake.HandshakeRequest != "handshake_request" {
t.Fatal("HandshakeRequest constant wrong")
}
if handshake.HandshakeAccept != "handshake_accept" {
t.Fatal("HandshakeAccept constant wrong")
}
if handshake.HandshakeReject != "handshake_reject" {
t.Fatal("HandshakeReject constant wrong")
}
if handshake.HandshakeRevoke != "handshake_revoke" {
t.Fatal("HandshakeRevoke constant wrong")
}
}
func TestTrustRecordStruct(t *testing.T) {
t.Parallel()
tr := handshake.TrustRecord{
NodeID: 42,
PublicKey: "base64key==",
ApprovedAt: time.Now(),
Mutual: true,
Network: 1,
}
if tr.NodeID != 42 || !tr.Mutual || tr.Network != 1 {
t.Fatal("TrustRecord field mismatch")
}
}
func TestPendingHandshakeStruct(t *testing.T) {
t.Parallel()
ph := handshake.PendingHandshake{
NodeID: 99,
PublicKey: "key==",
Justification: "testing",
ReceivedAt: time.Now(),
}
if ph.NodeID != 99 || ph.Justification != "testing" {
t.Fatal("PendingHandshake field mismatch")
}
}
// ---------------------------------------------------------------------------
// HMAC signature — PILOT-90
// ---------------------------------------------------------------------------
func TestWebhookClientHMACSignatureHeader(t *testing.T) {
t.Parallel()
secret := "test-secret-key"
var sigHeader string
var body []byte
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
sigHeader = r.Header.Get("X-Pilot-Signature-256")
body, _ = io.ReadAll(r.Body)
w.WriteHeader(200)
}))
defer ts.Close()
wc := webhook.NewClient(ts.URL, func() uint32 { return 42 },
webhook.WithSecret(secret))
if wc == nil {
t.Fatal("expected non-nil client with secret")
}
wc.Emit("test.event", map[string]string{"key": "val"})
wc.Close()
if sigHeader == "" {
t.Fatal("X-Pilot-Signature-256 header not set when secret is configured")
}
// Verify the HMAC ourselves
mac := hmac.New(sha256.New, []byte(secret))
mac.Write(body)
expected := hex.EncodeToString(mac.Sum(nil))
if sigHeader != expected {
t.Fatalf("HMAC mismatch: got %s, want %s", sigHeader, expected)
}
}
func TestWebhookClientNoSignatureWhenNoSecret(t *testing.T) {
t.Parallel()
var sigHeader string
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
sigHeader = r.Header.Get("X-Pilot-Signature-256")
w.WriteHeader(200)
}))
defer ts.Close()
wc := webhook.NewClient(ts.URL, func() uint32 { return 42 })
wc.Emit("test.event", nil)
wc.Close()
if sigHeader != "" {
t.Fatal("X-Pilot-Signature-256 should NOT be set when no secret configured")
}
}