The client downloaded half of the PDF and, when retrying, included “Range: bytes=1000-”. If the proxy ignores the request but still returns a 206 status code and sends the entire file, the client may retrieve corrupted content. The status code, range, and body of the response must be strictly consistent.
This document applies to stable, publicly accessible files. When dealing with dynamically generated content or files accessed based on user authorization, version consistency and access permissions must also be considered. It is not possible to first return a portion of the file and then determine if the user has the necessary permissions to access it.
First, establish the file identity, then decide on the transfer method.
Assume the client has stored the previous 1000 bytes of version A. When reconnecting, the same path has been overwritten by version B. A range request without a version prefix might return the remaining bytes of version B, resulting in an invalid concatenated file. The range only indicates the location, not which version the location belongs to. Reliable resumption requires consistent file identity, a verifier, and corresponding byte ranges. Content hash paths can ensure consistent identity, but access permissions are still independently checked.
For dynamically generated PDFs, the generation time, font, and data may change, resulting in different byte sequences. Even if the visual appearance is the same, this does not guarantee that resuming from a specific point will work. One option is to first generate a fixed file and save a version, then allow for range downloads. Alternatively, if range downloads are not supported, the complete current file should be returned. Avoid creating undefined version semantics solely for the purpose of displaying the Accept-Ranges header. The primary goal is to ensure correct downloads, and supporting resuming is an optimization built upon this foundation.
Authorization checks occur before any byte is sent, including requests with ranges and conditions. Just because a user has previously downloaded some files does not mean they still have permission; after a signature URL expires or an account is revoked, access rules must be followed, and the remaining content should not be provided simply because the client holds an ETag. Resource validation and authorization are distinct requirements that must be met separately.
206: A Clear Commitment
GET /manual.pdf
Range: bytes=1000-1999
HTTP/1.1 206 Partial Content
Content-Range: bytes 1000-1999/5000
Content-Length: 1000
Here, the byte endpoint represents a range, so the length is 1000. If the range cannot be satisfied, the server can return a 416 status code and provide a Content-Range header indicating the current length. The server can also choose not to support ranges and return a complete 200 status code, but it cannot do so by using error status codes or length information to falsely indicate support.
Requests covering multiple ranges require the multipart format, which is more complex than single-range requests. Avoid using string slicing to handle all cases. It’s best to rely on a mature storage solution or platform service to handle this. If you implement it yourself, clearly specify which formats you support, and ensure that you respond to other inputs according to the relevant standards.
A single range can specify a start and end position, a range from start to end, or the last N bytes. The numbers in a suffix range represent the length, not a negative index string; an open-ended range requires a specified length; when the endpoint exceeds the length, it should be handled according to the rules, rather than arbitrarily truncating and keeping the original header. The number parsing should also prevent overflow and invalid formats, and should not allow large values to trigger excessive allocation.
Invalid syntax, syntactically correct but unsatisfiable requests, and requests that violate a specific range capability are all different scenarios. A server can choose to ignore the range specification and provide a complete representation according to the protocol, but the state must still match the request. When a custom implementation does not support multiple ranges, it cannot silently discard the part after the comma and then claim that the entire request has been satisfied. Mature HTTP storage services can handle these semantic nuances, and applications only need to explicitly forward and handle the permission boundaries.
There is also a risk of resource amplification across multiple ranges. Requesting large numbers of small fragments could increase multipart overhead and processing costs. The service should have limitations that comply with the protocol and platform capabilities. These limitations are intended to protect resources, not to arbitrarily generate incorrect values. The tests include a large number of ranges, overlapping ranges, and anomalous numbers, and confirm that the rejection or rollback behavior is stable.
Text characters are not file bytes.
JavaScript string lengths and slicing are based on character encoding, and cannot be directly treated as HTTP byte ranges. Issues arise immediately when dealing with Chinese characters, emojis, or compressed data. Files should be handled as binary streams or byte arrays, and lengths and ranges should be calculated based on the chosen representation.
The compression further affects the representation. When compressing the same file, the byte positions will differ from the uncompressed version. When rewriting the content in the intermediate layer, the old Content-Range, Content-Length, and strong entity tags cannot be maintained. There needs to be a clear choice between streaming transcoding or cleaning and resuming from a specific point.
Assume the original server provides gzip files, and the client decompresses them to return the plaintext. If the byte ranges no longer correspond to the returned representation, the client will still concatenate based on the error offset if Content-Range is still forwarded. To handle content conversion, it’s necessary to explicitly determine whether to disable range capabilities, recalculate the range, or delegate to an upstream server that supports this representation. Even if only a single line of comments is added, it’s impossible to directly retain the original validator and length.
The “Worker fetch” and the “hosting layer” may have automatic encoding handling. To determine the specific stream received, you need to consult the runtime rules and perform actual testing. The two steps are: 1) verifying the original bytes and 2) decoding the resulting text. Do not infer the length of the transmitted data based on the output of curl after automatic decompression. The tool options may hide compression behavior, and the report should record the request and response encoding headers. Only when the selected encoding is explicitly defined and the range is specified, does it have meaning.
For large binary files, directly leveraging the range capabilities of a mature object storage solution is often more resource-efficient than reading the entire file in chunks. While reading the entire content and then slicing can return the correct bytes, it doesn’t address the memory and bandwidth costs. If the application only handles authorization, it can generate a controlled download path after verification, or forward based on platform support. However, the authorization URL should not be open to any source, otherwise, the file proxy will also be vulnerable to SSRF (Server-Side Request Forgery).
Preventing Version-Specific String Concatenation with if-range
Clients can use ETag or date as validation criteria to retrieve only the relevant parts of the content when the version is still consistent. If the resource has changed, the server returns the complete new representation, preventing the client from combining the first half of the old file with the second half of the new file.
If the file URL frequently contains overlapping content, a strong version identifier is particularly important. Using content hashes or explicit version paths can simplify download consistency. When dealing with authorized URLs, it’s also crucial to consider whether the expiration time is sufficient to allow retries, and to avoid misinterpreting a 403 error as a range issue due to a failed signature.
The goal when an If-Range doesn’t match is to allow the client to retrieve the complete current file, rather than returning a business error and continuing to attempt to piece it together. Strong validators and their date-related conditions should adhere to established standards, while weak tags should not be used arbitrarily to make byte consistency judgments for resuming transfers. If the platform already has mature handling, avoid using simple string equality to cover it in the proxy.
The verification process must still be applied to the currently selected representation. Different language files, different encodings, and user-specific watermarks can result in different byte sequences. The same path does not necessarily represent the same object. If the watermark file generates random content each time, it is best to use a clear version and private caching strategy, or disable the range. A strong ETag should not be created using the username or filename, and the version identifier should reflect the actual output.
The continuation client also needs to verify that the server has returned a 206 status code and the correct starting point. If the server returns a complete 200 status code, the old file should be replaced, and no further appending should occur. If a 200 status code is not returned, the length change should be handled. An incorrect response should not be saved as the remaining file. The correct protocol between the server and the client must work together, and any error on either side can damage the final file. The final summary must cover the entire result.
Understanding Key Concepts in Caching
Cache 206 has specific rules: handwritten cache layers should not place partial content under the full file key. When the next user requests the full file, they should not receive the previous fragment. If you do not intend to implement full-range caching semantics, it is safer to directly pass the request to the upstream or skip the manual caching.
When a worker forwards a range request, it should preserve the necessary request headers and forward the semantic meaning of the upstream response, but should not unconditionally copy untrusted headers. The support for range requests in the platform’s Cache API and object storage should be verified according to the official documentation, and cannot be solely based on the assumption that all cases can be inferred from the first successful download.
The tests cover the following ranges: from the beginning, the middle, the end, out-of-bounds, resource updates, and multiple ranges. The received fragments are compared with the original file’s corresponding bytes, and the final file’s hash after resuming from a breakpoint is also tested. The length of the HEAD and GET requests should also be consistent. A correct download is more important than a response header that appears to “support resuming.”
Manual caching can only store complete objects, and then rely on services with proper range support to return fragments; or it can store parts of objects explicitly supported by the platform, but must adhere to merging and validation rules. These two strategies cannot be mixed. If a request includes a Range header, and the origin server returns a 206 status code, writing to the full file key will pollute subsequent full requests. The simplest and most conservative approach is to bypass the manual cache and pass the range to a mature file service upstream.
To determine whether the platform can automatically generate partial responses, specify the required header lengths, and support different range formats if a complete object is already cached, please refer to the actual documentation. It is not possible to derive multiple ranges and correctly use the If-Range header from a single successful hit. The caching layer may modify the validator or encoding, and the application may also re-encode the body, so validation must be performed from the user’s perspective. Test different request sequences for the same file and observe whether the complete response is not replaced by a local object.
The file update process also involves cleanup. Older, complete objects have different versions than new objects, and after the fixed URL is overwritten, the old cache may still be valid. If the If-Range matches the selected older object, the client continues to download the older version. Whether this behavior is allowed depends on the file’s expiration time; in the case of secure revocation, authorization or rejection must be performed before the cache is read. Expired files cannot simply rely on long-term caching to expire naturally. Simplified version URLs improve consistency, but cannot eliminate the need for revocation.
For download proxies, the filenames specified in the Content-Disposition header also need to be handled securely. They should not be directly concatenated with user input or control characters. The filename itself does not determine the content bytes, but it does affect how users save and identify the file. Incorrect content should not be associated with a misleading filename that encourages saving. The correct content type should be maintained, and the client should first determine the status before writing the file. These details ensure that the protocol’s correctness translates into a reliable user experience.
The resource budget can limit the maximum response size and concurrent downloads, but it cannot treat the incomplete content after a timeout as a successful file. Interruption should clearly indicate to the client that the download is incomplete, and re-authentication should be performed when resuming. Finally, the report should provide four results: whether the download is complete, whether the range matches, whether the permissions are valid, and whether the resources have been released. Only testing speed, without testing the final summary, may lead to faster, corrupted downloads being mistakenly identified as successful optimizations.
Establish Clear Additional Conditions for Downloaders
The client already has the initial part of the file from the previous version, and requests the remaining part. Only if the response contains the expected part, with the starting offset matching the saved offset, the version condition is consistent, and the media type is appropriate, is the addition allowed. A complete “200” response should replace the old file. If there are permission errors or other errors, the content will not be added to the file. The decision to add is based solely on the “Range” request that was previously sent. If the server ignores the range, the complete file will be added after the old prefix.
It is also necessary to check the received length against the specified range. The range endpoints include both the start and end, so the expected number of bytes is the end minus the start plus one. If the connection is interrupted in the middle, the number of bytes received may be less than this value, and a complete and successful transfer cannot be confirmed. The final integrity of the file can be verified by comparing the reliable length with a content summary. The summary should come from a trusted source, and should not be solely relied upon for calculating the value of a damaged file. A comparison of the source hash and the result hash is the only way to verify the integrity.
The file containing the breakpoint information, including the identity, completed bytes, and applicable validator, is saved, rather than just the URL and size. Different users’ watermark or signature files may have different representations, and re-authorization and confirmation are required for the same object during recovery. Temporary signature addresses expire, requiring re-acquisition of access rights. This does not mean that version checking can be skipped and the process can continue. Access rights and byte identity are checked separately to ensure both permissions and integrity.
How to Avoid Polluting the Full Object with Partial Caching
A cache only maintains complete file keys, but writes the first 206 response to that key, and subsequent normal GET requests will read the fragments. The eligibility criteria should explicitly state the status and request conditions. Without support for the complete fragment caching protocol, manual layers should not save fragments. The test sequence should be meaningful: first fragments, then complete, then complete then fragments, then alternating fragments, and finally request the complete file to verify the summary. Clearing the cache in each scenario will hide the contamination.
If the platform can generate a range based on the complete cache, it should verify the required length metadata, supported range formats, and conditional processing. Applications should no longer convert the content to text or rewrite the encoding, as the byte positions in the platform correspond to the original representation. Using multiple ranges and merging ranges has additional semantic and resource costs. When not supported, it should use the standard’s allowed complete rollback or mature upstream, rather than simply extracting the first fragment to pretend to satisfy the entire request.
Cache invalidation also requires specifying a range. New and old files with the same path cannot be treated as the same byte object. The old complete object can continue to be downloaded within the valid period, which is a content invalidation strategy. Emergency authorization revocation should take effect before any cache read. Hashing simplifies content consistency, but does not have automatic revocation capabilities, and long-term public resources cannot support private access control.
Identifying Capabilities Based on Message Boundaries, Not File Extensions
PDF, images, or videos are simply media types, and whether they are suitable depends on the stability of the byte stream and the server’s capabilities. Dynamic PDFs may have different rendering times or font variations each time, and visual similarity does not necessarily mean they can be concatenated. Continuous event streams are even less likely to have a fixed final length. Generating and saving an immutable version, and then providing the range later, is often easier to guarantee than supporting random byte requests as they are generated.
Upstream compression and automatic decoding can also alter the selected bytes. The tool should save either the decoded text or the transmitted representation, and this needs to be clearly defined. Range testing should directly compare the bytes of the applicable representation, without relying on string length checks. Data containing Chinese characters and emojis can expose character slicing errors, but binary samples still need to include zero bytes and non-text sequences to avoid only validating UTF-8 exceptions.
Definitions of Resource Budget and Protocol Rollback
Resource Budget: A pre-defined limit on the amount of resources (e.g., CPU, memory, network bandwidth) that a process or application can consume. This budget is typically set during the initial configuration of the system or application.
Protocol Rollback: The process of reverting a system or application to a previous, known-good state. This can be done for a variety of reasons, such as:
- To undo the effects of a failed or corrupted configuration.
- To restore a system to a previous version before a major update or upgrade.
- To isolate a problem and prevent it from affecting other parts of the system.
Large overlapping ranges can lead to processing amplification, limiting the size, number, and concurrency of requests to meet resource protection requirements. Responses rejecting or ignoring a range must still comply with the protocol and cannot return arbitrary fragments with an incorrect Content-Range header. Numerical parsing prevents overflows and avoids allocating large arrays for very large requests. Error logging categories and routing are configured to not log signature parameters or complete private filenames.
The agent only downloads the entire large file to obtain a small final segment, although it may return the correct data, the resource budget is still insufficient. Comparing whether the object storage handles the range directly, and the application only handles authorization and explicit forwarding. Fixed source and redirection checks prevent the file agent from becoming an arbitrary URL reader, and size, time, and content type restrictions can control legitimate resources, but also pose a risk of excessive use. Correct protocol and resource control are acceptance criteria.
Empty files and files with zero-length extensions must have independent samples and cannot directly apply the endpoint algorithm for regular files. The client must also restrict the range of exceptions to avoid large allocations induced by server error headers. The downloader first verifies the reasonable length and status, and then performs file writing. Disk shortages and network interruptions are expressed as partial results. Protocol metadata is considered input, and mature clients also need to prevent untrusted responses from causing local resources to become uncontrolled.
Simulate a failed recovery, not just a successful transfer.
First, receive a segment and then disconnect. Then, modify the file length, content, and permissions, and restore them separately. Length changes should be handled according to the current representation. Content changes should be avoided to prevent mixing. Permission revocation should be rejected before returning the bytes. The client records some results, but does not treat intermediate errors as normal termination. Testing uses synthetic resources and locally controlled accounts, and does not send random read requests to real sensitive files.
Preserve the initial state, range header, actual bytes, final summary, and evidence of resource release. A single sample of 206 cannot prove the correctness of the entire downloader, and a complete file summary cannot prove the security of the rejection scenario. Only when multiple pieces of evidence are combined can “support resuming from a broken connection” be verified as a capability, rather than just a response header.
Verifying Offsets with Synthetic Binary Samples
The local write operation of the downloader also requires independent testing. When two recovery tasks simultaneously append to the same temporary file, even if each segment returned by the server is correct, interleaved bytes may still occur. A single writer needs to maintain a download status, or use a local mechanism that prevents concurrent modifications. When starting the second recovery, it’s important to first identify existing tasks, not just limiting concurrency at the network layer. Having the same URL does not necessarily mean that the local write target can be shared.
The persistent checkpoints must correspond to the previously saved range. If, for example, an offset is recorded as 2000 and then written to the second segment, the process crashes, and restarting will skip the bytes that have not been written to disk. The saved content and the progress checkpoint must have a clear consistency strategy. After recovery, verify the temporary file length and the confirmed range, and do not treat the last log entry as a persistent progress.
To test, stop the download process separately between writing and checkpoint updates, and observe whether the recovery process re-downloads without missing any data.
Once the process is complete, the validated temporary files are handed over to the user as the final result. The ability to replace specific files depends on the operating system and the libraries used. Insufficient disk space, permission errors, and failed renaming operations should not be interpreted as “download complete.” The original complete file should not be overwritten by a partial new result. This verification ensures that the correct HTTP bytes are written to a reliable local file, and the responsibility for obtaining the complete file remains with the user after protocol validation.
References: HTTP Range Requests, HTTP Semantics RFC 9110.