-
-
Notifications
You must be signed in to change notification settings - Fork 262
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
feature(provider): Rate limiting #15583
Open
0xTxbi
wants to merge
22
commits into
master
Choose a base branch
from
provider-rate-limit
base: master
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.
Open
Changes from 19 commits
Commits
Show all changes
22 commits
Select commit
Hold shift + click to select a range
afada47
update package.json
0xTxbi 6f7706f
update types
0xTxbi d350379
add unlock contracts config
0xTxbi 289f0f4
add rate limiter logic
0xTxbi c4ac13b
update handler
0xTxbi 8bab292
update wrangler
0xTxbi 0de4e22
update package.json
0xTxbi ad7490f
update yarn.lock
0xTxbi 50abe41
update unlock contract config
0xTxbi 74c1084
update index
0xTxbi 716321b
update readme
0xTxbi 319669d
clean up
0xTxbi b9f7d53
update env to use secret
0xTxbi 0f952c3
update handler to use secret
0xTxbi 57e84f2
update .op.env
0xTxbi a6c3bbc
update readme
0xTxbi d39e982
update op.env
0xTxbi 720cb0e
log crossed thresholds
0xTxbi 09e27ee
Merge branch 'master' into provider-rate-limit
0xTxbi 842bc0e
improved error handling
0xTxbi 9b0eba5
set up tests
0xTxbi 66ebc95
add comprehensive tests
0xTxbi 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 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 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 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 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 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 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 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,148 @@ | ||
import { Env } from './types' | ||
import { isKnownUnlockContract, checkIsLock } from './unlockContracts' | ||
|
||
/** | ||
* Checks if the request has the correct Locksmith secret key | ||
*/ | ||
export const hasValidLocksmithSecret = ( | ||
request: Request, | ||
env: Env | ||
): boolean => { | ||
if (!env.LOCKSMITH_SECRET_KEY) return false | ||
|
||
// Get the secret from the query parameter | ||
const url = new URL(request.url) | ||
const secret = url.searchParams.get('secret') | ||
|
||
// Check if the secret matches | ||
return secret === env.LOCKSMITH_SECRET_KEY | ||
} | ||
|
||
/** | ||
* Check if a contract is an Unlock contract | ||
* This uses a multi-step approach: | ||
* 1. Check if it's a known Unlock contract address | ||
* 2. If not, check if it's a lock by calling the Unlock contract | ||
*/ | ||
export const isUnlockContract = async ( | ||
contractAddress: string, | ||
networkId: string, | ||
env: Env | ||
): Promise<boolean> => { | ||
if (!contractAddress) return false | ||
|
||
try { | ||
// First, check if it's a known Unlock contract | ||
if (isKnownUnlockContract(contractAddress, networkId)) { | ||
return true | ||
} | ||
|
||
// If not a known Unlock contract, check if it's a lock | ||
return await checkIsLock(contractAddress, networkId, env) | ||
} catch (error) { | ||
console.error('Error checking if contract is Unlock contract:', error) | ||
return false | ||
} | ||
} | ||
|
||
/** | ||
* Performs rate limiting check using Cloudflare's Rate Limiting API | ||
* Returns true if the request should be allowed, false otherwise | ||
*/ | ||
export const checkRateLimit = async ( | ||
request: Request, | ||
method: string, | ||
contractAddress: string | null, | ||
env: Env | ||
): Promise<boolean> => { | ||
// Authenticated Locksmith requests are exempt from rate limiting | ||
if (hasValidLocksmithSecret(request, env)) { | ||
return true | ||
} | ||
|
||
// Get client IP for rate limiting | ||
const ip = getClientIP(request) | ||
|
||
try { | ||
// Create a key that combines IP with contract address or method to provide granular rate limiting | ||
// This is a more stable identifier than just IP alone, as recommended by Cloudflare | ||
const rateKey = contractAddress | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. In our case I think it will be almost exclusively There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. got it! |
||
? `${ip}:${contractAddress.toLowerCase()}` | ||
: `${ip}:${method}` | ||
|
||
// Check standard rate limiter (10 seconds period) | ||
const standardResult = await env.STANDARD_RATE_LIMITER.limit({ | ||
key: rateKey, | ||
}) | ||
if (!standardResult.success) { | ||
return false | ||
} | ||
|
||
// Check hourly rate limiter (60 seconds period) | ||
const hourlyResult = await env.HOURLY_RATE_LIMITER.limit({ key: ip }) | ||
return hourlyResult.success | ||
} catch (error) { | ||
console.error('Error checking rate limit:', error) | ||
// In case of error, allow the request to proceed | ||
// We don't want to block legitimate requests due to rate limiter failures | ||
return true | ||
} | ||
} | ||
|
||
/** | ||
* Extract contract address from RPC method params | ||
* This function supports common RPC methods that interact with contracts | ||
*/ | ||
export const getContractAddress = ( | ||
method: string, | ||
params: any[] | ||
): string | null => { | ||
if (!params || params.length === 0) return null | ||
|
||
try { | ||
// Common RPC methods that interact with contracts directly with 'to' field | ||
if ( | ||
['eth_call', 'eth_estimateGas', 'eth_sendTransaction'].includes(method) | ||
) { | ||
const txParams = params[0] | ||
if (txParams && typeof txParams === 'object' && 'to' in txParams) { | ||
return txParams.to as string | ||
} | ||
} | ||
|
||
// eth_getLogs and eth_getFilterLogs may contain contract address in 'address' field | ||
if (['eth_getLogs', 'eth_getFilterLogs'].includes(method)) { | ||
const filterParams = params[0] | ||
if ( | ||
filterParams && | ||
typeof filterParams === 'object' && | ||
'address' in filterParams | ||
) { | ||
return filterParams.address as string | ||
} | ||
} | ||
|
||
// eth_getCode, eth_getBalance, eth_getTransactionCount, eth_getStorageAt | ||
// These methods have the address as the first parameter | ||
if ( | ||
[ | ||
'eth_getCode', | ||
'eth_getBalance', | ||
'eth_getTransactionCount', | ||
'eth_getStorageAt', | ||
].includes(method) | ||
) { | ||
if (typeof params[0] === 'string') { | ||
return params[0] as string | ||
} | ||
} | ||
|
||
return null | ||
} catch (error) { | ||
console.error( | ||
`Error extracting contract address from method ${method}:`, | ||
error | ||
) | ||
return null | ||
} | ||
} |
This file contains 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
Oops, something went wrong.
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.
💯
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.
Actually, can we log the full body as well? This could be useful to debug more.
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.
(insead of just the ID which is not very useful!)