lukeed / sirv

An optimized middleware & CLI application for serving static files~!
MIT License
1.06k stars 56 forks source link

Range request overlap is handled incorrectly #140

Closed dmkret closed 1 year ago

dmkret commented 2 years ago

RFC 7233, Section 4.4:

The 416 (Range Not Satisfiable) status code indicates that none of the ranges in the request's Range header field (Section 3.1) overlap the current extent of the selected resource

For byte ranges, failing to overlap the current extent means that the first-byte-pos of all of the byte-range-spec values were greater than the current length of the selected representation.

Current implementation limits end of range and returns 416 error: https://github.com/lukeed/sirv/blob/886cc962a345780cd78f8910cdcf218db2a8d955/packages/sirv/index.js#L72-L80

end can be limited with Math.min, for example, and excluded from condition

let [x, y] = req.headers.range.replace('bytes=', '').split('-');
let end = opts.end = Math.min(parseInt(y, 10) || stats.size - 1, stats.size - 1);
let start = opts.start = parseInt(x, 10) || 0;

if (start >= stats.size) {
    res.setHeader('Content-Range', `bytes */${stats.size}`);
    res.statusCode = 416;
    return res.end();
}
bfanger commented 1 year ago

For ranges of bytes, if the first byte of the specified range was greater than the length of the sequence, then this error message will be returned.

https://http.dev/416

This is giving problems on Microsoft Azure Platform where a lot of range: bytes=0-8388607 requests are made by Azure Front Door.

alexbjorlig commented 1 year ago

@lukeed what do you think about the #147 ? Is not a low-risk PR - fixing a rather big problem? (Linkedin sends a 'range' => 'bytes=0-3145727', when previewing links.)