abhishekgahlot commited on
Commit
bddaf1a
·
verified ·
1 Parent(s): 65883b8

OpenJev 1.1: full card, figures, helper and licence files

Browse files
Files changed (1) hide show
  1. helper/compat.py +35 -7
helper/compat.py CHANGED
@@ -24,6 +24,8 @@ import shim as S
24
  DEFAULT_INSTRUCTIONS = {"choice": "Which option is correct?", "score": "Rate the content above.", "noul": "Is the statement true?"}
25
  RELEASE_DATE = os.environ.get("SHIM_RELEASE_DATE") or time.strftime("%Y-%m-%d") # the hosted schema requires a date; ours is unknown to the server
26
  MAX_BODY = 32 * 1024 * 1024 # the hosted limit, for the body as sent and after decompression (docs.typesafe.ai/api/errors.md)
 
 
27
 
28
 
29
  class ApiError(Exception):
@@ -32,17 +34,29 @@ class ApiError(Exception):
32
  self.code, self.message = code, message
33
 
34
 
35
- def unzstd(raw):
 
36
  try:
37
  from compression import zstd # Python 3.14+
38
- return zstd.decompress(raw)
39
  except ImportError:
40
  pass
41
  try:
42
  import zstandard
43
  except ImportError:
44
  raise ApiError(415, "this server cannot read zstd bodies (install the zstandard package or run on Python 3.14+); gzip works")
45
- return zstandard.ZstdDecompressor().decompressobj().decompress(raw) # decompressobj: frames without a content-size header decode too
 
 
 
 
 
 
 
 
 
 
 
46
 
47
 
48
  def decode(raw, encoding):
@@ -53,15 +67,19 @@ def decode(raw, encoding):
53
  if enc not in ("gzip", "x-gzip", "zstd"):
54
  raise ApiError(415, f"unsupported Content-Encoding {encoding!r}: use gzip, x-gzip or zstd, one layer")
55
  try:
56
- return gzip.decompress(raw) if enc != "zstd" else unzstd(raw)
57
  except ApiError:
58
  raise
59
  except Exception as e:
60
  raise ApiError(400, f"malformed {enc} body: {str(e)[:120]}")
 
 
 
61
 
62
 
63
  def split_multipart(data, content_type):
64
  """multipart/form-data (RFC 7578) → (the first part, `request`, as JSON bytes; {name: bytes} of the other parts)"""
 
65
  msg = email.message_from_bytes(b"Content-Type: " + content_type.encode("latin-1") + b"\r\n\r\n" + data, policy=email.policy.HTTP)
66
  parts = [(p.get_param("name", header="content-disposition"), p.get_payload(decode=True)) for p in msg.iter_parts()]
67
  names = [n for n, _ in parts]
@@ -70,6 +88,18 @@ def split_multipart(data, content_type):
70
  return parts[0][1] or b"", dict(parts[1:])
71
 
72
 
 
 
 
 
 
 
 
 
 
 
 
 
73
  def uses(v, ref):
74
  """how often `ref` occurs in the strings of v; object keys are not searched, as on the hosted API"""
75
  if isinstance(v, str):
@@ -145,9 +175,7 @@ class H(S.H):
145
  if self.unauthorized():
146
  return self.fail(401, "missing or invalid bearer token")
147
  try:
148
- data = decode(raw, self.headers.get("Content-Encoding"))
149
- if len(data) > MAX_BODY: # checked after inflating in full; only a token holder gets this far
150
- raise ApiError(413, "the body is over 32 MiB after decompression")
151
  files = {}
152
  if self.headers.get_content_type() == "multipart/form-data":
153
  data, files = split_multipart(data, self.headers["Content-Type"])
 
24
  DEFAULT_INSTRUCTIONS = {"choice": "Which option is correct?", "score": "Rate the content above.", "noul": "Is the statement true?"}
25
  RELEASE_DATE = os.environ.get("SHIM_RELEASE_DATE") or time.strftime("%Y-%m-%d") # the hosted schema requires a date; ours is unknown to the server
26
  MAX_BODY = 32 * 1024 * 1024 # the hosted limit, for the body as sent and after decompression (docs.typesafe.ai/api/errors.md)
27
+ WINDOW_LOG_MAX = 25 # zstd frames may ask for a window of at most 32 MiB, the largest a body within MAX_BODY needs
28
+ MAX_PARTS, MAX_PART_HEADER = 2, 8192 # a multipart body is the JSON part and at most one image; each part's header block stays short
29
 
30
 
31
  class ApiError(Exception):
 
34
  self.code, self.message = code, message
35
 
36
 
37
+ def zstd_reader(raw):
38
+ """a reader over a zstd body (all frames) whose window is capped at WINDOW_LOG_MAX"""
39
  try:
40
  from compression import zstd # Python 3.14+
41
+ return zstd.ZstdFile(io.BytesIO(raw), options={zstd.DecompressionParameter.window_log_max: WINDOW_LOG_MAX})
42
  except ImportError:
43
  pass
44
  try:
45
  import zstandard
46
  except ImportError:
47
  raise ApiError(415, "this server cannot read zstd bodies (install the zstandard package or run on Python 3.14+); gzip works")
48
+ return zstandard.ZstdDecompressor(max_window_size=1 << WINDOW_LOG_MAX).stream_reader(io.BytesIO(raw), read_across_frames=True)
49
+
50
+
51
+ def inflate(raw, enc, limit=None):
52
+ """one gzip or zstd layer → at most limit + 1 bytes (limit: MAX_BODY), read in 1 MiB steps: a bomb stops at the limit"""
53
+ limit = MAX_BODY if limit is None else limit
54
+ out, n = [], 0
55
+ with zstd_reader(raw) if enc == "zstd" else gzip.GzipFile(fileobj=io.BytesIO(raw)) as reader:
56
+ while n <= limit and (chunk := reader.read(min(1 << 20, limit + 1 - n))):
57
+ out.append(chunk)
58
+ n += len(chunk)
59
+ return b"".join(out)
60
 
61
 
62
  def decode(raw, encoding):
 
67
  if enc not in ("gzip", "x-gzip", "zstd"):
68
  raise ApiError(415, f"unsupported Content-Encoding {encoding!r}: use gzip, x-gzip or zstd, one layer")
69
  try:
70
+ data = inflate(raw, enc)
71
  except ApiError:
72
  raise
73
  except Exception as e:
74
  raise ApiError(400, f"malformed {enc} body: {str(e)[:120]}")
75
+ if len(data) > MAX_BODY:
76
+ raise ApiError(413, "the body is over 32 MiB after decompression")
77
+ return data
78
 
79
 
80
  def split_multipart(data, content_type):
81
  """multipart/form-data (RFC 7578) → (the first part, `request`, as JSON bytes; {name: bytes} of the other parts)"""
82
+ check_parts(data, content_type)
83
  msg = email.message_from_bytes(b"Content-Type: " + content_type.encode("latin-1") + b"\r\n\r\n" + data, policy=email.policy.HTTP)
84
  parts = [(p.get_param("name", header="content-disposition"), p.get_payload(decode=True)) for p in msg.iter_parts()]
85
  names = [n for n, _ in parts]
 
88
  return parts[0][1] or b"", dict(parts[1:])
89
 
90
 
91
+ def check_parts(data, content_type):
92
+ """a linear pass before parsing: at most MAX_PARTS parts, each header block under MAX_PART_HEADER bytes"""
93
+ boundary = email.message_from_bytes(b"Content-Type: " + content_type.encode("latin-1") + b"\r\n\r\n").get_param("boundary")
94
+ if not boundary:
95
+ raise ApiError(400, "a multipart body needs a boundary in its Content-Type")
96
+ parts = data.split(b"--" + boundary.encode("latin-1"))[1:-1]
97
+ if len(parts) > MAX_PARTS:
98
+ raise ApiError(400, f"a multipart body has at most {MAX_PARTS} parts: the JSON and one image")
99
+ if any(not 0 <= p.find(b"\r\n\r\n") <= MAX_PART_HEADER for p in parts):
100
+ raise ApiError(400, f"each multipart part needs a header block under {MAX_PART_HEADER} bytes")
101
+
102
+
103
  def uses(v, ref):
104
  """how often `ref` occurs in the strings of v; object keys are not searched, as on the hosted API"""
105
  if isinstance(v, str):
 
175
  if self.unauthorized():
176
  return self.fail(401, "missing or invalid bearer token")
177
  try:
178
+ data = decode(raw, self.headers.get("Content-Encoding")) # 413 when it inflates past MAX_BODY, without holding more
 
 
179
  files = {}
180
  if self.headers.get_content_type() == "multipart/form-data":
181
  data, files = split_multipart(data, self.headers["Content-Type"])