Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion crates/cf-workers/src/backend.rs
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,11 @@ impl ProxyBackend for WorkerBackend {
// Build web_sys::RequestInit.
let init = web_sys::RequestInit::new();
init.set_method(request.method.as_str());
init.set_headers(&WsHeaders::from(&request.headers).into_inner().into());
let headers = WsHeaders::from(&request.headers).into_inner();
if let Some(accept_encoding) = request.accept_encoding() {
let _ = headers.set("accept-encoding", accept_encoding);
}
init.set_headers(&headers.into());

// Bypass Cloudflare's subrequest cache for reads where leaving it on
// would break the request (HEAD rewritten to GET on cacheable-extension
Expand Down
48 changes: 48 additions & 0 deletions crates/core/src/route_handler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,28 @@ impl ForwardRequest {
pub fn should_bypass_cache(&self) -> bool {
self.method == Method::HEAD || self.headers.contains_key(http::header::RANGE)
}

/// The `Accept-Encoding` the runtime should send the backend, if any.
///
/// Reads ask for the stored encoding as-is. Object stores ignore the header
/// (S3 serves an object exactly as stored), but a runtime in front of them
/// may not: on Cloudflare, a subrequest without it has an object stored with
/// `Content-Encoding` (e.g. uploaded brotli-compressed) decoded before the
/// Worker sees it, so every client gets the uncompressed body with the
/// header dropped. With it, the encoded body passes through and the edge
/// decodes it only for clients whose `Accept-Encoding` can't take it.
/// Covers `br` and `gzip`, the encodings Cloudflare decodes for clients.
///
/// Ranged reads get none: Cloudflare strips `Content-Encoding` from a `206`
/// either way, so the header gains nothing there and would only invite a
/// backend that compresses on request to return a compressed slice.
///
/// Runtimes opt in by sending this on their backend request; only the
/// Cloudflare Workers backend does.
pub fn accept_encoding(&self) -> Option<&'static str> {
let read = matches!(self.method, Method::GET | Method::HEAD);
(read && !self.headers.contains_key(http::header::RANGE)).then_some("br, gzip")
}
}

/// The result of handling a proxy request.
Expand Down Expand Up @@ -465,6 +487,32 @@ mod tests {
assert!(!forward(Method::PUT, None).should_bypass_cache());
}

#[test]
fn accept_encoding_on_reads_only() {
// Reads take the stored encoding as-is (see `accept_encoding`).
assert_eq!(
forward(Method::GET, None).accept_encoding(),
Some("br, gzip")
);
assert_eq!(
forward(Method::HEAD, None).accept_encoding(),
Some("br, gzip")
);
// Ranged reads gain nothing (Cloudflare strips `Content-Encoding` from
// 206s) and must not invite a backend to compress the slice.
assert_eq!(
forward(Method::GET, Some("bytes=0-9")).accept_encoding(),
None
);
assert_eq!(
forward(Method::HEAD, Some("bytes=0-9")).accept_encoding(),
None
);
// Writes return no body worth negotiating.
assert_eq!(forward(Method::PUT, None).accept_encoding(), None);
assert_eq!(forward(Method::POST, None).accept_encoding(), None);
}

#[test]
fn test_blocks_hop_by_hop_headers() {
let mut headers = http::HeaderMap::new();
Expand Down
1 change: 1 addition & 0 deletions docs/architecture/request-lifecycle.md
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,7 @@ The handler generates a presigned URL using the backend's `Signer`, then the cor

- Presigned URL TTL: 300 seconds
- Headers forwarded: `range`, `if-match`, `if-none-match`, `if-modified-since`, `if-unmodified-since`, `content-type`, `content-length`, `content-md5`, `content-encoding`, `content-disposition`, `cache-control`, `x-amz-content-sha256`
- `ForwardRequest::accept_encoding` gives the `Accept-Encoding` a runtime should send the backend: `br, gzip` on non-ranged reads (GET/HEAD), so a runtime that would otherwise decode stored `Content-Encoding` bodies passes them through. Runtimes opt in by sending it; only the Cloudflare Workers backend does.

### `Response(ProxyResult)`

Expand Down
2 changes: 2 additions & 0 deletions docs/deployment/cloudflare-workers.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ The CF Workers runtime deploys the proxy to Cloudflare's edge network. It compil

Forwarded object responses (GET/HEAD) carry `Cache-Control: no-transform`, appended to any directives the backend returned. Without it, Cloudflare gzips compressible types such as `text/*` for clients that send `Accept-Encoding: gzip`, which strips `Content-Length` and `Accept-Ranges`, weakens the `ETag` (`W/"…"`), and breaks clients that size or split downloads from a HEAD or send `If-Match`.

Objects stored with a `Content-Encoding` (e.g. uploaded brotli-compressed with `Content-Encoding: br`) are served as stored to clients that accept that encoding, and decoded by Cloudflare's edge for clients that don't. This covers `br` and `gzip`, and relies on the backend subrequest sending `Accept-Encoding: br, gzip` on non-ranged reads (`ForwardRequest::accept_encoding`); without it, Cloudflare decodes the body before the Worker sees it, and every client gets the uncompressed body without the header. Ranged reads (`206`) of an encoded object return slices of the stored bytes, and Cloudflare's edge removes their `Content-Encoding` header, so they are sent without `Accept-Encoding`. `wrangler dev` passes encoded bodies through either way, so only a deployed Worker shows this behavior.

To trade those guarantees for edge compression (e.g. a text-only public mirror), remove the directive from the `web_sys::Response` returned by `into_web_sys()`:

```rust
Expand Down
45 changes: 45 additions & 0 deletions tests/integration/test_integration.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
ACTIONS_ID_TOKEN_REQUEST_URL: GitHub Actions OIDC endpoint (automatic in CI)
"""

import gzip
import os
import uuid
import xml.etree.ElementTree as ET
Expand Down Expand Up @@ -931,6 +932,50 @@ def test_get_caller_identity_rejects_static_credentials(self):
assert exc_info.value.response["ResponseMetadata"]["HTTPStatusCode"] == 403


# ---------------------------------------------------------------------------
# Stored Content-Encoding
# ---------------------------------------------------------------------------

class TestStoredContentEncoding:
"""An object stored with `Content-Encoding` (e.g. uploaded pre-compressed)
is served as stored, the encoded bytes plus the header, to a client that
accepts the encoding, so HTTP clients decode it transparently.

`wrangler dev` passes encoded bodies through even without the read-side
`Accept-Encoding` (`ForwardRequest::accept_encoding`); only Cloudflare's
network decodes them. This guards the proxy's own handling, not that.
"""

BODY = b'{"id": 1, "name": "example"}\n' * 500

@pytest.fixture(scope="class")
@classmethod
def encoded_key(cls):
key = f"test-encoded-{uuid.uuid4()}.jsonl"
backend = TestByteFaithfulKeys._backend_client()
backend.put_object(
Bucket="public-data",
Key=key,
Body=gzip.compress(cls.BODY, mtime=0),
ContentEncoding="gzip",
ContentType="application/x-ndjson",
)
yield key
backend.delete_object(Bucket="public-data", Key=key)

def test_full_get_keeps_encoding(self, encoded_key):
with requests.get(
f"{PROXY_URL}/public-data/{encoded_key}",
headers={"Accept-Encoding": "gzip"},
stream=True,
) as resp:
assert resp.status_code == 200
assert resp.headers.get("Content-Encoding") == "gzip"
wire = resp.raw.read(decode_content=False)
assert wire == gzip.compress(self.BODY, mtime=0)
assert gzip.decompress(wire) == self.BODY


# ---------------------------------------------------------------------------
# Anonymous access
# ---------------------------------------------------------------------------
Expand Down
Loading