feat(gateway): make request body size configurable via env#186
feat(gateway): make request body size configurable via env#186PranavAgarkar07 wants to merge 4 commits into
Conversation
Add dedicated duplicate-nonce error kind for nonce_already_used (was incorrectly mapped to 'expired'). Sanitize raw gateway JSON blobs in debug detail to show clean error codes instead. Closes AnkanMisra#165
Covers all HTTP status -> error kind mappings (400/402/403/408/409/429/ 502/504/5xx), gateway error codes (nonce_already_used, invalid_signature, upstream_unavailable, verification_unavailable, verifier_timeout, etc.), wallet error patterns (rejection codes 4001/ACTION_REJECTED, wrong chain messages, missing wallet, network errors), and detail sanitization.
Replace hardcoded 10MB limit with MAX_REQUEST_BODY_MB env var parsed by getMaxBodySize() helper in config.go. Falls back to 10MB when unset or invalid. Also fixes a P1 regression from the original implementation: the 413 error response key was mistakenly changed from 'max_size' to 'max_size_mb' with a different format. The original 'max_size' key with '%dMB' string format is restored, now driven by the configurable value. Closes AnkanMisra#116
|
@PranavAgarkar07 is attempting to deploy a commit to the ankanmisra's projects Team on Vercel. A member of the Team first needs to authorize it. |
📝 WalkthroughWalkthroughRequest body size limits transition from hardcoded 10MB to environment configuration; error classification adds duplicate-nonce handling with detail sanitization; web error tests validate classification paths and detail formatting rules. ChangesRequest Body Configurability and Error Handling
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~22 minutes Possibly related issues
Suggested labels
Suggested reviewers
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
⚔️ Resolve merge conflicts
Warning There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure. 🔧 ESLint
ESLint skipped: no ESLint configuration detected in root package.json. To enable, add 🔧 golangci-lint (2.12.2)level=error msg="[linters_context] typechecking error: pattern ./...: directory prefix . does not contain main module or its selected dependencies" Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 2
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@gateway/config.go`:
- Around line 99-102: The getMaxBodySize function must guard against
non-positive values returned by getEnvAsInt (e.g., MAX_REQUEST_BODY_MB=0 or
negative) by clamping them to the default used elsewhere (like
getPositiveTimeout); update getMaxBodySize to treat mb <= 0 as the default 10
(or use the same default constant if present) before converting to bytes so
http.MaxBytesReader never receives a zero/negative limit and accidentally
rejects valid requests.
In `@gateway/main.go`:
- Around line 419-425: Replace the hardcoded const maxBodySize = 10*1024*1024 in
gateway/cache.go and any Content-Length checks or http.MaxBytesReader uses with
the dynamic value from getMaxBodySize(); update the cache middleware (e.g., the
Cache middleware/handler function) to call maxSize := getMaxBodySize(), use
http.MaxBytesReader(c.Writer, c.Request.Body, maxSize), compare Content-Length
against maxSize, and when returning 413 include the same formatted max_size
string as in gateway/main.go (fmt.Sprintf("%dMB", maxSize/1024/1024)) so
CACHE_ENABLED respects MAX_REQUEST_BODY_MB.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID: 169325ae-7afd-47d8-8070-93b825677bde
📒 Files selected for processing (6)
.env.examplegateway/config.gogateway/main.goweb/package.jsonweb/src/lib/errors.test.tsweb/src/lib/errors.ts
| func getMaxBodySize() int64 { | ||
| mb := getEnvAsInt("MAX_REQUEST_BODY_MB", 10) | ||
| return int64(mb) * 1024 * 1024 | ||
| } |
There was a problem hiding this comment.
Guard against non-positive MAX_REQUEST_BODY_MB.
getEnvAsInt returns 0/negative values verbatim, so MAX_REQUEST_BODY_MB=0 (or a negative) produces a 0/negative byte limit. http.MaxBytesReader with a 0 limit rejects every non-empty body, silently turning all /api/ai/summarize requests into 413s. The sibling getPositiveTimeout already clamps non-positive values to the default; mirror that here.
🛡️ Proposed fix to clamp non-positive values
func getMaxBodySize() int64 {
mb := getEnvAsInt("MAX_REQUEST_BODY_MB", 10)
+ if mb <= 0 {
+ log.Printf("Warning: MAX_REQUEST_BODY_MB must be positive, using default 10")
+ mb = 10
+ }
return int64(mb) * 1024 * 1024
}📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| func getMaxBodySize() int64 { | |
| mb := getEnvAsInt("MAX_REQUEST_BODY_MB", 10) | |
| return int64(mb) * 1024 * 1024 | |
| } | |
| func getMaxBodySize() int64 { | |
| mb := getEnvAsInt("MAX_REQUEST_BODY_MB", 10) | |
| if mb <= 0 { | |
| log.Printf("Warning: MAX_REQUEST_BODY_MB must be positive, using default 10") | |
| mb = 10 | |
| } | |
| return int64(mb) * 1024 * 1024 | |
| } |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@gateway/config.go` around lines 99 - 102, The getMaxBodySize function must
guard against non-positive values returned by getEnvAsInt (e.g.,
MAX_REQUEST_BODY_MB=0 or negative) by clamping them to the default used
elsewhere (like getPositiveTimeout); update getMaxBodySize to treat mb <= 0 as
the default 10 (or use the same default constant if present) before converting
to bytes so http.MaxBytesReader never receives a zero/negative limit and
accidentally rejects valid requests.
| maxSize := getMaxBodySize() | ||
| c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, maxSize) | ||
| requestBody, err = io.ReadAll(c.Request.Body) | ||
| if err != nil { | ||
| var maxBytesErr *http.MaxBytesError | ||
| if errors.As(err, &maxBytesErr) { | ||
| c.JSON(413, gin.H{"error": "Payload too large", "max_size": "10MB"}) | ||
| c.JSON(413, gin.H{"error": "Payload too large", "max_size": fmt.Sprintf("%dMB", maxSize/1024/1024)}) |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Confirm cache.go still hardcodes the body limit / 413 max_size instead of using getMaxBodySize()
rg -nC3 'maxBodySize|max_size|MaxBytesReader' gateway/cache.goRepository: AnkanMisra/MicroAI-Paygate
Length of output: 1084
Fix gateway/cache.go to use the configurable request body limit instead of a hardcoded 10MB
gateway/cache.go hardcodes const maxBodySize = 10 * 1024 * 1024 for both the Content-Length check and http.MaxBytesReader, and returns a fixed max_size: "10MB" on 413. This makes the cached request path inconsistent with gateway/main.go’s dynamic getMaxBodySize() + formatted max_size, so MAX_REQUEST_BODY_MB won’t be honored when CACHE_ENABLED=true. Route cache middleware through getMaxBodySize() and use the same max_size formatting as the main handler.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@gateway/main.go` around lines 419 - 425, Replace the hardcoded const
maxBodySize = 10*1024*1024 in gateway/cache.go and any Content-Length checks or
http.MaxBytesReader uses with the dynamic value from getMaxBodySize(); update
the cache middleware (e.g., the Cache middleware/handler function) to call
maxSize := getMaxBodySize(), use http.MaxBytesReader(c.Writer, c.Request.Body,
maxSize), compare Content-Length against maxSize, and when returning 413 include
the same formatted max_size string as in gateway/main.go (fmt.Sprintf("%dMB",
maxSize/1024/1024)) so CACHE_ENABLED respects MAX_REQUEST_BODY_MB.
Summary
Replaces the hardcoded
const maxBodySize = 10 * 1024 * 1024ingateway/main.gowith a configurable value driven by theMAX_REQUEST_BODY_MBenvironment variable. A new helpergetMaxBodySize()ingateway/config.gohandles parsing and falls back to 10 MB when the variable is unset or invalid.Also fixes a P1 issue introduced when the original hardcoded constant was replaced: the 413 error response JSON key drifted from
"max_size"to"max_size_mb"with a type change (string → int). Restored the original response format so clients parsing the error do not break.Type Of Change
Affected Areas
gateway/)verifier/)web/)Contributor Checklist
Verification
Notes For Reviewers
The
getMaxBodySize()helper lives inconfig.goalongside the other typed-helper functions (getEnvAsDuration,getEnvAsBool, etc.) and follows the same pattern: log a warning and return the default when parsing fails.Summary by CodeRabbit
New Features
Tests
Chores