Skip to content

feat(rate-limit): accept API keys in the URL path - #1742

Merged
MuncleUscles merged 1 commit into
v0.121from
feat/v0.121-path-based-api-key
Aug 18, 2026
Merged

feat(rate-limit): accept API keys in the URL path#1742
MuncleUscles merged 1 commit into
v0.121from
feat/v0.121-path-based-api-key

Conversation

@MuncleUscles

Copy link
Copy Markdown
Member

What

POST /api/{api_key} now routes to the same JSON-RPC handler, so a key can be supplied in the URL as well as via the X-API-Key header.

  • Path wins when both are present; the header still works for server-side callers
  • Only glk_-prefixed segments count as keys — any other segment falls through to anonymous
  • New backend/protocol_rpc/api_key_redaction.py scrubs keys from logs and Sentry

Why

The header-only design makes Studio unusable from most of the EVM toolchain. MetaMask's "Add network" takes a URL and has no header field at all, and the same is true of foundry.toml, --rpc-url, and most viem/ethers setups. Every major provider puts the key in the path for exactly this reason (Alchemy /v2/<key>, Infura /v3/<key>, QuickNode, Ankr).

This is not hypothetical. An integrator we issued a key to said they would have to stand up a backend proxy "for them to be able to use it properly as most of the use comes from testing deployments through metamask". That proxy's entire job would be turning a URL into a header — and a shared proxy is also what pushes a team onto one shared key rather than one key per person, which loses per-user attribution and means one heavy user starves the rest.

Secondary: X-API-Key is not CORS-safelisted, so every browser call currently pays a preflight OPTIONS before the POST. The path form has no preflight.

Testing done

  • 823 unit tests pass (17 new)
  • Verified against the real app object that both /api and /api/{api_key} register, and that /api/explorer/* is not shadowed: POST /api/explorer/stats correctly 405s to the explorer GET route rather than being captured by the path param, and /api/a/b 404s
  • Redaction covers full keys, partial/truncated keys, uvicorn's args-based access line, and nested Sentry payloads (lists, dicts, transaction names)

Decisions made

  • The middleware path gate covers every path the route can match, not only key-shaped ones. A path the route serves but the gate misses would be an unlimited, unauthenticated RPC endpoint. A parametrised test pins that correspondence so the two cannot drift apart.
  • A mistyped key is still treated as a key, so it fails loudly as Invalid API key rather than silently falling back to anonymous limits. Silent downgrade is the exact confusion an earlier user hit ("check the header is actually attached"). A segment that is not key-shaped at all is not an error — it is simply anonymous.
  • The path takes precedence over the header, because it is what the caller typed rather than something an intermediary may have injected.
  • Log and Sentry scrubbing is part of this change, not a follow-up. Keys in URLs get written down where headers are not, and two of those places were ours: access_log=True sends full paths to stdout, and Sentry runs with send_default_pii=True and traces_sample_rate=1.0, so request URLs leave the process on every transaction, not just errors. Shipping path keys without this would have been a downgrade on header-only rather than an improvement.
  • The Sentry hook walks the entire event rather than known fields, because the URL is echoed into request.url, the transaction name, breadcrumbs and span descriptions — missing one defeats the purpose.

Checks

  • I have tested this code
  • I have reviewed my own PR
  • I have created an issue for this PR
  • I have set a descriptive PR title compliant with conventional commits

Reviewing tips

  • _is_rpc_path and the route decorators must stay in lockstep. That is the one place a mistake is dangerous rather than merely wrong.
  • Worth sanity-checking the redaction regex against your own expectations: it deliberately matches glk_ + 4-or-more hex so partial keys are caught too.
  • Keys in URLs still land in logs we do not control — proxies, browser history, Referer. That is the accepted trade every provider makes, and it argues for making key rotation self-serve. Rotation is currently impossible on prod because ADMIN_API_KEY is unset there, which is worth fixing separately.
  • Ordering note: install_log_redaction() runs before sentry_sdk.init, so the filter is in place before anything can log.

User facing release notes

  • API keys can now be passed in the URL — https://studio.genlayer.com/api/<key> — in addition to the X-API-Key header. This makes keyed access work from MetaMask, Foundry, and any other tool that accepts only an RPC URL.

Keys could only be supplied as an X-API-Key header, which makes Studio
unusable from most of the EVM toolchain. MetaMask's "Add network" takes a
URL and has no header field at all; the same is true of foundry.toml,
--rpc-url, and most viem/ethers setups. Every major provider puts the key in
the path for this reason (Alchemy /v2/<key>, Infura /v3/<key>).

This is not hypothetical: an integrator on a shared Studio key told us they
would have to stand up a backend proxy "for them to be able to use it
properly as most of the use comes from testing deployments through
metamask". That proxy's whole job would be turning a URL into a header, and
a shared proxy is also what pushes teams onto one shared key instead of one
key per person.

POST /api/{api_key} now routes to the same JSON-RPC handler, with the header
still accepted for server-side callers. The path wins when both are present,
since it is what the caller typed rather than something an intermediary may
have injected. Only `glk_`-prefixed segments count as keys: any other
segment falls through to anonymous rather than erroring, while a mistyped
real key is still treated as a key so it fails loudly as invalid instead of
silently dropping to anonymous limits.

The middleware's path gate now covers every path the route can match, not
just key-shaped ones. A path served by the route but missed by the gate
would be an unlimited, unauthenticated RPC endpoint, so a test pins that
correspondence.

Keys in URLs get written down in places headers are not, and two of those
were ours: uvicorn access logging is on, and Sentry runs with
send_default_pii and full trace sampling, so request URLs leave the process
on every transaction, not only on errors. api_key_redaction scrubs keys from
both — a logging filter covering uvicorn's args-based access line, and
before_send/before_send_transaction hooks that walk the whole event rather
than known fields. Without this, path keys would be a downgrade on
header-only rather than an improvement.
@coderabbitai

coderabbitai Bot commented Aug 17, 2026

Copy link
Copy Markdown
Contributor

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 5e9f145f-9004-49c9-8ddc-a05d318904f2

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@MuncleUscles

Copy link
Copy Markdown
Member Author

/run-e2e

@sonarqubecloud

Copy link
Copy Markdown

@MuncleUscles

Copy link
Copy Markdown
Member Author

/run-e2e

@MuncleUscles
MuncleUscles merged commit 7d66e42 into v0.121 Aug 18, 2026
17 of 18 checks passed
MuncleUscles added a commit that referenced this pull request Aug 18, 2026
…keys to v0.123 (#1743)

* feat(rate-limit): meter cheap reads separately and expose usage headers (#1741)

Rate limiting was method-agnostic: the middleware checked the quota before
the JSON-RPC body was parsed, so `gen_getContractCode` — a single indexed
read — cost exactly what a write fanning out to LLM validators cost. That
forces the limits to be sized for the expensive case, which starves the
cheap read traffic that batch tooling generates.

Reads that never enter the GenVM now meter into their own bucket at
RATE_LIMIT_READ_MULTIPLIER (default 10x) of the tier limits. The standard
bucket keeps its key shape and numbers, so limits in flight at deploy time
carry over rather than resetting.

The allowlist is maintained by hand and deliberately conservative. Two
methods that read like lookups are excluded because they build a Node backed
by a GenVMManager (gen_getContractSchema, gen_getContractSchemaForCode), and
eth_call is excluded for the same reason despite appearing in the
DISABLE_INFO_LOGS_ENDPOINTS env list that otherwise looks like the natural
source for this. Anything ambiguous — unparseable, oversized, or a batch with
one expensive member — is charged to the stricter bucket.

Responses now carry X-RateLimit-Limit/Remaining/Reset/Window/Bucket for the
window closest to exhaustion, so clients can pace themselves instead of
discovering the ceiling by hitting it. Reset is the time until the oldest
entry ages out, which is the honest answer for a sliding window. These are
listed in the CORS expose_headers, without which browsers hide them from JS.

Finally, gen_getContractCode no longer loads the whole contract state to read
one slot out of it. ContractSnapshot pulls the entire `data` JSONB — every
storage slot the contract owns — which for a contract holding a large vector
store is a substantial fetch and deserialize on a call that batch tooling
polls hard. The slot is now extracted in SQL. Postgres still detoasts the
JSONB server-side, so this narrows transfer and parse cost rather than
eliminating the read; legacy and undeployed row shapes defer to the original
path to keep their error semantics intact.

The Lua script gains a test that actually executes it under a stubbed
redis.call. It was previously covered only through mocked evalsha, so an
error in the script body would have surfaced first in production, on every
/api request.

* feat(rate-limit): accept API keys in the URL path (#1742)

Keys could only be supplied as an X-API-Key header, which makes Studio
unusable from most of the EVM toolchain. MetaMask's "Add network" takes a
URL and has no header field at all; the same is true of foundry.toml,
--rpc-url, and most viem/ethers setups. Every major provider puts the key in
the path for this reason (Alchemy /v2/<key>, Infura /v3/<key>).

This is not hypothetical: an integrator on a shared Studio key told us they
would have to stand up a backend proxy "for them to be able to use it
properly as most of the use comes from testing deployments through
metamask". That proxy's whole job would be turning a URL into a header, and
a shared proxy is also what pushes teams onto one shared key instead of one
key per person.

POST /api/{api_key} now routes to the same JSON-RPC handler, with the header
still accepted for server-side callers. The path wins when both are present,
since it is what the caller typed rather than something an intermediary may
have injected. Only `glk_`-prefixed segments count as keys: any other
segment falls through to anonymous rather than erroring, while a mistyped
real key is still treated as a key so it fails loudly as invalid instead of
silently dropping to anonymous limits.

The middleware's path gate now covers every path the route can match, not
just key-shaped ones. A path served by the route but missed by the gate
would be an unlimited, unauthenticated RPC endpoint, so a test pins that
correspondence.

Keys in URLs get written down in places headers are not, and two of those
were ours: uvicorn access logging is on, and Sentry runs with
send_default_pii and full trace sampling, so request URLs leave the process
on every transaction, not only on errors. api_key_redaction scrubs keys from
both — a logging filter covering uvicorn's args-based access line, and
before_send/before_send_transaction hooks that walk the whole event rather
than known fields. Without this, path keys would be a downgrade on
header-only rather than an improvement.

* feat(rate-limit): classify the v0.123-only RPC methods

The ported allowlist predates three methods that exist only on this branch.

sim_getFeeConfig and gen_getTransactionStatusDetails are cheap reads — a
config lookup and a transactions_processor read respectively, neither
touching the GenVM.

sim_estimateTransactionFees is not. It takes validators_manager and
genvm_manager and runs the contract through sim_call to measure fees, so it
costs a full execution. Worth flagging because eth_estimateGas *is*
allowlisted — that one returns a hardcoded constant. The names are nearly
identical and the costs are not, which is the same shape of trap as eth_call
and the two schema methods already documented here.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant