|
| 1 | +package x402 |
| 2 | + |
| 3 | +import ( |
| 4 | + "encoding/json" |
| 5 | + "math/big" |
| 6 | + "net/http" |
| 7 | + "net/http/httptest" |
| 8 | + "testing" |
| 9 | + "time" |
| 10 | + |
| 11 | + "github.com/ethereum/go-ethereum/common" |
| 12 | + "github.com/ethereum/go-ethereum/common/math" |
| 13 | + "github.com/ethereum/go-ethereum/crypto" |
| 14 | + "github.com/ethereum/go-ethereum/signer/core/apitypes" |
| 15 | + crypto2 "github.com/nathfavour/settlerengine/pkg/crypto" |
| 16 | +) |
| 17 | + |
| 18 | +func TestMiddleware_402Challenge(t *testing.T) { |
| 19 | + cfg := Config{ |
| 20 | + DomainParams: crypto2.DomainParams{ |
| 21 | + ChainID: big.NewInt(84532), |
| 22 | + VerifyingContract: common.HexToAddress("0x0"), |
| 23 | + }, |
| 24 | + NonceExpiry: 1 * time.Minute, |
| 25 | + Recipient: "0x123", |
| 26 | + Asset: "0x456", |
| 27 | + Amount: "100", |
| 28 | + } |
| 29 | + mw := NewMiddleware(cfg) |
| 30 | + |
| 31 | + nextHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 32 | + w.WriteHeader(http.StatusOK) |
| 33 | + w.Write([]byte("OK")) |
| 34 | + }) |
| 35 | + |
| 36 | + handler := mw.Handler(nextHandler) |
| 37 | + |
| 38 | + req := httptest.NewRequest("GET", "/", nil) |
| 39 | + rr := httptest.NewRecorder() |
| 40 | + |
| 41 | + handler.ServeHTTP(rr, req) |
| 42 | + |
| 43 | + if rr.Code != http.StatusPaymentRequired { |
| 44 | + t.Errorf("expected status 402, got %d", rr.Code) |
| 45 | + } |
| 46 | + |
| 47 | + var resp ChallengeResponse |
| 48 | + if err := json.Unmarshal(rr.Body.Bytes(), &resp); err != nil { |
| 49 | + t.Fatalf("failed to unmarshal response: %v", err) |
| 50 | + } |
| 51 | + |
| 52 | + if resp.Payment.Amount != "100" { |
| 53 | + t.Errorf("expected amount 100, got %s", resp.Payment.Amount) |
| 54 | + } |
| 55 | + |
| 56 | + if resp.Payment.Nonce == "" { |
| 57 | + t.Error("expected nonce in response") |
| 58 | + } |
| 59 | +} |
| 60 | + |
| 61 | +func TestMiddleware_Authorized(t *testing.T) { |
| 62 | + privateKey, _ := crypto.GenerateKey() |
| 63 | + agentAddr := crypto.PubkeyToAddress(privateKey.PublicKey) |
| 64 | + |
| 65 | + chainID := big.NewInt(84532) |
| 66 | + verifyingContract := common.HexToAddress("0x0") |
| 67 | + |
| 68 | + cfg := Config{ |
| 69 | + DomainParams: crypto2.DomainParams{ |
| 70 | + ChainID: chainID, |
| 71 | + VerifyingContract: verifyingContract, |
| 72 | + }, |
| 73 | + NonceExpiry: 1 * time.Minute, |
| 74 | + Recipient: agentAddr.Hex(), // Just for testing |
| 75 | + Asset: "0x456", |
| 76 | + Amount: "100", |
| 77 | + } |
| 78 | + mw := NewMiddleware(cfg) |
| 79 | + |
| 80 | + // First request to get a nonce |
| 81 | + req1 := httptest.NewRequest("GET", "/", nil) |
| 82 | + rr1 := httptest.NewRecorder() |
| 83 | + mw.Handler(nil).ServeHTTP(rr1, req1) |
| 84 | + |
| 85 | + var challenge ChallengeResponse |
| 86 | + json.Unmarshal(rr1.Body.Bytes(), &challenge) |
| 87 | + nonce := challenge.Payment.Nonce |
| 88 | + |
| 89 | + // Sign the intent |
| 90 | + intent := crypto2.IntentToPay{ |
| 91 | + Recipient: cfg.Recipient, |
| 92 | + Amount: cfg.Amount, |
| 93 | + Asset: cfg.Asset, |
| 94 | + Nonce: nonce, |
| 95 | + Deadline: uint64(time.Now().Add(1 * time.Hour).Unix()), |
| 96 | + } |
| 97 | + |
| 98 | + typedData := apitypes.TypedData{ |
| 99 | + Types: apitypes.Types{ |
| 100 | + "EIP712Domain": []apitypes.Type{ |
| 101 | + {Name: "name", Type: "string"}, |
| 102 | + {Name: "version", Type: "string"}, |
| 103 | + {Name: "chainId", Type: "uint256"}, |
| 104 | + {Name: "verifyingContract", Type: "address"}, |
| 105 | + }, |
| 106 | + "IntentToPay": []apitypes.Type{ |
| 107 | + {Name: "recipient", Type: "address"}, |
| 108 | + {Name: "amount", Type: "uint256"}, |
| 109 | + {Name: "asset", Type: "address"}, |
| 110 | + {Name: "nonce", Type: "string"}, |
| 111 | + {Name: "deadline", Type: "uint256"}, |
| 112 | + }, |
| 113 | + }, |
| 114 | + PrimaryType: "IntentToPay", |
| 115 | + Domain: apitypes.TypedDataDomain{ |
| 116 | + Name: "SettlerEngine", |
| 117 | + Version: "1", |
| 118 | + ChainId: (*math.HexOrDecimal256)(chainID), |
| 119 | + VerifyingContract: verifyingContract.Hex(), |
| 120 | + }, |
| 121 | + Message: apitypes.TypedDataMessage{ |
| 122 | + "recipient": intent.Recipient, |
| 123 | + "amount": intent.Amount, |
| 124 | + "asset": intent.Asset, |
| 125 | + "nonce": intent.Nonce, |
| 126 | + "deadline": (*math.HexOrDecimal256)(big.NewInt(int64(intent.Deadline))), |
| 127 | + }, |
| 128 | + } |
| 129 | + |
| 130 | + domainSeparator, _ := typedData.HashStruct("EIP712Domain", typedData.Domain.Map()) |
| 131 | + typedDataHash, _ := typedData.HashStruct(typedData.PrimaryType, typedData.Message) |
| 132 | + rawData := make([]byte, 2+32+32) |
| 133 | + rawData[0] = 0x19 |
| 134 | + rawData[1] = 0x01 |
| 135 | + copy(rawData[2:34], domainSeparator) |
| 136 | + copy(rawData[34:66], typedDataHash) |
| 137 | + sighash := crypto.Keccak256(rawData) |
| 138 | + |
| 139 | + signature, _ := crypto.Sign(sighash, privateKey) |
| 140 | + signature[64] += 27 // Transform V |
| 141 | + sigHex := "0x" + common.Bytes2Hex(signature) |
| 142 | + |
| 143 | + payload := PaymentPayload{ |
| 144 | + Intent: intent, |
| 145 | + Signature: sigHex, |
| 146 | + } |
| 147 | + payloadJSON, _ := json.Marshal(payload) |
| 148 | + |
| 149 | + // Second request with X-Payment header |
| 150 | + req2 := httptest.NewRequest("GET", "/", nil) |
| 151 | + req2.Header.Set("X-Payment", string(payloadJSON)) |
| 152 | + rr2 := httptest.NewRecorder() |
| 153 | + |
| 154 | + nextCalled := false |
| 155 | + nextHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 156 | + nextCalled = true |
| 157 | + w.WriteHeader(http.StatusOK) |
| 158 | + }) |
| 159 | + |
| 160 | + mw.Handler(nextHandler).ServeHTTP(rr2, req2) |
| 161 | + |
| 162 | + if rr2.Code != http.StatusOK { |
| 163 | + t.Errorf("expected status 200, got %d. Body: %s", rr2.Code, rr2.Body.String()) |
| 164 | + } |
| 165 | + if !nextCalled { |
| 166 | + t.Error("next handler was not called") |
| 167 | + } |
| 168 | + |
| 169 | + // Third request (Idempotency check) |
| 170 | + req3 := httptest.NewRequest("GET", "/", nil) |
| 171 | + req3.Header.Set("X-Payment", string(payloadJSON)) |
| 172 | + rr3 := httptest.NewRecorder() |
| 173 | + nextCalled = false |
| 174 | + mw.Handler(nextHandler).ServeHTTP(rr3, req3) |
| 175 | + |
| 176 | + if rr3.Code != http.StatusOK { |
| 177 | + t.Errorf("expected status 200 (cached), got %d", rr3.Code) |
| 178 | + } |
| 179 | + if !nextCalled { |
| 180 | + t.Error("next handler was not called (cached)") |
| 181 | + } |
| 182 | +} |
0 commit comments