feat(backend): compile queue, SEP-10 auth, validation middleware, rate limiter - #1464
Open
trustjosh4-dev wants to merge 1 commit into
Open
trustjosh4-dev wants to merge 1 commit into
trustjosh4-dev wants to merge 1 commit into
Conversation
…e limiter Implements four interconnected backend features: ## StellarDevHub#1381 — Redis BullMQ Compile Queue & Distributed Worker - backend/src/queues/compileQueue.ts: Queue with 3 priority tiers (HIGH=1, NORMAL=5, LOW=10), enqueueCompileJob() helper with source-code validation, 500 KB size limit, and dedup by jobId - backend/src/workers/compileWorker.ts: Distributed BullMQ Worker with COMPILE_WORKER_CONCURRENCY throttle (default 2), global token-bucket limiter, per-job WebSocket progress streaming via broadcastEvent(), graceful shutdown handler ## StellarDevHub#1383 — SEP-10 Stellar Web Authentication (Production Provider) - backend/src/auth/sep10.service.ts: Enhanced with: - Cryptographic nonce (32-byte) generated per challenge and stored in Redis alongside the transaction hash for binding - Per-account sliding-window rate limit (max 10 challenges/60s) - Atomic Redis SET NX replay prevention (challenge hash marked used before signature verification so concurrent replays both fail) - JWT claims include walletAddress + sep10Nonce for downstream authorization and audit trail - Fail-closed on Horizon non-404 errors - Acceptance criteria met: replaying a signed challenge returns error; valid signatures receive authenticated session JWTs ## StellarDevHub#1385 — Universal Zod Validation Middleware - backend/src/middleware/validation.ts: Enhanced with: - stripPrototypePollutingKeys(): recursively removes __proto__, constructor, prototype before any handler sees the payload - extractSchemaKeys(): extracts declared ZodObject keys at route registration time (zero overhead per request) - stripUnwhitelistedKeys(): drops any body keys not declared in the Zod schema (mass-assignment protection) - validate() factory pre-computes allowed keys and applies both prototype pollution guard and key whitelist on every request ## StellarDevHub#1384 — Redis-backed Distributed Rate Limiter - backend/src/middleware/rateLimiter.ts: Enhanced with: - extractClientIp(): TRUSTED_PROXY_DEPTH-aware X-Forwarded-For parsing -- walks right-to-left to avoid header spoofing - ApiKeyTierConfig loaded from RATE_LIMIT_API_KEY_TIERS_JSON env var; keys matching a configured prefix receive higher burst and sustained quotas - resolveApiKeyTier(): returns the matching tier or null for default - Single unified rate-limit key per request (API key > user > IP) so authenticated users with API keys have one quota bucket Closes StellarDevHub#1381 Closes StellarDevHub#1383 Closes StellarDevHub#1385 Closes StellarDevHub#1384
|
@trustjosh4-dev is attempting to deploy a commit to the Ayomide Adeniran's projects Team on Vercel. A member of the Team first needs to authorize it. |
|
@trustjosh4-dev Great news! 🎉 Based on an automated assessment of this PR, the linked Wave issue(s) no longer count against your application limits. You can now already apply to more issues while waiting for a review of this PR. Keep up the great work! 🚀 |
This branch has not been deployed
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
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.
Summary
Implements four production-ready backend features across the compilation pipeline, authentication, input validation, and rate limiting subsystems.
Changes
#1381— Redis BullMQ Compile Queue & Distributed WorkerFiles:
backend/src/queues/compileQueue.ts,backend/src/workers/compileWorker.tscompileQueue.ts): BullMQQueue<CompileJobData>with three priority tiers —HIGH=1(premium/API-key),NORMAL=5(authenticated),LOW=10(anonymous).enqueueCompileJob()validates source code (non-empty, ≤500 KB, valid language), deduplicates byuserId + source hashviajobId, and returns job metadata for WebSocket polling. Redis connection parsed fromREDIS_URL(follows project pattern). Configurable retry: 3 attempts with exponential back-off (3 s → 6 s → 12 s).compileWorker.ts): Distributed BullMQWorkerconsuming from the same queue. Concurrency throttled byCOMPILE_WORKER_CONCURRENCYenv var (default2— Rust builds are CPU/RAM intensive). Per-job timeout enforced viaCOMPILE_TIMEOUT_MS(default 5 min). Progress streaming: each build phase (preparing → compiling → linking → packaging → completed/failed) emits acompile_progressevent viabroadcastEvent()to the student's private Socket.IO room. Graceful shutdown viacloseCompileWorker().#1383— SEP-10 Stellar Web Authentication (Production Provider)File:
backend/src/auth/sep10.service.tsbuildSep10Challenge()call generates a 32-byte cryptographically random nonce stored in Redis alongside the transaction hash (sep10:ch:<txHash>→{accountId, nonce}). After successful verification the nonce is embedded in JWT claims (sep10Nonce).RATE_LIMITEDerror code; fails open if Redis is unavailable.verifySep10Challenge()checkssep10:used:<txHash>before marking it used — concurrent replays both observe the existing key and fail. TTL = challenge lifetime + 60 s verification window.walletAddressandsep10Noncefor downstream authorization.✅ Acceptance criteria: Replaying an existing signed challenge fails; valid signatures receive authenticated session JWTs.
#1385— Universal Zod Validation MiddlewareFile:
backend/src/middleware/validation.tsstripPrototypePollutingKeys(): Recursively removes__proto__,constructor,prototype, and other dangerous keys before any handler or schema sees the payload. Runs inside bothvalidateInput(global) andvalidate()(per-route).extractSchemaKeys(): Traverses Zod optional/nullable/default wrappers to extract top-levelZodObjectshape keys at route-registration time — zero cost per request.stripUnwhitelistedKeys(): Drops any body key not declared in the schema, eliminating mass-assignment vectors (e.g.isAdmin: trueinjected into a register body).validate()factory: Pre-computes allowed keys; per-request pipeline isstripPrototypePollutingKeys → stripUnwhitelistedKeys → schema.parse. Error responses use the project's versionedApiErrorenvelope and never echo submitted values.validateInputglobal guard: Prototype pollution stripping runs before HTML sanitization in the global middleware layer.#1384— Redis-backed Distributed Rate LimiterFile:
backend/src/middleware/rateLimiter.tsextractClientIp()): ReadsTRUSTED_PROXY_DEPTH(default 0) and walks theX-Forwarded-Forheader right-to-left by that many hops. When the header has fewer entries than the configured depth, falls back to the socket address and logs a warning.ApiKeyTierConfig): Loaded fromRATE_LIMIT_API_KEY_TIERS_JSONenv var (JSON array of{prefix, burstMax, sustainedMax}).resolveApiKeyTier()matches the request'sX-API-KeyorAuthorization: ApiKey <key>header against configured prefixes.apikey:<key[:24]>; authenticated users → user ID; anonymous → spoofing-resistant IP. Guarantees each principal has a single quota bucket regardless of originating IP.enforceTier()/ RFC 6585 headers preserved unchanged.Environment Variables Added
COMPILE_WORKER_CONCURRENCY2COMPILE_TIMEOUT_MS300000TRUSTED_PROXY_DEPTH0RATE_LIMIT_API_KEY_TIERS_JSON[]Closes #1381
Closes #1383
Closes #1385
Closes #1384