Type Confusion on Cloudflare
How Type Confusion Manifests in Cloudflare
Type confusion in Cloudflare edge logic typically occurs when a value expected to be one JavaScript/CF-type (e.g., a string or number) is interpreted as another (e.g., an object or function). This can bypass intended access checks or cause runtime exceptions that expose behavior differences. In Cloudflare Workers, common patterns include unsafe deserialization of JSON, misuse of Object.prototype methods, and improper handling of fetch Response bodies where a developer assumes a JSON type but receives a stream or blob.
Attack patterns specific to Cloudflare:
- Overriding built-in prototypes (e.g.,
Object.prototype) in a Worker to customize behavior, which can cause downstream code that iterates overObject.prototypekeys to treat injected properties as legitimate configuration or headers. - Incorrectly assuming a
Response.json()promise resolves to an object with a specific shape, allowing an attacker to supply a non-object (e.g., a string or number) that later triggers logic expecting an object with certain properties (bypassing guard checks that rely on property existence). - Using
JSON.parseon user-controlled input without validating the resulting type, enabling an attacker to supply an array where an object is expected, leading to logic that iterates or indexes the value as if it were an object (property access on an array produces unexpected keys, potentially exposing internal fields or routes).
Concrete example: a Worker that merges request headers into a configuration object without validating types:
addEventListener('fetch', event => {
event.respondWith(handle(event.request));
});
async function handle(request) {
const config = await request.json(); // attacker can send a string or number
if (config.securityEnabled) { // type confusion: if config is a string, this is undefined and may fallback to a dangerous default
enableSecurity();
} else {
disableSecurity();
}
return new Response('ok');
}
In this pattern, if the request body is a JSON string (e.g., "insecure") rather than an object, config.securityEnabled silently evaluates to undefined, which may lead to unintended execution paths. Another Cloudflare-specific scenario involves Workers KV where a key expected to map to a numeric revision is instead stored as a string, causing comparison logic to misbehave and potentially bypass version checks.
Cloudflare-Specific Detection
Detecting type confusion in Cloudflare Workers centers on validating assumptions about data types at boundaries: request.json(), await caches.match(), KV reads, and URL routing parameters. Because middleBrick scans the unauthenticated attack surface in 5–15 seconds, it can surface risky patterns such as unchecked deserialization and missing runtime type guards without credentials.
How to identify with middleBrick:
- Submit the Worker URL to middleBrick. The scan runs 12 checks in parallel and, under LLM/AI Security, includes prompt injection and output analysis; while type confusion is not an LLM issue per se, the scanner checks for unsafe deserialization and missing input validation that commonly coexist with type confusion.
- Review the findings for categories such as Input Validation and Property Authorization. middleBrick provides severity ratings and remediation guidance, helping you prioritize fixing paths where a non-object can reach internal logic.
- Use the CLI to complement the scan:
middlebrick scan https://your-worker.your-subdomain.workers.devreturns JSON output that highlights missing type checks and suggests where to add runtime assertions.
Example JSON output excerpt (simplified):
{
"score": 68,
"grade": "D",
"findings": [
{
"category": "Input Validation",
"severity": "high",
"description": "Untrusted input deserialized via request.json() without type verification",
"remediation": "Validate typeof after parsing or use a schema validator"
}
]
}
In the dashboard, you can track these findings over time and link them to compliance mappings (e.g., OWASP API Top 10:2023 A05:2023 – Security Misconfiguration) to understand risk context.
Cloudflare-Specific Remediation
Remediate type confusion in Cloudflare Workers by enforcing strict type checks at deserialization boundaries and leveraging Cloudflare-native patterns. Avoid relying on truthy/falsy checks for objects; instead, validate structure and type explicitly.
Code fix examples:
1) Validate parsed JSON is an object:
addEventListener('fetch', event => {
event.respondWith(handle(event.request));
});
function isObject(value) {
return value !== null && typeof value === 'object' && !Array.isArray(value);
}
async function handle(request) {
let config;
try {
config = await request.json();
} catch (e) {
return new Response('Invalid JSON', { status: 400 });
}
if (!isObject(config)) {
return new Response('Configuration must be an object', { status: 400 });
}
if (config.securityEnabled === true) { // strict equality avoids type coercion
enableSecurity();
} else {
disableSecurity();
}
return new Response('ok');
}
2) Safe iteration when using values that may be arrays or objects:
async function process(input) {
const data = await input.json();
if (Array.isArray(data)) {
return new Response('Expected an object, got an array', { status: 400 });
}
if (typeof data.metadata?.version !== 'number') {
return new Response('Missing or invalid version', { status: 400 });
}
// safe to use data.metadata.version as a number
return new Response('ok');
}
3) Cloudflare KV with type-safe retrieval:
addEventListener('fetch', event => {
event.respondWith(handle(event.request));
});
async function handle(request) {
const key = 'config';
const value = await MY_KV.get(key, { type: 'json' });
if (value === null) {
return new Response('Not found', { status: 404 });
}
if (typeof value !== 'object' || value === null || Array.isArray(value)) {
return new Response('Invalid stored type', { status: 500 });
}
if (value.enabled) {
// proceed safely
}
return new Response('ok');
}
General guidance: prefer schema validation libraries compatible with Workers (e.g., using zod or io-ts via modules) to enforce types at the edge. Ensure route parameters and KV keys are validated before use, and avoid prototype modifications that can pollute object behavior across modules.
Related CWEs: inputValidation
| CWE ID | Name | Severity |
|---|---|---|
| CWE-20 | Improper Input Validation | HIGH |
| CWE-22 | Path Traversal | HIGH |
| CWE-74 | Injection | CRITICAL |
| CWE-77 | Command Injection | CRITICAL |
| CWE-78 | OS Command Injection | CRITICAL |
| CWE-79 | Cross-site Scripting (XSS) | HIGH |
| CWE-89 | SQL Injection | CRITICAL |
| CWE-90 | LDAP Injection | HIGH |
| CWE-91 | XML Injection | HIGH |
| CWE-94 | Code Injection | CRITICAL |