protocol.spec.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  1. import { describe, expect, it } from 'vitest'
  2. import { checkDoneValue, encodeJsonPlain, hasNonLosslessNumber, hasUnsafeIntegerToken, logTruncationMarker, validateChildFrame } from '../src/index.ts'
  3. describe('logTruncationMarker', () => {
  4. it('names the configured byte budget', () => {
  5. expect(logTruncationMarker(65536)).toBe('[dsh-code-runtime-python] log capture truncated at 65536 bytes')
  6. expect(logTruncationMarker(1)).toBe('[dsh-code-runtime-python] log capture truncated at 1 bytes')
  7. })
  8. })
  9. describe('validateChildFrame', () => {
  10. it('rebuilds boot-ack frames without extra fields', () => {
  11. expect(validateChildFrame({ type: 'boot-ack' })).toEqual({ type: 'boot-ack' })
  12. // Forged extras never ride along.
  13. expect(validateChildFrame({ type: 'boot-ack', extra: 'x' })).toEqual({ type: 'boot-ack' })
  14. })
  15. it('rebuilds log frames when the text field is a string', () => {
  16. expect(validateChildFrame({ type: 'log', text: 'hi' })).toEqual({ type: 'log', text: 'hi' })
  17. // Non-string text drops.
  18. expect(validateChildFrame({ type: 'log', text: 42 })).toBeUndefined()
  19. expect(validateChildFrame({ type: 'log' })).toBeUndefined()
  20. })
  21. it('carries a log frame truncation flag only for the literal true', () => {
  22. // The child's own ledger marker sets `truncated: true`; the host rebuilds
  23. // it so it stops capturing at the same point.
  24. expect(validateChildFrame({ type: 'log', text: 'x', truncated: true }))
  25. .toEqual({ type: 'log', text: 'x', truncated: true })
  26. // Any other truthy or non-boolean value is a forgery and is dropped from
  27. // the rebuild — otherwise it would silence capture for the rest of the run.
  28. expect(validateChildFrame({ type: 'log', text: 'x', truncated: 1 })).toEqual({ type: 'log', text: 'x' })
  29. expect(validateChildFrame({ type: 'log', text: 'x', truncated: 'yes' })).toEqual({ type: 'log', text: 'x' })
  30. expect(validateChildFrame({ type: 'log', text: 'x', truncated: false })).toEqual({ type: 'log', text: 'x' })
  31. })
  32. it('rebuilds call frames with a numeric id, string global, and string name', () => {
  33. expect(validateChildFrame({ type: 'call', id: 1, global: 'tools', name: 'echo', args: { x: 1 } }))
  34. .toEqual({ type: 'call', id: 1, global: 'tools', name: 'echo', args: { x: 1 } })
  35. // A frame with NO args key drops whole: rebuilding it as `undefined`
  36. // would invoke the binding with a non-JSON value, bypassing the
  37. // lossless-JSON argument boundary. Any present value is JSON-plain by
  38. // construction (frames arrive via JSON.parse), so null passes.
  39. expect(validateChildFrame({ type: 'call', id: 2, global: 'tools', name: 'echo' })).toBeUndefined()
  40. expect(validateChildFrame({ type: 'call', id: 2, global: 'tools', name: 'echo', args: null }))
  41. .toEqual({ type: 'call', id: 2, global: 'tools', name: 'echo', args: null })
  42. // A missing/mistyped required field drops.
  43. expect(validateChildFrame({ type: 'call', id: '1', global: 'tools', name: 'echo' })).toBeUndefined()
  44. expect(validateChildFrame({ type: 'call', id: 1, global: 7, name: 'echo' })).toBeUndefined()
  45. expect(validateChildFrame({ type: 'call', id: 1, global: 'tools' })).toBeUndefined()
  46. })
  47. it('rebuilds done frames with optional value/error', () => {
  48. expect(validateChildFrame({ type: 'done' })).toEqual({ type: 'done' })
  49. expect(validateChildFrame({ type: 'done', value: 42 })).toEqual({ type: 'done', value: 42 })
  50. expect(validateChildFrame({ type: 'done', error: { kind: 'exception', message: 'boom' } }))
  51. .toEqual({ type: 'done', error: { kind: 'exception', message: 'boom' } })
  52. expect(validateChildFrame({ type: 'done', error: { kind: 'invalid-output', message: 'lossy' } }))
  53. .toEqual({ type: 'done', error: { kind: 'invalid-output', message: 'lossy' } })
  54. expect(validateChildFrame({ type: 'done', error: { kind: 'output-limit', message: 'big' } }))
  55. .toEqual({ type: 'done', error: { kind: 'output-limit', message: 'big' } })
  56. expect(validateChildFrame({ type: 'done', value: 1, error: { kind: 'exception', message: 'boom' } }))
  57. .toEqual({ type: 'done', value: 1, error: { kind: 'exception', message: 'boom' } })
  58. // A `value: undefined` field is dropped (JSON never carries it, but a forged
  59. // shape might; the rebuild coalesces to the absent case).
  60. expect(validateChildFrame({ type: 'done', value: undefined })).toEqual({ type: 'done' })
  61. // A missing or unrecognized kind drops the frame: the child always sends
  62. // one of the three, so anything else is a forgery.
  63. expect(validateChildFrame({ type: 'done', error: { message: 'boom' } })).toBeUndefined()
  64. expect(validateChildFrame({ type: 'done', error: { kind: 'timeout', message: 'x' } })).toBeUndefined()
  65. })
  66. it('rejects malformed done frames', () => {
  67. // error must be an object.
  68. expect(validateChildFrame({ type: 'done', error: 'boom' })).toBeUndefined()
  69. expect(validateChildFrame({ type: 'done', error: null })).toBeUndefined()
  70. // error.message must be a string.
  71. expect(validateChildFrame({ type: 'done', error: {} })).toBeUndefined()
  72. expect(validateChildFrame({ type: 'done', error: { message: 42 } })).toBeUndefined()
  73. })
  74. it('drops non-object inputs and unknown types silently', () => {
  75. expect(validateChildFrame(null)).toBeUndefined()
  76. expect(validateChildFrame(undefined)).toBeUndefined()
  77. expect(validateChildFrame(42)).toBeUndefined()
  78. expect(validateChildFrame('str')).toBeUndefined()
  79. expect(validateChildFrame({})).toBeUndefined()
  80. expect(validateChildFrame({ type: 'unknown' })).toBeUndefined()
  81. })
  82. it('drops CALL frames whose args are non-finite or negative zero', () => {
  83. // JSON.parse turns 1e400 into Infinity and preserves -0; the honest child
  84. // rejects both before sending, so a call frame carrying one is forged.
  85. expect(validateChildFrame({ type: 'call', id: 1, global: 'tools', name: 'x', args: { n: Infinity } })).toBeUndefined()
  86. expect(validateChildFrame({ type: 'call', id: Infinity, global: 'tools', name: 'x', args: null })).toBeUndefined()
  87. // Plain zero and ordinary floats pass.
  88. expect(validateChildFrame({ type: 'call', id: 1, global: 'tools', name: 'x', args: [0, 1.5] }))
  89. .toEqual({ type: 'call', id: 1, global: 'tools', name: 'x', args: [0, 1.5] })
  90. })
  91. it('drops a CALL frame whose id is negative zero', () => {
  92. // `-0` passes Number.isFinite, but the reply re-serializes it as `0`
  93. // (JSON.stringify({id:-0}) === '{"id":0}'), so a forged `-0` id would
  94. // collide with a real call whose id is `0`. The honest child never sends it.
  95. expect(validateChildFrame({ type: 'call', id: -0, global: 'tools', name: 'x', args: null })).toBeUndefined()
  96. // Plain positive zero is a legitimate id and passes.
  97. expect(validateChildFrame({ type: 'call', id: 0, global: 'tools', name: 'x', args: null }))
  98. .toEqual({ type: 'call', id: 0, global: 'tools', name: 'x', args: null })
  99. })
  100. it('passes DONE values through untouched — losslessness is metered later', () => {
  101. // validateChildFrame no longer scans done.value: an unbounded scan would
  102. // push every member of a wide forged payload before any byte cap ran. The
  103. // done handler's checkDoneValue folds losslessness into the metered walk.
  104. expect(validateChildFrame({ type: 'done', value: Infinity })).toEqual({ type: 'done', value: Infinity })
  105. expect(validateChildFrame({ type: 'done', value: [{ x: -0 }] })).toEqual({ type: 'done', value: [{ x: -0 }] })
  106. expect(validateChildFrame({ type: 'done', value: [0, 1.5] })).toEqual({ type: 'done', value: [0, 1.5] })
  107. })
  108. })
  109. describe('lossless-number scan', () => {
  110. it('finds non-finite and negative-zero numbers at any depth, iteratively', () => {
  111. expect(hasNonLosslessNumber(Infinity)).toBe(true)
  112. expect(hasNonLosslessNumber(-Infinity)).toBe(true)
  113. expect(hasNonLosslessNumber(NaN)).toBe(true)
  114. expect(hasNonLosslessNumber(-0)).toBe(true)
  115. expect(hasNonLosslessNumber({ a: [1, { b: -0 }] })).toBe(true)
  116. expect(hasNonLosslessNumber({ a: [0, 1.5, 'x', null, true] })).toBe(false)
  117. // Deep nesting must not overflow the stack.
  118. let deep: unknown = 0
  119. for (let i = 0; i < 100000; i++) deep = [deep]
  120. expect(hasNonLosslessNumber(deep)).toBe(false)
  121. })
  122. it('walks wide arrays and objects one member at a time', () => {
  123. // `call.args` carries no seam byte cap, so a wide forged payload has no
  124. // budget to be rejected against — the walk must hold one cursor per
  125. // NESTING LEVEL, not one entry per member, or a flat payload just below
  126. // the 256 MiB frame ceiling would allocate tens of millions of stack
  127. // entries (and `Object.values` a second full-breadth copy). Observable
  128. // through the boundary: a wide payload whose per-member cost the old shape
  129. // would have paid still scans, and a violation ANYWHERE in it is found
  130. // wherever it sits.
  131. const wideArray = new Array(2_000_000).fill(0) as unknown[]
  132. expect(hasNonLosslessNumber(wideArray)).toBe(false)
  133. // Last element, so the cursor must run the whole breadth lazily.
  134. wideArray[wideArray.length - 1] = -0
  135. expect(hasNonLosslessNumber(wideArray)).toBe(true)
  136. const wideObject: Record<string, unknown> = {}
  137. for (let i = 0; i < 200_000; i++) wideObject[`k${i}`] = i
  138. expect(hasNonLosslessNumber(wideObject)).toBe(false)
  139. wideObject.last = Infinity
  140. expect(hasNonLosslessNumber(wideObject)).toBe(true)
  141. // Interleaved nesting: a per-level cursor must resume its parent after a
  142. // child level ends, so a violation after a nested container is still seen.
  143. expect(hasNonLosslessNumber([[1], { a: 2 }, NaN])).toBe(true)
  144. })
  145. it('scans only own enumerable properties', () => {
  146. // The per-level cursor filters own keys (a prototype-carrying frame is
  147. // impossible off JSON.parse, but the filter is what keeps the walk equal
  148. // to what the encoder would serialize).
  149. const withProto = Object.create({ inherited: -0 }) as Record<string, unknown>
  150. withProto.own = 1
  151. expect(hasNonLosslessNumber(withProto)).toBe(false)
  152. })
  153. })
  154. describe('unsafe-integer token scan', () => {
  155. it('flags integer tokens outside the safe range, skipping strings and float forms', () => {
  156. expect(hasUnsafeIntegerToken('{"v":9007199254740993}')).toBe(true)
  157. // Exact beyond-safe-range tokens are lossless and pass (2**53, 2**64).
  158. expect(hasUnsafeIntegerToken('{"v":9007199254740992}')).toBe(false)
  159. expect(hasUnsafeIntegerToken('{"v":18446744073709551616}')).toBe(false)
  160. // A token that parses to Infinity is trivially lossy.
  161. expect(hasUnsafeIntegerToken(`{"v":${'9'.repeat(400)}}`)).toBe(true)
  162. expect(hasUnsafeIntegerToken('{"v":-9007199254740993}')).toBe(true)
  163. expect(hasUnsafeIntegerToken('{"v":9007199254740991}')).toBe(false)
  164. expect(hasUnsafeIntegerToken('{"v":"9007199254740993"}')).toBe(false)
  165. expect(hasUnsafeIntegerToken(String.raw`{"v":"esc\"9007199254740993"}`)).toBe(false)
  166. expect(hasUnsafeIntegerToken('{"v":9007199254740993.0}')).toBe(false)
  167. expect(hasUnsafeIntegerToken('{"v":9e99}')).toBe(false)
  168. })
  169. })
  170. describe('checkDoneValue', () => {
  171. it('matches the exact encoded size and rejects one byte over', () => {
  172. const cases: unknown[] = [null, true, false, 0, -1.5, 'a"b\\', [], {}, [1, 'x', null], { a: [1, 2], b: { c: 'd' } }]
  173. for (const value of cases) {
  174. const exact = Buffer.byteLength(JSON.stringify(value), 'utf8')
  175. expect(checkDoneValue(value, exact), JSON.stringify(value)).toEqual({ ok: true, bytes: exact })
  176. expect(checkDoneValue(value, exact - 1), JSON.stringify(value)).toEqual({ ok: false, reason: 'over-budget' })
  177. expect(encodeJsonPlain(value)).toBe(JSON.stringify(value))
  178. }
  179. })
  180. it('stops early on a huge value instead of measuring it whole', () => {
  181. const huge = { data: 'x'.repeat(1_000_000), tail: 'y' }
  182. expect(checkDoneValue(huge, 1024)).toEqual({ ok: false, reason: 'over-budget' })
  183. // A forged flat array below the frame ceiling must fail BEFORE its
  184. // elements are enqueued — the pre-enqueue bound keeps the walk O(cap).
  185. const flat = new Array(10_000_000).fill(0)
  186. expect(checkDoneValue(flat, 1024)).toEqual({ ok: false, reason: 'over-budget' })
  187. // Same bound for a wide object: braces+commas fit the cap, but the
  188. // per-entry lower bound (quoted key + colon + value) does not, so it fails
  189. // before any key is metered or any value enqueued.
  190. const wide: Record<string, number> = {}
  191. for (let i = 0; i < 10; i++) wide[`k${i}`] = i
  192. expect(checkDoneValue(wide, 12)).toEqual({ ok: false, reason: 'over-budget' })
  193. // A forged object with millions of keys and a small cap must reject in
  194. // O(cap): the key COUNT loop itself bails once the running minimum encoding
  195. // (braces + 4 bytes/entry + commas) crosses the budget, rather than walking
  196. // the whole breadth before checking. Observable as a bounded key subset:
  197. // build a Proxy whose ownKeys would yield far more than the cap admits and
  198. // assert the metered walk never enumerates past it.
  199. let enumerated = 0
  200. const millionKeys = new Proxy({}, {
  201. ownKeys() { return Array.from({ length: 2_000_000 }, (_unused, i) => `k${i}`) },
  202. getOwnPropertyDescriptor() { enumerated += 1; return { enumerable: true, configurable: true, value: 0 } },
  203. })
  204. expect(checkDoneValue(millionKeys, 64)).toEqual({ ok: false, reason: 'over-budget' })
  205. // With cap 64, at most ~16 entries (4 bytes each) can fit before the bound
  206. // trips, so the walk enumerates far fewer than the 2,000,000 declared keys.
  207. expect(enumerated).toBeLessThan(1000)
  208. })
  209. it('rejects an over-budget string on its length before escaping it', () => {
  210. // A control-heavy forged string escapes to ~6x its length; the walk must
  211. // refuse it on the cheap `length + 2` lower bound so the escaped copy is
  212. // never allocated. Observable through the boundary: a string whose LENGTH
  213. // already exceeds the cap fails even though every character is 1 byte.
  214. expect(checkDoneValue('�'.repeat(4096), 1024)).toEqual({ ok: false, reason: 'over-budget' })
  215. // The bound is a lower bound, never a false rejection: a string that fits
  216. // exactly still passes with its exact escaped size.
  217. expect(checkDoneValue('�', 8)).toEqual({ ok: true, bytes: 8 })
  218. expect(checkDoneValue('�', 7)).toEqual({ ok: false, reason: 'over-budget' })
  219. // Same lower bound for keys, checked before the key is escaped.
  220. expect(checkDoneValue({ ['�'.repeat(4096)]: 1 }, 1024)).toEqual({ ok: false, reason: 'over-budget' })
  221. })
  222. it('meters only own enumerable keys', () => {
  223. // The walk counts keys with a `for...in` + hasOwn pass rather than
  224. // Object.keys/entries (which allocate per member before the bound). A
  225. // prototype-carrying forgery is impossible off JSON.parse, but the own-key
  226. // filter is what keeps the count equal to the encoder's.
  227. const withProto = Object.create({ inherited: 'x' }) as Record<string, unknown>
  228. withProto.own = 1
  229. expect(checkDoneValue(withProto, 1024)).toEqual({ ok: true, bytes: Buffer.byteLength('{"own":1}', 'utf8') })
  230. })
  231. it('rejects non-finite and negative-zero numbers at any depth as non-lossless', () => {
  232. expect(checkDoneValue(Infinity, 1024)).toEqual({ ok: false, reason: 'non-lossless' })
  233. expect(checkDoneValue(-Infinity, 1024)).toEqual({ ok: false, reason: 'non-lossless' })
  234. expect(checkDoneValue(NaN, 1024)).toEqual({ ok: false, reason: 'non-lossless' })
  235. expect(checkDoneValue(-0, 1024)).toEqual({ ok: false, reason: 'non-lossless' })
  236. expect(checkDoneValue({ a: [1, { b: -0 }] }, 1024)).toEqual({ ok: false, reason: 'non-lossless' })
  237. // An ordinary finite value within budget passes with its exact byte count.
  238. const clean = { a: [0, 1.5, 'x', null, true] }
  239. expect(checkDoneValue(clean, 1024)).toEqual({ ok: true, bytes: Buffer.byteLength(JSON.stringify(clean), 'utf8') })
  240. })
  241. it('meters deep nesting iteratively without overflowing the stack', () => {
  242. let deep: unknown = 0
  243. for (let i = 0; i < 100_000; i++) deep = [deep]
  244. // 100000 '[' + '0' + 100000 ']' = 200001 bytes.
  245. expect(checkDoneValue(deep, 1_000_000)).toEqual({ ok: true, bytes: 200_001 })
  246. })
  247. it('emits exact digits for beyond-safe integral doubles', () => {
  248. // String(2**60) prints the ROUNDED ...847000; echoing that to the child
  249. // would change the integer. BigInt digits give the exact ...846976.
  250. const v = JSON.parse('[1152921504606846976]') as unknown
  251. expect(encodeJsonPlain(v)).toBe('[1152921504606846976]')
  252. expect(checkDoneValue(v, 100)).toEqual({ ok: true, bytes: Buffer.byteLength('[1152921504606846976]', 'utf8') })
  253. })
  254. })