-
Notifications
You must be signed in to change notification settings - Fork 58
[codex] refactor gateway paid-request verification flow #235
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Draft
AnkanMisra
wants to merge
1
commit into
main
Choose a base branch
from
codex/refactor-gateway-paid-request-flow
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,91 @@ | ||
| package main | ||
|
|
||
| import ( | ||
| "context" | ||
| "errors" | ||
| "fmt" | ||
| "net/http" | ||
| "strconv" | ||
|
|
||
| "github.com/gin-gonic/gin" | ||
| ) | ||
|
|
||
| type verifiedPayment struct { | ||
| PaymentContext PaymentContext | ||
| RecoveredAddress string | ||
| } | ||
|
|
||
| func verifyPaidRequest(c *gin.Context) (*verifiedPayment, bool) { | ||
| signature := c.GetHeader("X-402-Signature") | ||
| nonce := c.GetHeader("X-402-Nonce") | ||
|
|
||
| if signature == "" || nonce == "" { | ||
| c.JSON(http.StatusPaymentRequired, gin.H{ | ||
| "error": "Payment Required", | ||
| "message": "Please sign the payment context", | ||
| "paymentContext": createPaymentContext(), | ||
| }) | ||
| return nil, false | ||
| } | ||
|
|
||
| timestampValue, ok := paymentTimestamp(c) | ||
| if !ok { | ||
| return nil, false | ||
| } | ||
|
|
||
| verifyResp, paymentCtx, err := verifyPayment(c.Request.Context(), signature, nonce, timestampValue) | ||
| if err != nil { | ||
| verificationTotal.WithLabelValues("error").Inc() | ||
|
|
||
| if errors.Is(err, context.DeadlineExceeded) { | ||
| respondError(c, http.StatusGatewayTimeout, "verifier_timeout", err) | ||
| } else { | ||
| respondError(c, http.StatusBadGateway, "verification_unavailable", err) | ||
| } | ||
| return nil, false | ||
| } | ||
|
|
||
| if !verifyResp.IsValid { | ||
| verificationTotal.WithLabelValues("invalid").Inc() | ||
| respondVerificationFailure(c, verifyResp) | ||
| return nil, false | ||
| } | ||
| if verifyResp.RecoveredAddress == "" { | ||
| verificationTotal.WithLabelValues("error").Inc() | ||
| respondError(c, http.StatusBadGateway, "verification_unavailable", fmt.Errorf("verifier success missing recovered_address")) | ||
| return nil, false | ||
| } | ||
|
|
||
| verificationTotal.WithLabelValues("success").Inc() | ||
|
|
||
| return &verifiedPayment{ | ||
| PaymentContext: *paymentCtx, | ||
| RecoveredAddress: verifyResp.RecoveredAddress, | ||
| }, true | ||
| } | ||
|
|
||
| func paymentTimestamp(c *gin.Context) (uint64, bool) { | ||
| timestampHeader := c.GetHeader("X-402-Timestamp") | ||
| if timestampHeader == "" { | ||
| respondError(c, http.StatusBadRequest, "invalid_timestamp", fmt.Errorf("missing X-402-Timestamp header")) | ||
| return 0, false | ||
| } | ||
|
|
||
| timestampValue, err := strconv.ParseUint(timestampHeader, 10, 64) | ||
| if err != nil || timestampValue == 0 { | ||
| respondError(c, http.StatusBadRequest, "invalid_timestamp", fmt.Errorf("invalid X-402-Timestamp header")) | ||
| return 0, false | ||
| } | ||
|
|
||
| return timestampValue, true | ||
| } | ||
|
|
||
| func sendPaidResult(c *gin.Context, payment *verifiedPayment, requestBody []byte, result string) error { | ||
| if payment == nil { | ||
| err := fmt.Errorf("missing verified payment") | ||
| respondError(c, http.StatusInternalServerError, "receipt_generation_failed", err) | ||
| return err | ||
| } | ||
|
|
||
| return generateAndSendReceipt(c, payment.PaymentContext, payment.RecoveredAddress, requestBody, result) | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,106 @@ | ||
| package main | ||
|
|
||
| import ( | ||
| "context" | ||
| "encoding/json" | ||
| "net/http" | ||
| "net/http/httptest" | ||
| "strings" | ||
| "testing" | ||
| "time" | ||
|
|
||
| "github.com/gin-gonic/gin" | ||
| "github.com/stretchr/testify/require" | ||
| ) | ||
|
|
||
| func newPaymentFlowTestContext(req *http.Request) (*gin.Context, *httptest.ResponseRecorder) { | ||
| gin.SetMode(gin.TestMode) | ||
| recorder := httptest.NewRecorder() | ||
| c, _ := gin.CreateTestContext(recorder) | ||
| c.Request = req | ||
| if correlationID := req.Header.Get("X-Correlation-ID"); correlationID != "" { | ||
| c.Set("correlation_id", correlationID) | ||
| c.Request = c.Request.WithContext(context.WithValue(c.Request.Context(), CorrelationIDKey, correlationID)) | ||
| } | ||
| return c, recorder | ||
| } | ||
|
|
||
| func TestVerifyPaidRequestWritesPaymentChallengeForMissingHeaders(t *testing.T) { | ||
| req := httptest.NewRequest(http.MethodPost, "/api/ai/summarize", strings.NewReader(`{"text":"hello"}`)) | ||
| c, recorder := newPaymentFlowTestContext(req) | ||
|
|
||
| verified, ok := verifyPaidRequest(c) | ||
|
|
||
| require.False(t, ok) | ||
| require.Nil(t, verified) | ||
| require.Equal(t, http.StatusPaymentRequired, recorder.Code) | ||
|
|
||
| var response struct { | ||
| Error string `json:"error"` | ||
| Message string `json:"message"` | ||
| PaymentContext PaymentContext `json:"paymentContext"` | ||
| } | ||
| require.NoError(t, json.Unmarshal(recorder.Body.Bytes(), &response)) | ||
| require.Equal(t, "Payment Required", response.Error) | ||
| require.Equal(t, "Please sign the payment context", response.Message) | ||
| require.NotEmpty(t, response.PaymentContext.Recipient) | ||
| require.NotEmpty(t, response.PaymentContext.Token) | ||
| require.NotEmpty(t, response.PaymentContext.Amount) | ||
| require.NotEmpty(t, response.PaymentContext.Nonce) | ||
| require.Positive(t, response.PaymentContext.ChainID) | ||
| require.Positive(t, response.PaymentContext.Timestamp) | ||
| } | ||
|
|
||
| func TestVerifyPaidRequestReturnsVerifiedPayment(t *testing.T) { | ||
| withVerifierResponse(t, http.StatusOK, `{"is_valid":true,"recovered_address":"0xabc","error":""}`) | ||
| req := signedSummarizeRequest(`{"text":"hello"}`) | ||
| c, recorder := newPaymentFlowTestContext(req) | ||
|
|
||
| verified, ok := verifyPaidRequest(c) | ||
|
|
||
| require.True(t, ok) | ||
| require.Equal(t, http.StatusOK, recorder.Code) | ||
| require.Equal(t, "0xabc", verified.RecoveredAddress) | ||
| require.Equal(t, "nonce-1", verified.PaymentContext.Nonce) | ||
| require.Equal(t, uint64(1700000000), verified.PaymentContext.Timestamp) | ||
| } | ||
|
|
||
| func TestVerifyPaidRequestMapsVerifierTimeout(t *testing.T) { | ||
| server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | ||
| time.Sleep(1500 * time.Millisecond) | ||
| })) | ||
| t.Cleanup(server.Close) | ||
| t.Setenv("VERIFIER_URL", server.URL) | ||
| t.Setenv("VERIFIER_TIMEOUT_SECONDS", "1") | ||
|
|
||
| req := signedSummarizeRequest(`{"text":"hello"}`) | ||
| c, recorder := newPaymentFlowTestContext(req) | ||
|
|
||
| verified, ok := verifyPaidRequest(c) | ||
|
|
||
| require.False(t, ok) | ||
| require.Nil(t, verified) | ||
| require.Equal(t, http.StatusGatewayTimeout, recorder.Code) | ||
|
|
||
| var response map[string]string | ||
| require.NoError(t, json.Unmarshal(recorder.Body.Bytes(), &response)) | ||
| require.Equal(t, "verifier_timeout", response["error"]) | ||
| require.Equal(t, "test-correlation-id", response["correlation_id"]) | ||
| } | ||
|
|
||
| func TestVerifyPaidRequestRequiresRecoveredAddress(t *testing.T) { | ||
| withVerifierResponse(t, http.StatusOK, `{"is_valid":true,"recovered_address":"","error":""}`) | ||
| req := signedSummarizeRequest(`{"text":"hello"}`) | ||
| c, recorder := newPaymentFlowTestContext(req) | ||
|
|
||
| verified, ok := verifyPaidRequest(c) | ||
|
|
||
| require.False(t, ok) | ||
| require.Nil(t, verified) | ||
| require.Equal(t, http.StatusBadGateway, recorder.Code) | ||
|
|
||
| var response map[string]string | ||
| require.NoError(t, json.Unmarshal(recorder.Body.Bytes(), &response)) | ||
| require.Equal(t, "verification_unavailable", response["error"]) | ||
| require.Equal(t, "test-correlation-id", response["correlation_id"]) | ||
| } |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
When
CACHE_ENABLED=false(the default path whereregisterAPIRoutesattacheshandleSummarizedirectly), this now callsverifyPaidRequestbefore the request body is read and size-limited below. The verifier claims a nonce after any valid signature, so a signed request with an oversized or otherwise unreadable body now gets rejected with 413/500 only after burning the payment nonce and cannot retry that signed payment; before this refactor, theMaxBytesReaderbody read happened beforeverifyPayment. Keep the verifier call after the body read/size guard, or split timestamp/header validation from nonce-claiming verification.Useful? React with 👍 / 👎.