Skip to content

Commit d8b30b7

Browse files
steipetePeter Steinberger
andauthored
fix(gateway): honor conditional media ETags (#116880)
Co-authored-by: Peter Steinberger <[email protected]>
1 parent c19e55f commit d8b30b7

9 files changed

Lines changed: 190 additions & 16 deletions

‎src/gateway/control-ui-assistant-media.e2e.test.ts‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,24 @@ describe("Control UI assistant media e2e", () => {
7272
expect(head.headers.get("etag")).toBe(ranged.headers.get("etag"));
7373
expect(await head.text()).toBe("");
7474

75+
for (const method of ["GET", "HEAD"]) {
76+
const notModified = await fetch(
77+
`${route}?source=${sourceParam}&mediaTicket=${encodeURIComponent(payload.mediaTicket ?? "")}`,
78+
{
79+
method,
80+
headers: {
81+
"If-None-Match": `W/${ranged.headers.get("etag")}`,
82+
Range: "bytes=9-15",
83+
"If-Range": '"stale"',
84+
},
85+
},
86+
);
87+
expect(notModified.status).toBe(304);
88+
expect(notModified.headers.get("etag")).toBe(ranged.headers.get("etag"));
89+
expect(notModified.headers.get("content-length")).toBeNull();
90+
expect(await notModified.text()).toBe("");
91+
}
92+
7593
const emptyFilePath = path.join(mediaDir, "empty.bin");
7694
await fs.writeFile(emptyFilePath, Buffer.alloc(0));
7795
const empty = await fetch(`${route}?source=${encodeURIComponent(emptyFilePath)}`, {

‎src/gateway/control-ui.http.test.ts‎

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -567,6 +567,44 @@ describe("handleControlUiHttpRequest", () => {
567567
});
568568
});
569569

570+
it.each(["GET", "HEAD"] as const)(
571+
"revalidates assistant media ETags before ranges for %s",
572+
async (method) => {
573+
await withAllowedAssistantMediaRoot({
574+
prefix: "ui-media-conditional-",
575+
fn: async (tmpRoot) => {
576+
const filePath = path.join(tmpRoot, "photo.png");
577+
await fs.writeFile(filePath, Buffer.from("not-a-real-png"));
578+
const url = `/__openclaw__/assistant-media?source=${encodeURIComponent(filePath)}&token=test-token`;
579+
const auth = { mode: "token", token: "test-token", allowTailscale: false } as const;
580+
const initial = await runAssistantMediaRequest({ url, method: "HEAD", auth });
581+
const etag = initial.setHeader.mock.calls.find(([name]) => name === "ETag")?.[1];
582+
expect(etag).toMatch(/^"[A-Za-z0-9_-]+"$/);
583+
584+
const conditional = await runAssistantMediaRequest({
585+
url,
586+
method,
587+
auth,
588+
headers: {
589+
"if-none-match": `W/${String(etag)}`,
590+
range: "bytes=0-3",
591+
"if-range": '"stale"',
592+
},
593+
});
594+
595+
expect(conditional.handled).toBe(true);
596+
expect(conditional.res.statusCode).toBe(304);
597+
expect(conditional.setHeader).toHaveBeenCalledWith("ETag", etag);
598+
expect(conditional.setHeader).not.toHaveBeenCalledWith(
599+
"Content-Length",
600+
expect.anything(),
601+
);
602+
expect(conditional.end).toHaveBeenCalledWith();
603+
},
604+
});
605+
},
606+
);
607+
570608
it("returns 202 while assistant playback media is preparing", async () => {
571609
resolvePlaybackTranscodeMock.mockResolvedValueOnce({ kind: "preparing" });
572610
await withAllowedAssistantMediaRoot({

‎src/gateway/control-ui.ts‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -735,9 +735,15 @@ export async function handleControlUiAssistantMediaRequest(
735735
method: req.method,
736736
rangeHeader: req.headers.range,
737737
ifRangeHeader: req.headers["if-range"],
738+
ifNoneMatchHeader: req.headers["if-none-match"],
738739
});
739740
writeByteHeaders(res, byteResponse);
740-
if (req.method === "HEAD" || byteResponse.kind === "unsatisfiable" || opened.stat.size === 0) {
741+
if (
742+
req.method === "HEAD" ||
743+
byteResponse.kind === "not-modified" ||
744+
byteResponse.kind === "unsatisfiable" ||
745+
opened.stat.size === 0
746+
) {
741747
await closeOpenedHandle();
742748
res.end();
743749
return true;

‎src/gateway/http-byte-range.test.ts‎

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,60 @@ describe("resolveByteResponse", () => {
8787
}),
8888
).toMatchObject({ kind: "full", statusCode: 200, contentLength: 10 });
8989
});
90+
91+
it.each([
92+
{ label: "exact", header: (etag: string) => etag },
93+
{ label: "weak", header: (etag: string) => `W/${etag}` },
94+
{ label: "wildcard", header: () => "*" },
95+
{ label: "list", header: (etag: string) => `"other", ${etag}` },
96+
{ label: "multiple headers", header: (etag: string) => ['"other"', `W/${etag}`] },
97+
])("returns 304 for a matching $label If-None-Match validator", ({ header }) => {
98+
const etag = resolveByteResponse({ file: FILE }).etag;
99+
const plan = resolveByteResponse({
100+
file: FILE,
101+
method: "GET",
102+
ifNoneMatchHeader: header(etag),
103+
});
104+
105+
expect(plan).toEqual({ kind: "not-modified", statusCode: 304, etag });
106+
const setHeader = vi.fn();
107+
const res = { statusCode: 0, setHeader } as unknown as ServerResponse;
108+
writeByteHeaders(res, plan);
109+
expect(res.statusCode).toBe(304);
110+
expect(setHeader).toHaveBeenCalledWith("ETag", etag);
111+
expect(setHeader).not.toHaveBeenCalledWith("Content-Length", expect.anything());
112+
});
113+
114+
it.each(["GET", "HEAD"])(
115+
"evaluates matching If-None-Match before Range and If-Range for %s",
116+
(method) => {
117+
const etag = resolveByteResponse({ file: FILE }).etag;
118+
119+
expect(
120+
resolveByteResponse({
121+
file: FILE,
122+
method,
123+
rangeHeader: "bytes=1-2",
124+
ifRangeHeader: '"stale"',
125+
ifNoneMatchHeader: etag,
126+
}),
127+
).toEqual({ kind: "not-modified", statusCode: 304, etag });
128+
},
129+
);
130+
131+
it("keeps the requested range when If-None-Match does not match", () => {
132+
const etag = resolveByteResponse({ file: FILE }).etag;
133+
134+
expect(
135+
resolveByteResponse({
136+
file: FILE,
137+
method: "GET",
138+
rangeHeader: "bytes=1-2",
139+
ifRangeHeader: etag,
140+
ifNoneMatchHeader: '"stale"',
141+
}),
142+
).toMatchObject({ kind: "partial", statusCode: 206, range: { start: 1, end: 2 } });
143+
});
90144
});
91145

92146
describe("byte ETag generation", () => {

‎src/gateway/http-byte-range.ts‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import { createHash } from "node:crypto";
22
import type { ServerResponse } from "node:http";
3+
import { matchesHttpIfNoneMatch } from "./http-conditional.js";
34

45
type FileIdentity = {
56
size: number;
@@ -32,6 +33,11 @@ type ByteResponsePlan =
3233
contentLength: 0;
3334
etag: string;
3435
size: number;
36+
}
37+
| {
38+
kind: "not-modified";
39+
statusCode: 304;
40+
etag: string;
3541
};
3642

3743
function createByteEtag(file: FileIdentity): string {
@@ -80,8 +86,16 @@ export function resolveByteResponse(params: {
8086
method?: string;
8187
rangeHeader?: string | string[];
8288
ifRangeHeader?: string | string[];
89+
ifNoneMatchHeader?: string | string[];
8390
}): ByteResponsePlan {
8491
const etag = createByteEtag(params.file);
92+
if (
93+
(params.method === "GET" || params.method === "HEAD") &&
94+
matchesHttpIfNoneMatch(params.ifNoneMatchHeader, etag)
95+
) {
96+
// RFC 9110 evaluates representation validators before Range or If-Range.
97+
return { kind: "not-modified", statusCode: 304, etag };
98+
}
8599
const full = {
86100
kind: "full",
87101
statusCode: 200,
@@ -122,6 +136,9 @@ export function writeByteHeaders(res: ServerResponse, plan: ByteResponsePlan): v
122136
res.statusCode = plan.statusCode;
123137
res.setHeader("Accept-Ranges", "bytes");
124138
res.setHeader("ETag", plan.etag);
139+
if (plan.kind === "not-modified") {
140+
return;
141+
}
125142
res.setHeader("Content-Length", String(plan.contentLength));
126143
if (plan.kind === "partial") {
127144
res.setHeader("Content-Range", `bytes ${plan.range.start}-${plan.range.end}/${plan.size}`);

‎src/gateway/http-conditional.ts‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
// HTTP conditional requests use weak entity-tag comparison for representation reuse.
2+
export function matchesHttpIfNoneMatch(
3+
header: string | string[] | undefined,
4+
etag: string,
5+
): boolean {
6+
const value = Array.isArray(header) ? header.join(",") : header;
7+
if (!value) {
8+
return false;
9+
}
10+
return value.split(",").some((candidate) => {
11+
const tag = candidate.trim();
12+
return tag === "*" || tag === etag || (tag.startsWith("W/") && tag.slice(2) === etag);
13+
});
14+
}

‎src/gateway/managed-image-attachments.test.ts‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -416,6 +416,39 @@ describe("handleManagedOutgoingImageHttpRequest", () => {
416416
expect(result.body.toString("utf8")).toBe("image");
417417
});
418418

419+
it.each(["GET", "HEAD"])(
420+
"revalidates managed media ETags before ranges for %s",
421+
async (method) => {
422+
const { attachmentId, sessionKey } = await createFixture(stateDir);
423+
const pathName = `/api/chat/media/outgoing/${encodeURIComponent(sessionKey)}/${attachmentId}/full`;
424+
const initial = await requestManagedImage({
425+
stateDir,
426+
pathName,
427+
authResponse: { authMethod: "token" },
428+
});
429+
const etag = initial.result.headers.etag;
430+
expect(etag).toMatch(/^"[A-Za-z0-9_-]+"$/);
431+
432+
const { result } = await requestManagedImage({
433+
stateDir,
434+
pathName,
435+
method,
436+
authResponse: { authMethod: "token" },
437+
headers: {
438+
"if-none-match": `W/${String(etag)}`,
439+
range: "bytes=0-3",
440+
"if-range": '"stale"',
441+
},
442+
});
443+
444+
expect(result.statusCode).toBe(304);
445+
expect(result.headers.etag).toBe(etag);
446+
expect(result.headers["content-length"]).toBeUndefined();
447+
expect(result.headers["content-range"]).toBeUndefined();
448+
expect(result.body).toHaveLength(0);
449+
},
450+
);
451+
419452
it("serves a ticketed byte range from managed audio", async () => {
420453
const body = Buffer.from("original-audio");
421454
const { attachmentId, sessionKey } = await createFixture(stateDir, {

‎src/gateway/managed-image-attachments.ts‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1518,9 +1518,15 @@ export async function handleManagedOutgoingMediaHttpRequest(
15181518
method: req.method,
15191519
rangeHeader: req.headers.range,
15201520
ifRangeHeader: req.headers["if-range"],
1521+
ifNoneMatchHeader: req.headers["if-none-match"],
15211522
});
15221523
writeByteHeaders(res, byteResponse);
1523-
if (req.method === "HEAD" || byteResponse.kind === "unsatisfiable" || opened.stat.size === 0) {
1524+
if (
1525+
req.method === "HEAD" ||
1526+
byteResponse.kind === "not-modified" ||
1527+
byteResponse.kind === "unsatisfiable" ||
1528+
opened.stat.size === 0
1529+
) {
15241530
await closeOpenedHandle();
15251531
res.end();
15261532
return true;

‎src/gateway/user-profiles-http.ts‎

Lines changed: 2 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import {
1212
import type { AuthRateLimiter } from "./auth-rate-limit.js";
1313
import type { ResolvedGatewayAuth } from "./auth.js";
1414
import { sendJson, sendMethodNotAllowed } from "./http-common.js";
15+
import { matchesHttpIfNoneMatch } from "./http-conditional.js";
1516
import {
1617
authorizeScopedGatewayHttpRequestOrReply,
1718
resolveSharedSecretHttpOperatorScopes,
@@ -267,7 +268,7 @@ function sendAvatar(
267268
avatar: { bytes: Uint8Array; mime: string; etag: string },
268269
cacheControl: string,
269270
): void {
270-
if (ifNoneMatchMatches(req.headers["if-none-match"], avatar.etag)) {
271+
if (matchesHttpIfNoneMatch(req.headers["if-none-match"], avatar.etag)) {
271272
// Carry the success cache policy so a 304 does not inherit the miss-path
272273
// no-store and force the client to re-download an unchanged avatar.
273274
res.writeHead(304, { ETag: avatar.etag, "Cache-Control": cacheControl });
@@ -404,16 +405,3 @@ export async function handleUserProfileAvatarHttpRequest(
404405
});
405406
return true;
406407
}
407-
408-
// RFC 9110 §13.1.2 weak comparison: wildcard, comma-separated lists, and W/ prefixes
409-
// all revalidate; exact-string matching alone would miss proxy-normalized headers.
410-
function ifNoneMatchMatches(header: string | string[] | undefined, etag: string): boolean {
411-
const value = Array.isArray(header) ? header.join(",") : header;
412-
if (!value) {
413-
return false;
414-
}
415-
return value.split(",").some((candidate) => {
416-
const tag = candidate.trim();
417-
return tag === "*" || tag === etag || (tag.startsWith("W/") && tag.slice(2) === etag);
418-
});
419-
}

0 commit comments

Comments
 (0)