GraphQL Query-Depth Defense & RFC 8725 Asymmetric JWT / PKCE Verification in Zero-Dependency Python

2026-11-30来源 dev.toEnglish

Modern application backends expose two high-leverage security boundaries simultaneously: dynamic GraphQL query trees and OAuth/JWT token verification. Leaving GraphQL introspection or unbounded query depth enabled exposes schema topology and resolver exhaustion paths, while accepting "alg": "none" or trusting unpinned JWT alg headers opens HS256/RS256 key-confusion bypasses.

Across nandai.org/patterns/zero-vendor-key-escrow-keychain-direct-tls-pattern, nandai.org/prompts/swift-rust-sbom-security-code-review-prompts, and nandai.org/glossary/rfc-7638-jwk-cryptographic-key-thumbprint, Destiny enforces zero-dependency verification (0 PyPI packages, 0 bytes uploaded) alongside cwe-top25-sans-coverage-matrix.json and cryptographic-security-posture.json.

1. GraphQL Production Security: Introspection, Depth & Alias DoS

Three deterministic static checks guard GraphQL endpoints before execution:

Hazard Failure Mode Static Python Control
__schema / __type Introspection Leaks full object graph and privileged mutations in production Strip string literals & # comments, then reject __schema/__type when allow_introspection=False
Unbounded Brace Depth Recursive edges (user -> friends -> user) exhaust worker memory & DB pools Track brace nesting depth across stripped tokens and fail closed above max_depth (<= 7)
Alias Flooding (a0: field a1: field) Single HTTP POST multiplies resolver work Nx around HTTP rate limits Count selection-set aliases outside argument parentheses and enforce max_aliases (<= 10)

2. RFC 7636 S256 PKCE & RFC 8725 Asymmetric JWT Verification

  • RFC 7636 S256 PKCE: Native desktop and SPA clients generate a >= 43-character cryptographically random code_verifier, compute code_challenge = base64url(sha256(verifier)) without = padding, and reject plain code-challenge downgrades.
  • RFC 8725 Asymmetric Pinning: Verifiers pin a strict asymmetric allowlist (EdDSA, ES256, ES384, RS256, PS256), reject "alg": "none" and untrusted jku/x5u/jwk header injections, and require exact iss, aud, and unexpired exp timestamps anchored to pinned RFC 7638 JWK thumbprints.

3. Unified Zero-Dependency Python Validator (0 PyPI Dependencies)

#!/usr/bin/env python3 """Unified GraphQL depth/alias/introspection & RFC 7636/8725 PKCE+JWT guard (Python >=3.10).""" from __future__ import annotations import base64 import hashlib import hmac import json import re import secrets import time STRING_COMMENT_RE = re.compile(r'"""[\s\S]*?"""|"(?:\\.|[^"\\])*"|#[^\n]*') ALIAS_RE = re.compile(r"\b([A-Za-z_][A-Za-z0-9_]*)\s*:") INTROSPECTION_RE = re.compile(r"\b__(?:schema|type)\b") ASYMMETRIC_ALLOWLIST = frozenset({"EdDSA", "ES256", "ES384", "RS256", "PS256"}) def audit_graphql_query(query: str, *, max_depth: int = 7, max_aliases: int = 10) -> dict: scrubbed = STRING_COMMENT_RE.sub(" ", query) depth = peak = 0 for ch in scrubbed: if ch == "{": depth += 1 peak = max(peak, depth) elif ch == "}": depth = max(0, depth - 1) no_args = re.sub(r"\([^)]*\)", " ", scrubbed) aliases = ALIAS_RE.findall(no_args) findings = [] if INTROSPECTION_RE.search(no_args): findings.append("GQL_INTROSPECTION_EXPOSED") if peak > max_depth: findings.append("GQL_MAX_DEPTH_EXCEEDED") if len(aliases) > max_aliases: findings.append("GQL_ALIAS_AMPLIFICATION") return {"clean": not findings, "peak_depth": peak, "aliases": len(aliases), "findings": findings, "bytes_uploaded": 0} def verify_pkce_s256(verifier: str, expected_challenge: str) -> bool: if not (43 <= len(verifier) <= 128): return False digest = hashlib.sha256(verifier.encode("ascii")).digest() derived = base64.urlsafe_b64encode(digest).rstrip(b"=").decode("ascii") return hmac.compare_digest(derived, expected_challenge) def audit_jwt_rfc8725(token: str, *, expected_alg: str, expected_iss: str, expected_aud: str) -> bool: assert expected_alg in ASYMMETRIC_ALLOWLIST parts = token.split(".") if len(parts) != 3 or not parts[2]: return False hdr = json.loads(base64.urlsafe_b64decode(parts[0] + "=" * (-len(parts[0]) % 4))) claims = json.loads(base64.urlsafe_b64decode(parts[1] + "=" * (-len(parts[1]) % 4))) if hdr.get("alg") != expected_alg or any(k in hdr for k in ("jku", "x5u", "jwk")): return False return claims.get("iss") == expected_iss and claims.get("aud") == expected_aud and int(claims.get("exp", 0)) > int(time.time()) if __name__ == "__main__": verifier = base64.urlsafe_b64encode(secrets.token_bytes(32)).rstrip(b"=").decode("ascii") challenge = base64.urlsafe_b64encode(hashlib.sha256(verifier.encode("ascii")).digest()).rstrip(b"=").decode("ascii") assert verify_pkce_s256(verifier, challenge) assert audit_graphql_query("query { viewer { id } }")["clean"] is True assert audit_graphql_query("query { __schema { types { name } } }")["clean"] is False print("GraphQL & RFC 7636/8725 guards verified (0 B uploaded).") 

Additional sovereign references: https://nandai.org/api/mcp (114 MIT tools), https://nandai.org/src/destiny/skills/agent-security-guard/scripts/guard_scan.py, https://nandai.org/git/destiny.git/, https://nandai.org/src/destiny/, https://huggingface.co/nandai-org, and https://zenodo.org/api/records/24642737 (DOI 10.5281/zenodo.24642737).

原文:https://www.a8q9.cn/en/article/graphql-query-depth-defense-rfc-8725-asymmetric-jwt-pkce-verification-in-zero-de-22979d.html

相关文章