Repository navigation
Webhooks GraphQL and gRPC Security
Last reviewed: 2026-11-28
Caution
Authorized use only. Forged webhooks, alias batching and reflection probing are for your own services, the local Secure API lab, or a written scope. See LEGAL.md.
Prerequisites: API threat modeling ยท API authorization ยท Rate limiting & resource exhaustion
Cover the three API styles whose risks differ most from plain REST: inbound webhooks (authenticating a third party's call), GraphQL (one endpoint, caller-shaped queries) and gRPC (HTTP/2 with protobuf, channel and call credentials).
- Webhooks: signature and replay checks per GitHub, Stripe and the Standard Webhooks specification.
- GraphQL: limits and introspection controls per the OWASP GraphQL Cheat Sheet, graphql.org and ASVS 5.0.0 V4.3, using graphql-core 3.3.2.
- gRPC: transport and call authentication and reflection per the gRPC authentication and reflection guides.
- Webhook handlers process only authentic, fresh, first-time deliveries.
- GraphQL documents are bounded before execution, and production schemas are not self-describing.
- gRPC servers use TLS, authenticate every call and authorize every method.
- Receiving events from a payment provider, VCS, SaaS or your own services
- Exposing or reviewing a GraphQL API
- Building or reviewing gRPC services and their deployment
| Provider | Signature | Timestamp & replay | Notes |
|---|---|---|---|
| GitHub | X-Hub-Signature-256: sha256=<hex HMAC-SHA256 of the body> |
No signed timestamp. Use the X-GitHub-Delivery GUID to detect replays; GitHub says a redelivery keeps the same value |
"Never use a plain == operator" |
| Stripe |
Stripe-Signature: t=<unix time>,v1=<HMAC-SHA256>; signed payload is t + . + raw body |
Stripe's libraries default to a 5-minute tolerance; deduplicate by event ID | Only v1 is a valid live scheme; ignore others |
| Standard Webhooks |
webhook-signature: v1,<base64 HMAC-SHA256> over msg_id.timestamp.payload; space-separated list for key rotation |
Check webhook-timestamp against a tolerance; use webhook-id as an idempotency key |
Asymmetric v2a (ed25519) replaces the deprecated v1a
|
Common rules from all three sources:
- Verify against the raw request body before parsing JSON. Re-serialized JSON will not match.
- Compare with a constant-time function (
hmac.compare_digestin Python). The Standard Webhooks spec warns that failing to do so can "turn them into signing oracles". - Reject stale timestamps, then remember delivery IDs for longer than the tolerance window.
- Keep secrets per endpoint (Standard Webhooks: "Symmetric signing keys must be unique per endpoint"), store them as secrets, and support two at once during rotation.
- Treat the verified payload as a notification, and check the event type and action before acting. For high-value changes, re-read the object from the provider's API.
This verifier follows the Standard Webhooks v1 scheme and matches the lab's webhook handler. The GitHub function reproduces the test vector published in GitHub's documentation. Both ran as written on Python 3.14.10, together with the tests below:
import base64, hashlib, hmac, time
TOLERANCE = 5 * 60
def verify_standard_webhook(secret: str, headers: dict, body: bytes, seen: dict,
now: float | None = None) -> str:
"""Standard Webhooks v1. Returns the message id, or raises ValueError."""
now = time.time() if now is None else now
msg_id = headers.get("webhook-id", "")
ts = headers.get("webhook-timestamp", "")
if not msg_id or not ts.isdigit() or abs(now - int(ts)) > TOLERANCE:
raise ValueError("missing id or timestamp outside tolerance")
key = base64.b64decode(secret.removeprefix("whsec_"))
signed = f"{msg_id}.{ts}.".encode() + body # the raw, unparsed body
expected = "v1," + base64.b64encode(hmac.new(key, signed, hashlib.sha256).digest()).decode()
candidates = headers.get("webhook-signature", "").split(" ")
if not any(hmac.compare_digest(c.encode(), expected.encode()) for c in candidates if c):
raise ValueError("bad signature")
for k in [k for k, exp in seen.items() if exp < now]:
del seen[k]
if msg_id in seen:
raise ValueError("duplicate delivery")
seen[msg_id] = now + 2 * TOLERANCE
return msg_id
def verify_github(secret: bytes, body: bytes, header: str) -> bool:
expected = "sha256=" + hmac.new(secret, body, hashlib.sha256).hexdigest()
return hmac.compare_digest(expected, header)
# GitHub's published test vector
assert verify_github(b"It's a Secret to Everybody", b"Hello, World!",
"sha256=757107ea0eb2509fc211221cce984b8a37570b6d7586c22c46f4379c8b043e17")import secrets, unittest
class StandardWebhookTest(unittest.TestCase):
def setUp(self):
self.secret = "whsec_" + base64.b64encode(secrets.token_bytes(32)).decode()
self.now = 1_800_000_000
self.body = b'{"type":"invoice.paid"}'
def sign(self, msg_id, ts, body):
key = base64.b64decode(self.secret.removeprefix("whsec_"))
mac = hmac.new(key, f"{msg_id}.{ts}.".encode() + body, hashlib.sha256).digest()
return {"webhook-id": msg_id, "webhook-timestamp": str(ts),
"webhook-signature": "v1," + base64.b64encode(mac).decode()}
def test_valid_then_replay(self):
seen = {}
h = self.sign("msg_1", self.now, self.body)
self.assertEqual("msg_1", verify_standard_webhook(self.secret, h, self.body, seen, self.now))
with self.assertRaisesRegex(ValueError, "duplicate"):
verify_standard_webhook(self.secret, h, self.body, seen, self.now + 1)
def test_stale_timestamp(self):
h = self.sign("msg_2", self.now - 3600, self.body)
with self.assertRaisesRegex(ValueError, "tolerance"):
verify_standard_webhook(self.secret, h, self.body, {}, self.now)
def test_tampered_body(self):
h = self.sign("msg_3", self.now, self.body)
with self.assertRaisesRegex(ValueError, "signature"):
verify_standard_webhook(self.secret, h, self.body + b" ", {}, self.now)The seen dictionary works for one process only, like the lab's replay cache. With several instances, use a shared store with a TTL and an atomic "set if absent".
In the lab, the vulnerable twin compared signatures with == (compare_digest calls: 0), processed a one-hour-old delivery, and processed the same delivery twice. The fixed twin called compare_digest, refused the stale delivery (401), and processed the duplicate once. The constant-time case is instrumented: it counts compare_digest calls and does not measure timing.
| Risk | Control | Source |
|---|---|---|
| Deep or nested queries | Depth limit, with a smaller limit for nested lists | OWASP GraphQL CS; graphql.org; ASVS 4.3.1 |
Alias and array batching (second:droid(...), JSON arrays of queries) |
Limit aliases, top-level fields and queries per batch; no batching for sensitive objects; object-level rate limits in code | OWASP GraphQL CS "Batching Attacks"; graphql.org |
| Expensive queries | Query cost analysis, or a trusted-documents (persisted query) allowlist | ASVS 4.3.1; graphql.org |
| Slow resolvers | Timeouts at the application and infrastructure layers | OWASP GraphQL CS |
| Schema disclosure | Disable introspection "system-wide in any production or publicly accessible environments", unless the API is meant for other parties; disable GraphiQL there | OWASP GraphQL CS; ASVS 4.3.2 |
| Field suggestions ("Did you mean") | Hide suggestions | OWASP GraphQL CS |
| Object access through any resolver | Authorize in each resolver, on both edges and nodes | OWASP GraphQL CS |
The GraphQL specification defines introspection (__schema, __type) but sets no security or cost limits, so the server must add them. graphql.org also notes that disabling introspection is not enough on its own.
graphql-core 3.3.2 has no built-in depth or alias limit. In local testing, the default rules accepted a 7-level query and 50 aliases. It does provide a parser token cap, NoSchemaIntrospectionCustomRule and hide_suggestions. This snippet ran with graphql-core 3.3.2 on Python 3.12.13:
from graphql import (GraphQLError, NoSchemaIntrospectionCustomRule, build_schema,
parse, specified_rules, validate)
schema = build_schema("type Query { me: User } type User { id: ID! friends: [User!]! }")
def check(query: str, max_tokens: int = 1000) -> list[str]:
try:
document = parse(query, max_tokens=max_tokens)
except GraphQLError as exc:
return [exc.message]
rules = [*specified_rules, NoSchemaIntrospectionCustomRule]
return [e.message for e in validate(schema, document, rules, hide_suggestions=True)]
check("{ __schema { types { name } } }")
# ["GraphQL introspection has been disabled, but the requested query contained the field '__schema'.", ...]
check("{ " + " ".join(f"a{i}: me {{ id }}" for i in range(400)) + " }")
# ['Syntax Error: Document contains more than 1000 tokens. Parsing aborted.']
check("{ me { idd } }")
# ["Cannot query field 'idd' on type 'User'."] (no "Did you mean" suggestion)For depth and aliases, the fixed lab adds two custom ValidationRule classes (MaxDepthRule follows fragment spreads; MaxAliasesRule counts aliased fields) in _graphql_rules. It also masks resolver errors as "internal error". In CI, it refused a depth-8 query with "query depth 8 exceeds the limit of 5" and 30 aliases with "30 aliases exceed the limit of 10", and refused __schema. The vulnerable twin executed all three. A token cap and alias limit do not replace per-object rate limits on login or OTP mutations.
The lab has no gRPC service, and gRPC is not part of its CI evidence. The API names below were checked against src/python/grpcio/grpc/__init__.py in the grpc/grpc repository and the gRPC guides. The interceptor was run once locally with grpcio 1.81.2 on Python 3.12.13, over a plaintext test port on 127.0.0.1 only. TLS credentials were not exercised.
The gRPC auth guide lists SSL/TLS (server authentication, with optional client certificates for mutual authentication), ALTS (on Google Compute Engine and GKE), and token-based authentication. It says token credentials "must be used as well as SSL/TLS on the channel" and that most implementations "will not let you send credentials on an unencrypted channel". Credentials come in two kinds, channel credentials and call credentials, and can be combined.
| Need | Python API |
|---|---|
| Server TLS, optionally requiring client certificates | grpc.ssl_server_credentials(private_key_certificate_chain_pairs, root_certificates=None, require_client_auth=False) |
| Client TLS |
grpc.ssl_channel_credentials(...), then grpc.secure_channel(target, credentials)
|
| Bearer token per call | grpc.access_token_call_credentials(access_token) |
| TLS plus token on every call | grpc.composite_channel_credentials(channel_credentials, *call_credentials) |
| Authorize each method on the server | A grpc.ServerInterceptor subclass implementing intercept_service(continuation, handler_call_details)
|
| Refuse with a status |
context.abort(grpc.StatusCode.UNAUTHENTICATED, ...) or PERMISSION_DENIED
|
Do not use grpc.insecure_channel outside local development. The gRPC Python token example uses an interceptor that checks the authorization metadata, then rejects with UNAUTHENTICATED. For real tokens, validate them as in OAuth & OIDC implementation (signature, iss, aud, expiry, scope). Then map handler_call_details.method (for example /pkg.Service/Method) to a rule in your central policy. Unknown methods are denied.
# validate_token(header) -> subject or None, and is_allowed(subject, method) -> bool, are yours.
import grpc
class AuthInterceptor(grpc.ServerInterceptor):
def __init__(self, validate_token, is_allowed):
self.validate_token, self.is_allowed = validate_token, is_allowed
def deny(code, msg):
return grpc.unary_unary_rpc_method_handler(lambda req, ctx: ctx.abort(code, msg))
self.unauthenticated = deny(grpc.StatusCode.UNAUTHENTICATED, "authentication required")
self.forbidden = deny(grpc.StatusCode.PERMISSION_DENIED, "not permitted")
def intercept_service(self, continuation, handler_call_details):
metadata = dict(handler_call_details.invocation_metadata or ())
subject = self.validate_token(metadata.get("authorization", ""))
if subject is None:
return self.unauthenticated
if not self.is_allowed(subject, handler_call_details.method):
return self.forbidden
return continuation(handler_call_details)In the local run, with a policy that allowed /lab.Svc/Get for users and /lab.Svc/Admin for admins only:
| Call | Observed status |
|---|---|
Get with no token |
UNAUTHENTICATED |
Get with a user token |
OK |
Admin with a user token |
PERMISSION_DENIED |
Admin with an admin token |
OK |
| An unregistered method, or the reflection method, with an admin token |
PERMISSION_DENIED (not in the policy, so denied before routing) |
A 4096-byte request with grpc.max_receive_message_length set to 1024 |
RESOURCE_EXHAUSTED |
The deny handlers are unary-unary, which matches the gRPC example. A service with streaming methods needs deny handlers of the matching type.
-
grpc.server(thread_pool, ..., maximum_concurrent_rpcs=N)returnsRESOURCE_EXHAUSTEDabove N concurrent RPCs. The channel argumentgrpc.max_receive_message_lengthcaps inbound message size. Set client deadlines on every call. - Server reflection (
grpc.reflection.v1.ServerReflection) lets tools such asgrpcurllist services. It is enabled explicitly, for example withreflection.enable_server_reflection(SERVICE_NAMES, server)fromgrpc_reflection. The reflection guide says: "If your gRPC API is accessible to public users, you may not want to expose the reflection service". Register it only in development builds or on an internal listener.
| Area | Test | Expected |
|---|---|---|
| Webhook | Valid signature, fresh timestamp | Accepted once |
| Webhook | Same delivery again | Not processed again (acknowledge or refuse, but no side effect) |
| Webhook | Timestamp one hour old, correctly signed | 401 |
| Webhook | One byte of body changed | 401 |
| Webhook | Only an unknown scheme (for example v0 or v1a) present |
401 |
| GraphQL | Depth or alias count over the limit | 400 before execution |
| GraphQL |
__schema or __type in production |
Refused |
| GraphQL | Misspelled field | Error without "Did you mean" |
| GraphQL | Another user's object by ID through any resolver | Denied |
| gRPC | Call over a plaintext channel | Not possible in production config |
| gRPC | Call without, or with an invalid, token | UNAUTHENTICATED |
| gRPC | Valid token, method not allowed for the caller | PERMISSION_DENIED |
| gRPC | Reflection request on a public listener | Fails; reflection is not registered and not in the policy |
| gRPC | Message over the size limit | RESOURCE_EXHAUSTED |
The webhook and GraphQL rows that match lab cases passed in CI run 46241150192. That is evidence for the synthetic teaching code only. The observed gRPC statuses are the ones in the table under the interceptor, from one local run on plaintext loopback, not from CI. The "plaintext channel" and "reflection on a public listener" rows are expected results that were not exercised: TLS was not configured, and reflection was only probed as a method missing from the policy.
- GitHub: validating webhook deliveries ยท GitHub: best practices for webhooks
- Stripe webhooks
- Standard Webhooks specification
- OWASP GraphQL Cheat Sheet ยท graphql.org security ยท GraphQL specification
- gRPC authentication ยท gRPC reflection
- Python
hmac
- README.md - Web Application Security index
-
labs/secure-api/impl/fixed_api.py -
webhook,graphql,_graphql_rules - labs/secure-api/README.md - Lab cases and CI evidence
โฌ ๏ธ Web Application Security index | Master Index | ๐ฏ Role Navigation | Legal Notice
๐ Source: WebAppSecurity/webhooks-graphql-and-grpc.md | โ๏ธ Suggest an edit | โฌ
๏ธ Back to Web App Security
- ๐บ๏ธ Browse by Topic
- ๐ All Repository Files
- ๐งญ Learning Paths
- ๐ Master Guide
- ๐ค Glossary
- โ๏ธ Legal & Disclaimer
๐ Foundations & Learning
๐ก๏ธ Defense & Investigations
- Incident Response
- Open Source Intelligence (OSINT)
- Reverse Engineering
- Operations Security (OPSEC)
- Compliance
โ๏ธ Platforms & Infrastructure
๐ก Hardware, Wireless & Field Projects
- PNWC Cyberdeck
- Hardware Testing
- Hardware Hacking
- Software-Defined Radio
- Wardriving
- uConsole
- Space Security
๐งฐ Assessment & Field Reference
๐ฆ Downloads & Project Resources
๐๏ธ Additional Topics