-
Notifications
You must be signed in to change notification settings - Fork 1.9k
Expand file tree
/
Copy pathfacilitator_hooks_test.go
More file actions
387 lines (313 loc) · 11.5 KB
/
Copy pathfacilitator_hooks_test.go
File metadata and controls
387 lines (313 loc) · 11.5 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
package x402
import (
"context"
"encoding/json"
"errors"
"fmt"
"testing"
"github.com/x402-foundation/x402/go/v2/types"
)
// Test Facilitator BeforeVerify hook - abort verification
func TestFacilitatorBeforeVerifyHook_Abort(t *testing.T) {
facilitator := Newx402Facilitator()
// Register hook that aborts verification
facilitator.OnBeforeVerify(func(ctx FacilitatorVerifyContext) (*FacilitatorBeforeHookResult, error) {
return &FacilitatorBeforeHookResult{
Abort: true,
Reason: "Facilitator 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"}
payloadBytes, _ := json.Marshal(payload)
requirementsBytes, _ := json.Marshal(requirements)
result, err := facilitator.Verify(
context.Background(),
payloadBytes,
requirementsBytes,
)
if err == nil {
t.Error("Expected error from aborted verification")
}
if result != nil {
t.Error("Expected nil result when verification is aborted")
}
// Check error is VerifyError with correct reason
ve := &VerifyError{}
if errors.As(err, &ve) {
if ve.InvalidReason != "Facilitator security check failed" {
t.Errorf("Expected specific reason, got '%s'", ve.InvalidReason)
}
} else {
t.Errorf("Expected *VerifyError, got %T", err)
}
}
// Test Facilitator AfterVerify hook
func TestFacilitatorAfterVerifyHook(t *testing.T) {
var capturedPayer string
facilitator := Newx402Facilitator()
// Register mock scheme facilitator
mockScheme := &mockSchemeFacilitator{
scheme: "exact",
verifyFunc: func(ctx context.Context, payload types.PaymentPayload, reqs types.PaymentRequirements) (*VerifyResponse, error) {
return &VerifyResponse{IsValid: true, Payer: "0xTestPayer"}, nil
},
}
facilitator.Register([]Network{"eip155:8453"}, mockScheme)
// Register hook to capture result
facilitator.OnAfterVerify(func(ctx FacilitatorVerifyResultContext) error {
capturedPayer = ctx.Result.Payer
return nil
})
// Verify payment (marshal to bytes for facilitator API)
payload := types.PaymentPayload{X402Version: 2, Payload: map[string]interface{}{}}
requirements := types.PaymentRequirements{Scheme: "exact", Network: "eip155:8453"}
payloadBytes, _ := json.Marshal(payload)
requirementsBytes, _ := json.Marshal(requirements)
result, err := facilitator.Verify(
context.Background(),
payloadBytes,
requirementsBytes,
)
if err != nil {
t.Errorf("Expected no error, got %v", err)
}
if !result.IsValid {
t.Error("Expected verification to succeed")
}
// Check hook captured the result
if capturedPayer != "0xTestPayer" {
t.Errorf("Expected hook to capture payer '0xTestPayer', got '%s'", capturedPayer)
}
}
// Test Facilitator OnVerifyFailure hook - recovery
func TestFacilitatorOnVerifyFailureHook_Recover(t *testing.T) {
facilitator := Newx402Facilitator()
// Register mock scheme facilitator that fails
mockScheme := &mockSchemeFacilitator{
scheme: "exact",
verifyFunc: func(ctx context.Context, payload types.PaymentPayload, reqs types.PaymentRequirements) (*VerifyResponse, error) {
return nil, NewVerifyError("verification_failed", "", fmt.Sprintf("verification failed: %s", payload.Payload["signature"]))
},
}
facilitator.Register([]Network{"eip155:8453"}, mockScheme)
// Register hook that recovers from failure
facilitator.OnVerifyFailure(func(ctx FacilitatorVerifyFailureContext) (*FacilitatorVerifyFailureHookResult, error) {
return &FacilitatorVerifyFailureHookResult{
Recovered: true,
Result: &VerifyResponse{
IsValid: true,
Payer: "0xRecovered",
},
}, nil
})
// Verify payment (should be recovered by hook)
payload := types.PaymentPayload{X402Version: 2, Payload: map[string]interface{}{}}
requirements := types.PaymentRequirements{Scheme: "exact", Network: "eip155:8453"}
payloadBytes, _ := json.Marshal(payload)
requirementsBytes, _ := json.Marshal(requirements)
result, err := facilitator.Verify(
context.Background(),
payloadBytes,
requirementsBytes,
)
if err != nil {
t.Errorf("Expected hook to recover, got error: %v", err)
}
if !result.IsValid {
t.Error("Expected hook to recover verification")
}
if result.Payer != "0xRecovered" {
t.Errorf("Expected recovered payer, got '%s'", result.Payer)
}
}
// Test Facilitator BeforeSettle hook - abort
func TestFacilitatorBeforeSettleHook_Abort(t *testing.T) {
facilitator := Newx402Facilitator()
// Register hook that aborts settlement
facilitator.OnBeforeSettle(func(ctx FacilitatorSettleContext) (*FacilitatorBeforeHookResult, error) {
return &FacilitatorBeforeHookResult{
Abort: true,
Reason: "Gas price too high",
}, 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"}
payloadBytes, _ := json.Marshal(payload)
requirementsBytes, _ := json.Marshal(requirements)
result, err := facilitator.Settle(
context.Background(),
payloadBytes,
requirementsBytes,
)
if err == nil {
t.Error("Expected error when settlement is aborted")
}
if result != nil {
t.Error("Expected nil result when settlement is aborted")
}
}
// Test Facilitator AfterSettle hook
func TestFacilitatorAfterSettleHook(t *testing.T) {
var capturedTx string
facilitator := Newx402Facilitator()
// Register mock scheme facilitator
mockScheme := &mockSchemeFacilitator{
scheme: "exact",
settleFunc: func(ctx context.Context, payload types.PaymentPayload, reqs types.PaymentRequirements) (*SettleResponse, error) {
return &SettleResponse{Success: true, Transaction: "0xFacilitatorTx", Network: Network(reqs.Network), Payer: "0xPayer"}, nil
},
}
facilitator.Register([]Network{"eip155:8453"}, mockScheme)
// Register hook to capture settlement result
facilitator.OnAfterSettle(func(ctx FacilitatorSettleResultContext) error {
capturedTx = ctx.Result.Transaction
return nil
})
// Settle payment
payload := types.PaymentPayload{X402Version: 2, Payload: map[string]interface{}{}}
requirements := types.PaymentRequirements{Scheme: "exact", Network: "eip155:8453"}
payloadBytes, _ := json.Marshal(payload)
requirementsBytes, _ := json.Marshal(requirements)
result, err := facilitator.Settle(
context.Background(),
payloadBytes,
requirementsBytes,
)
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
if capturedTx != "0xFacilitatorTx" {
t.Errorf("Expected hook to capture tx '0xFacilitatorTx', got '%s'", capturedTx)
}
}
// Test Facilitator OnSettleFailure hook - recovery
func TestFacilitatorOnSettleFailureHook_Recover(t *testing.T) {
facilitator := Newx402Facilitator()
// Register mock scheme facilitator that fails
mockScheme := &mockSchemeFacilitator{
scheme: "exact",
settleFunc: func(ctx context.Context, payload types.PaymentPayload, reqs types.PaymentRequirements) (*SettleResponse, error) {
return nil, NewSettleError("settlement_failed", "", Network(reqs.Network), "", "settlement failed")
},
}
facilitator.Register([]Network{"eip155:8453"}, mockScheme)
// Register hook that recovers from failure
facilitator.OnSettleFailure(func(ctx FacilitatorSettleFailureContext) (*FacilitatorSettleFailureHookResult, error) {
return &FacilitatorSettleFailureHookResult{
Recovered: true,
Result: &SettleResponse{
Success: true,
Transaction: "0xFacilitatorRecovered",
Network: Network(ctx.Requirements.GetNetwork()),
Payer: "0xRecoveredPayer",
},
}, nil
})
// Settle payment (should be recovered by hook)
payload := types.PaymentPayload{X402Version: 2, Payload: map[string]interface{}{}}
requirements := types.PaymentRequirements{Scheme: "exact", Network: "eip155:8453"}
payloadBytes, _ := json.Marshal(payload)
requirementsBytes, _ := json.Marshal(requirements)
result, err := facilitator.Settle(
context.Background(),
payloadBytes,
requirementsBytes,
)
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 != "0xFacilitatorRecovered" {
t.Errorf("Expected recovered transaction, got '%s'", result.Transaction)
}
}
// Test Facilitator multiple hooks execution order
func TestFacilitatorMultipleHooks_ExecutionOrder(t *testing.T) {
executionOrder := []string{}
facilitator := Newx402Facilitator()
// Register mock scheme facilitator
mockScheme := &mockSchemeFacilitator{
scheme: "exact",
verifyFunc: func(ctx context.Context, payload types.PaymentPayload, reqs types.PaymentRequirements) (*VerifyResponse, error) {
return &VerifyResponse{IsValid: true, Payer: "0xpayer"}, nil
},
}
facilitator.Register([]Network{"eip155:8453"}, mockScheme)
// Register multiple hooks in order
facilitator.OnBeforeVerify(func(ctx FacilitatorVerifyContext) (*FacilitatorBeforeHookResult, error) {
executionOrder = append(executionOrder, "before1")
return nil, nil
})
facilitator.OnBeforeVerify(func(ctx FacilitatorVerifyContext) (*FacilitatorBeforeHookResult, error) {
executionOrder = append(executionOrder, "before2")
return nil, nil
})
facilitator.OnAfterVerify(func(ctx FacilitatorVerifyResultContext) error {
executionOrder = append(executionOrder, "after1")
return nil
})
facilitator.OnAfterVerify(func(ctx FacilitatorVerifyResultContext) error {
executionOrder = append(executionOrder, "after2")
return nil
})
// Verify payment
payload := types.PaymentPayload{X402Version: 2, Payload: map[string]interface{}{}}
requirements := types.PaymentRequirements{Scheme: "exact", Network: "eip155:8453"}
payloadBytes, _ := json.Marshal(payload)
requirementsBytes, _ := json.Marshal(requirements)
_, _ = facilitator.Verify(
context.Background(),
payloadBytes,
requirementsBytes,
)
// 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
}
}
}
// Mock scheme facilitator for testing
type mockSchemeFacilitator struct {
scheme string
verifyFunc func(ctx context.Context, payload types.PaymentPayload, reqs types.PaymentRequirements) (*VerifyResponse, error)
settleFunc func(ctx context.Context, payload types.PaymentPayload, reqs types.PaymentRequirements) (*SettleResponse, error)
}
func (m *mockSchemeFacilitator) Scheme() string {
return m.scheme
}
func (m *mockSchemeFacilitator) CaipFamily() string {
return "test:*"
}
func (m *mockSchemeFacilitator) GetExtra(_ Network) map[string]interface{} {
return nil
}
func (m *mockSchemeFacilitator) GetSigners(_ Network) []string {
return []string{}
}
func (m *mockSchemeFacilitator) Verify(ctx context.Context, payload types.PaymentPayload, requirements types.PaymentRequirements, _ *FacilitatorContext) (*VerifyResponse, error) {
if m.verifyFunc != nil {
return m.verifyFunc(ctx, payload, requirements)
}
return nil, errors.New("not implemented")
}
func (m *mockSchemeFacilitator) Settle(ctx context.Context, payload types.PaymentPayload, requirements types.PaymentRequirements, _ *FacilitatorContext) (*SettleResponse, error) {
if m.settleFunc != nil {
return m.settleFunc(ctx, payload, requirements)
}
return nil, errors.New("not implemented")
}