forked from coinbase/x402
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver_hooks_test.go
More file actions
491 lines (401 loc) · 13.2 KB
/
server_hooks_test.go
File metadata and controls
491 lines (401 loc) · 13.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
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
package x402
import (
"context"
"errors"
"testing"
"github.com/x402-foundation/x402/go/types"
)
// Mock facilitator client for testing
type mockFacilitatorClient struct {
verify func(ctx context.Context, payload []byte, reqs []byte) (*VerifyResponse, error)
settle func(ctx context.Context, payload []byte, reqs []byte) (*SettleResponse, error)
kinds []SupportedKind // Configurable supported kinds
}
func (m *mockFacilitatorClient) Verify(ctx context.Context, payloadBytes []byte, requirementsBytes []byte) (*VerifyResponse, error) {
if m.verify != nil {
return m.verify(ctx, payloadBytes, requirementsBytes)
}
return &VerifyResponse{IsValid: true, Payer: "0xmock"}, nil // Default to success
}
func (m *mockFacilitatorClient) Settle(ctx context.Context, payloadBytes []byte, requirementsBytes []byte) (*SettleResponse, error) {
if m.settle != nil {
return m.settle(ctx, payloadBytes, requirementsBytes)
}
return &SettleResponse{Success: true, Transaction: "0xmock", Network: "eip155:1", Payer: "0xmock"}, nil // Default to success
}
func (m *mockFacilitatorClient) GetSupported(ctx context.Context) (SupportedResponse, error) {
if m.kinds != nil {
return SupportedResponse{
Kinds: m.kinds,
Extensions: []string{},
Signers: make(map[string][]string),
}, nil
}
// Default kinds for backward compatibility with server_hooks tests
return SupportedResponse{
Kinds: []SupportedKind{
{X402Version: 2, Scheme: "exact", Network: "eip155:8453"},
},
Extensions: []string{},
Signers: make(map[string][]string),
}, nil
}
// Test BeforeVerify hook - abort verification
func TestBeforeVerifyHook_Abort(t *testing.T) {
server := Newx402ResourceServer()
// Register hook that aborts verification
server.OnBeforeVerify(func(ctx VerifyContext) (*BeforeHookResult, error) {
return &BeforeHookResult{
Abort: true,
Reason: "Security check failed",
}, nil
})
// Try to verify (should be aborted by hook)
payload := types.PaymentPayload{X402Version: 2, Payload: map[string]interface{}{}}
requirements := types.PaymentRequirements{Scheme: "exact", Network: "eip155:8453"}
result, err := server.VerifyPayment(
context.Background(),
payload,
requirements,
)
if err == nil {
t.Error("Expected error when hook aborts")
}
if result != nil {
t.Error("Expected nil result when hook aborts")
}
// Check that it's a VerifyError with the correct reason
ve := &VerifyError{}
if errors.As(err, &ve) {
if ve.InvalidReason != "Security check failed" {
t.Errorf("Expected reason='Security check failed', got '%s'", ve.InvalidReason)
}
} else {
t.Errorf("Expected *VerifyError, got %T", err)
}
}
// Test BeforeVerify hook - continue verification
func TestBeforeVerifyHook_Continue(t *testing.T) {
called := false
server := Newx402ResourceServer()
// Register hook that allows verification to continue
server.OnBeforeVerify(func(ctx VerifyContext) (*BeforeHookResult, error) {
called = true
// Return nil to continue
return nil, nil
})
// Try to verify (will fail due to no facilitators, but hook should be called)
payload := types.PaymentPayload{X402Version: 2, Payload: map[string]interface{}{}}
requirements := types.PaymentRequirements{Scheme: "exact", Network: "eip155:8453"}
_, _ = server.VerifyPayment(
context.Background(),
payload,
requirements,
)
if !called {
t.Error("Expected beforeVerify hook to be called")
}
}
// Test AfterVerify hook
func TestAfterVerifyHook(t *testing.T) {
var capturedResult *VerifyResponse
server := Newx402ResourceServer()
// Register hook to capture result
server.OnAfterVerify(func(ctx VerifyResultContext) error {
capturedResult = ctx.Result
return nil
})
// Mock facilitator that returns success
mockFacilitator := &mockFacilitatorClient{
verify: func(ctx context.Context, payload []byte, reqs []byte) (*VerifyResponse, error) {
return &VerifyResponse{IsValid: true, Payer: "0xpayer"}, nil
},
}
// Setup facilitator in the map
server.facilitatorClients[Network("eip155:8453")] = map[string]FacilitatorClient{
"exact": mockFacilitator,
}
// Verify payment (typed)
payload := types.PaymentPayload{X402Version: 2, Payload: map[string]interface{}{}}
requirements := types.PaymentRequirements{Scheme: "exact", Network: "eip155:8453"}
result, err := server.VerifyPayment(
context.Background(),
payload,
requirements,
)
if err != nil {
t.Errorf("Expected no error, got %v", err)
}
if !result.IsValid {
t.Error("Expected verification to succeed")
}
// Check hook was called with correct result
if !capturedResult.IsValid {
t.Error("Expected afterVerify hook to capture valid result")
}
}
// Test OnVerifyFailure hook - recovery
func TestOnVerifyFailureHook_Recover(t *testing.T) {
server := Newx402ResourceServer()
// Register hook that recovers from failure
server.OnVerifyFailure(func(ctx VerifyFailureContext) (*VerifyFailureHookResult, error) {
return &VerifyFailureHookResult{
Recovered: true,
Result: &VerifyResponse{
IsValid: true,
// Hook recovered the payment
},
}, nil
})
// Mock facilitator that returns error
mockFacilitator := &mockFacilitatorClient{
verify: func(ctx context.Context, payload []byte, reqs []byte) (*VerifyResponse, error) {
return nil, errors.New("facilitator error")
},
}
server.facilitatorClients[Network("eip155:8453")] = map[string]FacilitatorClient{
"exact": mockFacilitator,
}
// Verify payment (should be recovered by hook)
payload := types.PaymentPayload{X402Version: 2, Payload: map[string]interface{}{}}
requirements := types.PaymentRequirements{Scheme: "exact", Network: "eip155:8453"}
result, err := server.VerifyPayment(
context.Background(),
payload,
requirements,
)
if err != nil {
t.Errorf("Expected hook to recover, got error: %v", err)
}
if !result.IsValid {
t.Error("Expected hook to recover verification")
}
}
// Test OnVerifyFailure hook - no recovery
func TestOnVerifyFailureHook_NoRecover(t *testing.T) {
hookCalled := false
server := Newx402ResourceServer()
// Register hook that doesn't recover
server.OnVerifyFailure(func(ctx VerifyFailureContext) (*VerifyFailureHookResult, error) {
hookCalled = true
// Return nil to not recover
return nil, nil
})
// Mock facilitator that returns error
mockFacilitator := &mockFacilitatorClient{
verify: func(ctx context.Context, payload []byte, reqs []byte) (*VerifyResponse, error) {
return nil, errors.New("facilitator error")
},
}
server.facilitatorClients[Network("eip155:8453")] = map[string]FacilitatorClient{
"exact": mockFacilitator,
}
// Verify payment (should fail)
payload := types.PaymentPayload{X402Version: 2, Payload: map[string]interface{}{}}
requirements := types.PaymentRequirements{Scheme: "exact", Network: "eip155:8453"}
_, err := server.VerifyPayment(
context.Background(),
payload,
requirements,
)
if err == nil {
t.Error("Expected error to be returned when hook doesn't recover")
}
if !hookCalled {
t.Error("Expected failure hook to be called")
}
}
// Test BeforeSettle hook - abort settlement
func TestBeforeSettleHook_Abort(t *testing.T) {
server := Newx402ResourceServer()
// Register hook that aborts settlement
server.OnBeforeSettle(func(ctx SettleContext) (*BeforeHookResult, error) {
return &BeforeHookResult{
Abort: true,
Reason: "Insufficient funds",
}, nil
})
// Try to settle (should be aborted by hook)
payload := types.PaymentPayload{X402Version: 2, Payload: map[string]interface{}{}}
requirements := types.PaymentRequirements{Scheme: "exact", Network: "eip155:8453"}
result, err := server.SettlePayment(
context.Background(),
payload,
requirements,
nil,
)
if err == nil {
t.Error("Expected error when settlement is aborted")
}
if result != nil {
t.Error("Expected nil result when settlement is aborted")
}
// Check that it's a SettleError with the correct reason
se := &SettleError{}
if errors.As(err, &se) {
if se.ErrorReason != "Insufficient funds" {
t.Errorf("Expected reason='Insufficient funds', got '%s'", se.ErrorReason)
}
} else {
t.Errorf("Expected *SettleError, got %T", err)
}
}
// Test AfterSettle hook
func TestAfterSettleHook(t *testing.T) {
var capturedTxHash string
server := Newx402ResourceServer()
// Register hook to capture settlement result
server.OnAfterSettle(func(ctx SettleResultContext) error {
capturedTxHash = ctx.Result.Transaction
return nil
})
// Mock facilitator that returns successful settlement
mockFacilitator := &mockFacilitatorClient{
settle: func(ctx context.Context, payload []byte, reqs []byte) (*SettleResponse, error) {
return &SettleResponse{
Success: true,
Transaction: "0xabc123",
Network: "eip155:8453",
Payer: "0xpayer",
}, nil
},
}
server.facilitatorClients[Network("eip155:8453")] = map[string]FacilitatorClient{
"exact": mockFacilitator,
}
// Settle payment
payload := types.PaymentPayload{X402Version: 2, Payload: map[string]interface{}{}}
requirements := types.PaymentRequirements{Scheme: "exact", Network: "eip155:8453"}
result, err := server.SettlePayment(
context.Background(),
payload,
requirements,
nil,
)
if err != nil {
t.Errorf("Expected no error, got %v", err)
}
if !result.Success {
t.Error("Expected settlement to succeed")
}
// Check hook captured the transaction hash
if capturedTxHash != "0xabc123" {
t.Errorf("Expected hook to capture tx hash '0xabc123', got '%s'", capturedTxHash)
}
}
// Test OnSettleFailure hook - recovery
func TestOnSettleFailureHook_Recover(t *testing.T) {
server := Newx402ResourceServer()
// Register hook that recovers from failure
server.OnSettleFailure(func(ctx SettleFailureContext) (*SettleFailureHookResult, error) {
return &SettleFailureHookResult{
Recovered: true,
Result: &SettleResponse{
Success: true,
Transaction: "0xrecovered",
Network: "eip155:8453",
Payer: "0xpayer",
},
}, nil
})
// Mock facilitator that returns error
mockFacilitator := &mockFacilitatorClient{
settle: func(ctx context.Context, payload []byte, reqs []byte) (*SettleResponse, error) {
return nil, errors.New("settlement failed")
},
}
server.facilitatorClients[Network("eip155:8453")] = map[string]FacilitatorClient{
"exact": mockFacilitator,
}
// Settle payment (should be recovered by hook)
payload := types.PaymentPayload{X402Version: 2, Payload: map[string]interface{}{}}
requirements := types.PaymentRequirements{Scheme: "exact", Network: "eip155:8453"}
result, err := server.SettlePayment(
context.Background(),
payload,
requirements,
nil,
)
if err != nil {
t.Errorf("Expected hook to recover, got error: %v", err)
}
if !result.Success {
t.Error("Expected hook to recover settlement")
}
if result.Transaction != "0xrecovered" {
t.Errorf("Expected recovered transaction, got '%s'", result.Transaction)
}
}
// Test multiple hooks execution order
func TestMultipleHooks_ExecutionOrder(t *testing.T) {
executionOrder := []string{}
server := Newx402ResourceServer()
// Register multiple hooks in order
server.OnBeforeVerify(func(ctx VerifyContext) (*BeforeHookResult, error) {
executionOrder = append(executionOrder, "before1")
return nil, nil
})
server.OnBeforeVerify(func(ctx VerifyContext) (*BeforeHookResult, error) {
executionOrder = append(executionOrder, "before2")
return nil, nil
})
server.OnAfterVerify(func(ctx VerifyResultContext) error {
executionOrder = append(executionOrder, "after1")
return nil
})
server.OnAfterVerify(func(ctx VerifyResultContext) error {
executionOrder = append(executionOrder, "after2")
return nil
})
// Mock facilitator
mockFacilitator := &mockFacilitatorClient{
verify: func(ctx context.Context, payload []byte, reqs []byte) (*VerifyResponse, error) {
return &VerifyResponse{IsValid: true, Payer: "0xpayer"}, nil
},
}
server.facilitatorClients[Network("eip155:8453")] = map[string]FacilitatorClient{
"exact": mockFacilitator,
}
// Verify payment
payload := types.PaymentPayload{X402Version: 2, Payload: map[string]interface{}{}}
requirements := types.PaymentRequirements{Scheme: "exact", Network: "eip155:8453"}
_, _ = server.VerifyPayment(
context.Background(),
payload,
requirements,
)
// Check execution order
expected := []string{"before1", "before2", "after1", "after2"}
if len(executionOrder) != len(expected) {
t.Errorf("Expected %d hooks to execute, got %d", len(expected), len(executionOrder))
}
for i, v := range expected {
if i >= len(executionOrder) || executionOrder[i] != v {
t.Errorf("Expected execution order %v, got %v", expected, executionOrder)
break
}
}
}
// Test using functional options to register hooks at construction
func TestHooks_FunctionalOptions(t *testing.T) {
hookCalled := false
// Create service with hooks registered via options
server := Newx402ResourceServer(
WithBeforeVerifyHook(func(ctx VerifyContext) (*BeforeHookResult, error) {
hookCalled = true
return nil, nil
}),
)
// Verify
payload := types.PaymentPayload{X402Version: 2, Payload: map[string]interface{}{}}
requirements := types.PaymentRequirements{Scheme: "exact", Network: "eip155:8453"}
_, _ = server.VerifyPayment(
context.Background(),
payload,
requirements,
)
if !hookCalled {
t.Error("Expected hook registered via option to be called")
}
}
// Note: mockFacilitatorClient is defined in service_test.go