All notes

A Fetch Proxy Needs an SSRF Boundary

Constrain the requested capability, every redirect and the resources spent reading a response.

English edition, edited for length. Read the complete Chinese original.

The image proxy accepts ?url=... and then directly calls fetch. This allows the user to simply compress images, but the interface gains the ability to access any address without the server. The SSRF risk comes from granting request permissions to user input, not from whether the URL is correctly formatted.

This article discusses obtaining and deploying server-side URLs, specifically within a Worker or other server environment. While edge deployments present different network constraints compared to traditional internal networks, this does not automatically imply that any proxy is inherently secure. It is still possible to access trusted services, leak responses, or consume resources.

Limiting Retrieval Capabilities to a Single, Understandable Business Task

Assuming the product only needs to retrieve the cover image from its own CDN, and accepts image identifiers, the server generates a fixed source path, and does not accept any URLs. The user specifies which image to retrieve, and the application decides where to obtain it. This is a narrower capability than a general URL proxy. Only introduce source addresses when absolutely necessary, and clearly document the purpose, responsible party, and revocation method for each source type. Removing unnecessary capabilities is often simpler than maintaining a comprehensive and secure classification of internet addresses.

This allows a host to still have dangerous paths, such as open proxies that can forward requests or management interfaces with side effects. In addition to the allowed list, it’s necessary to restrict paths and parameters, and to enforce read-only access that aligns with the business requirements. HTTPS ensures data transmission encryption, but does not guarantee the trustworthiness of the server or the correctness of the resource type. There are four different checks: URL format, source trust, path permissions, and response eligibility.

The fact that a Worker is not on the traditional internal network does not mean that there are no risks. Proxies can consume account quotas, access protected services, or attribute external content to the site’s own source. Deploying runtime network restrictions will affect the threat model, but it cannot determine which sources are allowed by the application. The documentation describes the platform’s capabilities, but the application still needs to control the permissions it grants to incoming requests.

A smaller, more restricted whitelist is easier to audit.

const allowed = new Set(['images.example.com']);
function validateSource(value) {
  const url = new URL(value);
  if (url.protocol !== 'https:' || !allowed.has(url.hostname)) {
    throw new Error('Unsupported source');
  }
  if (url.username || url.password || url.port) {
    throw new Error('Unsupported URL authority');
  }
  return url;
}

Example: Using precise hostnames, while rejecting user-provided information and non-default ports that remain after parsing. Standard URL parsing would normalize the explicit HTTPS :443 protocol to an empty port; the example would accept this. If the policy also requires rejecting this raw format, it needs to be designed separately and cannot be derived from url.port. Real-world products may have other rules, but do not use hostname.endsWith('example.com') without a domain name boundary, as similar suffixes could be mistakenly allowed.

Prioritize allowing businesses to explicitly specify their trusted sources, rather than maintaining a perpetually incomplete and unreliable blacklist of dangerous IP addresses. If support for any public source is required, DNS resolution, IP categorization, re-binding, and platform-specific parsing will increase complexity and require dedicated design; this simplified example should not be reused.

Use a standard URL parser to obtain the protocol, hostname, port, and path, and then validate the results without string containment checks. After verification, request the same parsing object without further decoding or concatenation before sending, otherwise the actual destination may be different. User information, abnormal ports, and unnecessary fragments can be explicitly rejected. Hostname comparison is based on the normalized result. If domain name suffix matching is necessary, it must have a label boundary and specify the subdomain control range.

Supporting connections from any public network source is significantly more complex than using a fixed CDN. DNS resolution may return multiple addresses, and redirects or re-resolutions can alter the results. Simply blocking a few IP addresses cannot prevent re-binding. Network egress and application validation must be coordinated. Choosing a mature service and a reliable resolution strategy is essential. You cannot simply copy a regular expression and claim to have complete protection. You must also verify whether connections to certain types of addresses are allowed at runtime. Security conclusions should be limited to the actual deployment scope.

If the vendor’s host is subsequently reassigned or reconfigured, the fixed whitelist will also lose its original trust assumptions. Regularly verify ownership and path behavior, and revoke if necessary. The whitelist is not a permanent certificate of trust. When dealing with publicly accessible image sources, pay particular attention to whether the tracking parameters and signature URLs contain secrets. Logs should only store necessary host and resource classifications, without duplicating complete token queries.

Redirection requires re-validation

It is possible for a domain to be redirected to an address that is not allowed. Automatic redirection will bypass the initial check. Manual redirection can be used, where the Location is re-parsed and validated at each step, and the number of redirects is limited. The Location header should be relative to the current URL and should not be constructed using string concatenation.

Do not send the original authentication headers or cookies to the new target. The proxy request headers should be based on a whitelist, and all headers from the browser requests should not be forwarded directly. Even if the target still allows it, the business credentials must be bound to a specific upstream.

When handling a Location manually, the current URL is used to resolve the relative destination, applying the same source, protocol, and path rules. This limits the total number of hops and the total duration. It’s important to avoid assigning a new, full timeout to each hop, which would allow long chains to indefinitely extend their waiting time. Circular jumps must be recognized, and missing or invalid Locations should be handled with controlled error handling. Finally, the 200 response also requires type and size validation.

The request header should only contain fields that are essential for the business, and should not include browser cookies, Authorization headers, or the Host header. If a specific CDN requires service credentials, these credentials should be bound to the specific source and should not be inherited when switching to another source. A CDN claiming to require a specific header does not constitute authorization. The response header should also be filtered, and Set-Cookie headers and any CORS headers should not be unconditionally granted to proxy interfaces.

When DNS and source verification cannot be fully guaranteed by application code, restricting access to trusted, fixed sources is a reasonable product constraint, preventing compatibility with arbitrary websites that might gradually relax security. Failure messages indicate that the source is not trusted, rather than leaking internal network addresses or complete responses to the user. Input validation errors and upstream network anomalies are recorded separately, helping to distinguish between user errors, attacks, and vendor failures.

Size, Time, and Type: All are Boundaries

Configure the overall timeout, maximum response size, and allowed media types. The Content-Length header may be missing or unreliable, so it’s important to also limit the actual number of bytes read during streaming. You should not rely solely on file extensions, as the .png address could return HTML or large amounts of data.

The image conversion process also needs to prevent resource bloat after decoding, and the fact that a compressed file is small does not necessarily mean that the number of pixels is small. Mature conversion services have related limitations, but applications still need to limit request parameters to prevent attackers from creating a large number of variations and incurring high processing costs.

When the Content-Length is missing, restrictions cannot be relaxed. During the read process, the actual number of bytes is accumulated, and when the limit is reached, the upstream connection is terminated, and a controlled error is returned. The length in the header can be used to proactively reject, but it is still necessary to verify the actual transmission. Image file compression uses small bytes, but may declare large pixels or a large number of frames. The converter needs an independent decoding budget. The upper limit of the response body, pixel limit, conversion parameters, and concurrency limit jointly constrain the cost.

Timeout overrides the response headers and body, and the client attempts to stop unnecessary fetches. Cache writes only accept content that has been fully validated, and do not inject any external bytes into the shared object before completion. For formats that require full validation first, it may be necessary to temporarily store the data; this is the cost of ensuring correctness. Do not prematurely expose untrusted content in pursuit of the lowest possible latency.

Rate limiting is based on authenticated users or controlled anonymous budgets, not just on easily changing query fields. The conversion width uses a limited set, rejecting or normalizing unknown values to avoid creating single, temporary objects. The cache key records the verified source and conversion version, but does not store the complete secret URL for long-term logging. Resource proxies need to control both request and consumption permissions simultaneously.

Content returned should not inherit permissions from upstream execution

The proxy image should use a controlled Content-Type and appropriate content sniffing restrictions. If the original HTML is proxied and served from the same origin as this site, it may allow third-party content to execute scripts in the site’s environment. Downloading files, images, and web pages are different products and should not use the same forwarding interface.

The cache key should include verified source and transformation parameters, while also limiting the parameter set. Rate limiting, quotas, and authorization can control abuse, but cannot replace source verification. Essential parts of logging that avoid including sensitive query tokens from URLs.

The acceptance criteria include allowing for source, similar domain, redirection to disabled sources, anomalous protocols, large responses, slow streams, and error types. A failed check should not reveal sensitive upstream content. A secure proxy must be able to explain why a request’s permissions are restricted, rather than simply demonstrating that the fetch function can successfully execute.

The agent obtained valid bytes, but this does not mean that these bytes are suitable for display on this site. The image service occasionally returns erroneous HTML, which can be forwarded directly and allow the browser to execute potentially malicious code. Explicitly supporting media types and content handling, while using controlled downloads or relying on trusted third-party sources to handle complex files. nosniff is a supplement, but correct Content-Type and secure content boundaries remain essential.

The upstream header uses an allowlist and does not inherit arbitrary Set-Cookie, redirection, or script policies. If only images are provided, the HTML response should reject the request rather than redirect to another site; if downloads are provided, the filenames and disposition are handled securely; if web previews are provided, a dedicated design isolation is required. The three product capabilities have different permissions and do not create a universal byte proxy for code reuse.

The cache only stores objects that have successfully passed source and response checks. Private content accessed via identity requests or signatures is not shared publicly. When a temporary token is present in the source URL, the key and logs can become credential storage points, and it is important to avoid exposing this information and limit storage. Public images may also raise copyright and user privacy concerns. Secure access does not guarantee permanent hosting. Authorization, licensing, and execution security must be evaluated separately.

The error response doesn’t necessarily need to include the complete upstream address. Users can understand that the source is unsupported, the resource is too large, or the request failed temporarily. Maintainers can view controlled diagnostics by associating with the ID. Private queries in the URL should be cleared first, then logged. Avoid automatically including the complete Request object in the exception stack, which can leak sensitive information in the error handling process.

Assess the proxy fees and actual reuse rates to determine if there is any abuse or over-usage. After rate limiting, provide a controlled state without continuous scraping before rejecting the user. Resource budgets are checked both before initiating requests and during stream reading, which can reduce unnecessary work. The whitelist and budget work together; a trusted source can still provide significant resources, while a low-cost source may provide insecure content.

How to Narrow Down a Cover Acquisition Task to Resource Identity

The site only allows authors to select cover images from their own CDN, and can receive asset IDs, which are then mapped to approved paths by the server. Input fields do not support protocols, hostnames, or ports, and cannot include any query parameters. The conversion width is limited to a specific set of uses, and authors can choose either the main text or a thumbnail, rather than requesting a specific number of pixels. By expressing the requirements in terms of resource identity and purpose, the proxy does not need to make the complex commitment of “securely requesting the entire internet.”

If the collaborating party’s source is permitted, configure the fixed host, path prefix, and allowed parameters according to the vendor’s specifications. The path prefix should be segmented to avoid allowing interfaces like /images and /images-proxy simultaneously. The signature parameters are obtained from the server or generated according to the vendor’s agreement, and are not directly transmitted to the browser token. After the parsing object is validated, it is directly used in the request. Subsequent decoding or concatenation is not performed, ensuring the actual destination remains unchanged.

When adding a feature to preview arbitrary URLs to a product, it should be re-evaluated, rather than simply reusing the existing cover proxy with an added parameter. Previewing web pages requires handling HTML, scripts, source isolation, and other network targets, all with different levels of trust. Keeping the interface’s purpose limited allows maintainers to clearly see which new requirement actually expands the attack surface, and prevents a generic helper from quietly merging different product capabilities.

Redirection chains also fall under the same authorization task.

A trusted CDN returns relative location information. It first resolves the current location and then verifies the new source, path, and parameters. Each hop shares the same total timeout and hop budget, and cannot re-obtain the full waiting window. When the target changes, the original source credentials are not carried over; instead, only the approved read headers are sent by default. Even if the new host is on the list, the service token should still be bound to a specific vendor and purpose, rather than following any license source.

Return a clear error message when encountering a loop, missing location, or unsupported state, rather than directly passing the upstream redirection to the browser for validation. The final “200” simply indicates that a response was successfully received, and additional information such as media type and byte size, along with decoding budget, are still required. The upstream may return a login page or error HTML, and should not be granted execution permissions solely based on the source’s trustworthiness. Each stage of the chain must adhere to the same eligibility rules.

The test provides a mechanism to allow access to specific scenarios, including:

  • Accessing allowed same-origin graphs
  • Blocking by hostname
  • Handling exceptions for ports
  • Detecting circular dependencies

The test verifies that the intended target is not accessible, and that the client does not receive an error. By using a synthetic server instead of a real internal management address, the test avoids actively interacting with sensitive services. The security validation should collect evidence of behavior to demonstrate the presence of risk, without expanding the network risk.

DNS checks cannot be performed in isolation from the actual network environment.

When supporting arbitrary public URLs, an application might initially resolve a public address and then, in a subsequent fetch, resolve to a different target. Treating a single DNS result as permanent authorization prevents automatic duplicate binding. Multiple address records, IPv6, redirects, and caching all introduce complexity. Choose a mature solution that allows you to explicitly control the verification and connection relationships, and mitigate risks by implementing exit restrictions. Don’t claim complete functionality simply by writing a few IP string checks.

The edge platform has its own prohibited targets and network semantics, ensuring that current documents are properly secured. The platform’s restrictions can reduce traditional internal network risks without limiting the number of accounts, third-party response permissions, or trusted services available to the site. The threat model should specify the deployment environment and avoid assuming that “Workers do not have access to the traditional internal network” automatically implies a security vulnerability. Products with fixed sources can avoid many complexities and should not be prematurely opened up for potential future needs.

The source of ownership can also change. When a supplier revokes a domain or subdomain and transfers it to another customer, the list continues to reflect the current trust. The registered owner and purpose, along with the revocation of the source and related caches, should be updated. The allowed list reflects the current approval, not permanent trust. Security maintenance includes both input validation and resource relationship lifecycle management.

Execute Hard Budget Instead of Just Looking at Statement Headers During Reading

Content-Length can be used to proactively reject excessively large resources, but a missing or incorrect declaration will not allow for unbounded reading. Actual bytes are accumulated, and the upstream source is removed when the limit is exceeded. Error responses do not interfere with already started image or download streams. When complete format validation is required, the data is temporarily stored within the controlled limit, and then a decision is made whether to make it publicly available. Prioritizing early output should not compromise the security of the returned content.

The decoding budget is independent of the number of compressed bytes. Large sizes, multiple frames, and complex formats can consume significant resources, even if the resulting file is small. Mature converters need to have limitations on pixel count, frame rate, and processing time. The output size can also be large, and it’s important to consider the trade-offs between width, quality, and cost. The cache only stores the results of all successful validations and does not store unvalidated upstream bytes for later checking.

Total consumption of the concurrency budget control account, performing one operation per request. Trusted sources may also be slow, and a large number of legitimate requests can exhaust connections and incur costs. Rate limiting should be performed before initiating expensive operations, with a continuous upper limit still in place during data retrieval. Whether to continue caching after a client cancels is a clear choice, and all failed requests are not left to run indefinitely in the background. Monitor aggregated metrics, duration, and limits, without recording complete URL signatures.

The Source of Return Determines What Capabilities the Third Party Gains

If a legitimate source returns HTML, and the proxy provides it exactly as it came from the original source, the browser may grant it greater same-origin capabilities than the original source. Fixed media types and “nosniff” can provide additional protection, but require actual format validation and cannot be used to arbitrarily rename any HTML as “image/png.” File downloads, image display, and web previews each have their own strategies. Complex, untrusted content typically requires independent sources or controlled downloads.

The following elements are not unconditionally inherited: Set-Cookie, authentication headers, and diagnostic headers. Download filenames are securely generated and do not reveal control characters or private paths. Resource identities in cache keys may include access tokens, and storage and logging should be minimized and protected. Public caches should not store private signed resources. Successful retrieval does not grant permanent hosting licenses, and copyright and user information policies must be independently confirmed.

Complete Text of Failure Report Not Being Sent Upstream

Public errors only indicate unsupported sources, excessive resources, or temporary retrieval failures, and provide associated IDs. Internal events use controlled source categories and stages to avoid generating a complete Request output from generic exception serialization. Test secrets are placed separately in the query, request header, and upstream error body to ensure that failures are handled without re-exposing them. Valid samples must remain available, and complete rejection is not a successful business outcome. For an authorization source, limited functionality, and restricted return capabilities to be in place, the task is considered successfully completed.

The test servers return valid images, HTML, incorrect lengths, infinite slow streams, excessively large text, and redirects to disabled sources. Each sample is pre-configured to reject requests, ensuring that unauthorized targets are not accessed and that private headers are not forwarded. Do not use real internal management services for testing; synthetic, observable endpoints are sufficient to demonstrate request behavior. Error responses do not include upstream text or internal addresses.

Another often overlooked authorization point is cache hits. If you first check the cache using the URL submitted by the user and then return the cached result directly, the old object, which is no longer authorized after being revoked, might bypass the new policy. To test this, first cache an approved resource and then revoke its source. Repeat the same request. The expected behavior is to re-evaluate the current eligibility before returning the bytes. The cache only avoids redundant retrieval; it does not grant permanent access. The policy version and revocation process should clearly handle the old object.

References: OWASP SSRF, Workers fetch.