View Issue Details

IDProjectCategoryView StatusLast Update
0012337Talerwallet (iOS App)public2026-11-26 17:26
Reporterbot-cg [agent]  
PrioritynormalSeverityminor 
Status new 
Summary0012337: HTTP bridge: no limit on the size of an answer -- a one-gigabyte reply to a payment service's /config costs 3.4 GB of memory and ten seconds before the usual error (patch attached)
DescriptionNothing between the network and wallet-core limits the size of an answer.
A server that replies to the wallet's first request with one gigabyte
makes the app hold more than three gigabytes and keeps wallet-core busy
for ten seconds, before the usual error is shown.

Measured (iPhone 17 simulator, iOS 27.2, master 16f6f629)
---------------------------------------------------------
Settings > Payment Services > "+", http://localhost:8124/ , Add -- against
a server that answers GET .../config with "Content-Length: 1000000000" and
a body of that length (a JSON string of x's), complete 3 s after the
request. The app's resident memory was sampled twice a second.

    GNU Taler 1.6.19 memory of the app
    18:23:57.446 request sent 0.49 GB
    18:23:59 body mostly received 1.49 GB
    18:24:00.562 answer handed to the JS thread
    18:24:01 2.52 GB
    18:24:04.856 wallet-core: 7002 "Response invalid"
    18:24:06 (highest sample) 3.41 GB
    18:24:07.113 the app: "addExchange failed after 9659 ms"
    18:24:08 0.51 GB

Taler Nightly gave the same picture (0.49 -> 3.41 GB, "failed after
10188 ms"). With 256 MB the answer was parsed for 1.2 s and ended the
same way.

The simulator has no memory limit, so the app survives and shows "Network
problem / Response invalid" (picture attached, left). NOT VERIFIED on a
device: a phone ends an app that grows like this, and I could not try
that here.

Where the copies are made
-------------------------
* TalerWallet1/Quickjs/QuickDataTask.swift:129 -- the request is a
  URLSession data task with a completion handler, so URLSession collects
  the whole body in memory before anything sees it (1 GB).
* quickjs-tart (3f58047) quickjs/quickjs-libc.c:2426-2436,
  handle_http_resp -- the body is copied for the JS thread:
  malloc(body_len) + memcpy (2 GB; it is this copy that a cancel has to
  wait for, QuickDataTask.swift:158-185).
* quickjs/quickjs-libc.c:3267 -- JS_NewArrayBufferCopy(ctx, msg->body,
  msg->body_len): the JS value is a third copy.
* wallet-core then makes text of it and parses it.

None of the four looks at the size, and neither does wallet-core's
request code for this request (the answer was read to the end and then
judged invalid).

Why it matters
--------------
Here the address was typed by the user. The same bridge carries every
request wallet-core makes, so by the code any server the wallet is sent
to can do this -- a payment service, a merchant or a bank named in a
taler:// link or a QR code. NOT TESTED through a link. The largest
answers I know to be legitimate are the /keys of a payment service:
1.2 MB at exchange.demo.taler.net and 2.6 MB at exchange.taler-ops.ch
today.

Proposed fix (http-bridge-response-size-limit-v16f6f629.diff, against 16f6f629)
-----------------------------------------------------------------------------
QuickDataTask watches the task's byte counts (key-value observation of
countOfBytesReceived) and cancels a transfer that announces, or has
already brought, more than a limit -- 64 MB in the patch, which is a
suggestion. The request then fails with NSURLErrorDataLengthExceedsMaximum
and the text "Response larger than 64 MB".

Built and run with the same server and steps (GNU Taler 1.6.19):

    18:25:04.602 request sent 0.49 GB
    18:25:04.625 wallet-core: 7003 "HTTP request failed: Response
                  larger than 64 MB" (the server logs a broken pipe
                                              5 ms after the request)
    18:25:04.639 the app: "addExchange failed after 39 ms"
    18:25:06 (highest sample) 0.50 GB

The user sees "Network problem / HTTP request failed: Response larger
than 64 MB" (picture, right).

The patch does not depend on the one in 0012335 and does not conflict with
it; both were in the tree for this run. A limit inside quickjs-tart or
wallet-core would cover the other platforms as well -- I have only looked
at the iOS bridge.

To reproduce: late_answer_server.py.txt (attached) is the server:
    python3 late_answer_server.py 8124 200 1000000000 3000
answers every request with a body of 1000000000 bytes, the last byte
3000 ms after the request.

Found while arranging a cancel during a response callback
(QuickDataTask.swift:172) for a fixed test: the callback's copy had to be
made long, and nothing objected to a gigabyte.
TagsNo tags attached.
Attached Files
http-bridge-response-size-limit-v16f6f629.diff (2,253 bytes)   
--- a/TalerWallet1/Quickjs/QuickDataTask.swift	2026-11-26 18:21:11.765079709 +0100
+++ b/TalerWallet1/Quickjs/QuickDataTask.swift	2026-11-26 18:21:11.773079719 +0100
@@ -81,6 +81,14 @@
 }
 // MARK: -
 final class QuickDataTask: NSObject, @unchecked Sendable {
+    /// The largest answer that is handed on to wallet-core.  Without a limit an answer of any
+    /// size is held in memory several times over -- by URLSession, by the copy made for the
+    /// JS thread, by the JS value made from that -- and wallet-core is busy with it for
+    /// seconds: one gigabyte was measured as 3.4 GB resident.
+    static let maxResponseBytes: Int64 = 64 * 1024 * 1024
+    private var sizeObservation: NSKeyValueObservation?
+    private var isTooLarge = false
+
     let urlSession: URLSession
     let request: URLRequest
     let requestID: Int32
@@ -134,6 +142,18 @@
                               url: url)
         }
 
+        // Stop a transfer that announces, or has already brought, more than the limit.
+        sizeObservation = task.observe(\.countOfBytesReceived) { [weak self] task, _ in
+            guard let self else { return }
+            if task.countOfBytesReceived > QuickDataTask.maxResponseBytes
+                || task.countOfBytesExpectedToReceive > QuickDataTask.maxResponseBytes {
+                self.state.lock()
+                self.isTooLarge = true
+                self.state.unlock()
+                task.cancel()
+            }
+        }
+
         state.lock()
         guard !isFinished else {
             state.unlock()
@@ -195,6 +215,17 @@
         }
         defer { endCallback() }
 
+        state.lock()
+        let tooLarge = isTooLarge
+        state.unlock()
+        if tooLarge {
+            let megabytes = QuickDataTask.maxResponseBytes >> 20
+            deliver(error: NSError(domain: NSURLErrorDomain,
+                                     code: NSURLErrorDataLengthExceedsMaximum,
+                                 userInfo: [NSLocalizedDescriptionKey: "Response larger than \(megabytes) MB"]))
+            return
+        }
+
         if let response = response as? HTTPURLResponse {
             deliver(response: response, data: data ?? Data(), method: method, url: url)
         } else {
late_answer_server.py.txt (4,401 bytes)   
#!/usr/bin/env python3
"""A server whose answer is complete at a chosen moment, and large.

    python3 scripts/late_answer_server.py [port] [seconds] [body-bytes] [delay-ms ...]

Every request is answered at once with the headers of a `body-bytes` long
answer and all of it but the last byte.  The last byte follows `delay-ms`
after the request arrived -- the first request gets the first delay, the
second the second, and the last delay is used for all further ones.  A delay
of 0 means "never": the connection is held until the server stops, which is
how to measure a client's own time-out.

Why (QuickDataTask.swift:158-185): the wallet's HTTP bridge lets a cancel wait
for a response callback that has already started.  wallet-core cancels a
request when its time-out fires; the callback copies the body twice
(quickjs-libc.c handle_http_resp: malloc + memcpy), which for a small answer
takes microseconds -- one nightly walk in 785 met the two at once, on a bank
long-poll answered in the instant it was cancelled.  With a few hundred
megabytes the copy takes a tenth of a second, and an answer completed that
much before the time-out is being delivered when the cancel arrives.

Log (arrival and last byte, with milliseconds): /tmp/late-answer.log.
`LATE_BIND` sets the address to listen on (default 127.0.0.1).
"""
from __future__ import annotations

import datetime
import os
import socket
import sys
import threading
import time

LOG = "/tmp/late-answer.log"


def log(msg: str) -> None:
    stamp = datetime.datetime.now().strftime("%H:%M:%S.%f")[:-3]
    with open(LOG, "a") as f:
        f.write(f"{stamp} {msg}\n")


def serve(conn: socket.socket, nbytes: int, delay_ms: int, deadline: float) -> None:
    try:
        conn.settimeout(10)
        req = b""
        while b"\r\n\r\n" not in req and len(req) < 65536:
            chunk = conn.recv(4096)
            if not chunk:
                break
            req += chunk
        arrived = time.monotonic()
        first = req.split(b"\r\n", 1)[0].decode("latin-1", "replace")
        log(f"request: {first}; {nbytes} bytes, last byte "
            + (f"after {delay_ms} ms" if delay_ms else "never"))
        conn.settimeout(None)
        conn.sendall(b"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\n"
                     + f"Content-Length: {nbytes}\r\nConnection: close\r\n\r\n".encode())
        # A JSON string, so that what is delivered is at least well-formed.
        left = nbytes - 1
        conn.sendall(b'"')
        left -= 1
        block = b"x" * (1 << 20)
        while left > 0:
            n = min(left, len(block))
            conn.sendall(block[:n])
            left -= n
        log(f"all but the last byte sent after {int((time.monotonic() - arrived) * 1000)} ms")
        if delay_ms:
            wait = arrived + delay_ms / 1000.0 - time.monotonic()
            if wait > 0:
                time.sleep(wait)
            conn.sendall(b'"')
            log(f"last byte sent {int((time.monotonic() - arrived) * 1000)} ms after the request")
            time.sleep(2.0)
        else:
            while time.monotonic() < deadline:
                time.sleep(0.5)
    except OSError as e:
        log(f"connection ended: {e}")
    finally:
        try:
            conn.close()
        except OSError:
            pass


def main() -> int:
    port = int(sys.argv[1]) if len(sys.argv) > 1 else 8124
    seconds = float(sys.argv[2]) if len(sys.argv) > 2 else 240.0
    nbytes = int(sys.argv[3]) if len(sys.argv) > 3 else 64
    delays = [int(a) for a in sys.argv[4:]] or [0]
    bind = os.environ.get("LATE_BIND", "127.0.0.1")
    srv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    srv.bind((bind, port))
    srv.listen(8)
    srv.settimeout(1.0)
    deadline = time.monotonic() + seconds
    log(f"listening on {bind}:{port} for {int(seconds)} s; body {nbytes}; delays {delays}")
    served = 0
    while time.monotonic() < deadline:
        try:
            conn, _ = srv.accept()
        except socket.timeout:
            continue
        delay = delays[min(served, len(delays) - 1)]
        served += 1
        threading.Thread(target=serve, args=(conn, nbytes, delay, deadline),
                         daemon=True).start()
    srv.close()
    log("stopped")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
late_answer_server.py.txt (4,401 bytes)   

Required notifications

Address or linkRemarkAdded byNotifiedActions

Activities

Issue History

Date ModifiedUsernameFieldChange
2026-11-26 17:26bot-cgNew Issue
2026-11-26 17:26bot-cgImplementer => MarcS
2026-11-26 17:26bot-cgReviewer => vlada.svirsh
2026-11-26 17:26bot-cgRelease signed by => MarcS
2026-11-26 17:26bot-cgDeployed by => MarcS
2026-11-26 17:26bot-cgVerifier => vlada.svirsh
2026-11-26 17:26bot-cgCommunicator => CM_7
2026-11-26 17:26bot-cgFile Added: http-bridge-size-limit-before-after.jpg
2026-11-26 17:26bot-cgFile Added: http-bridge-response-size-limit-v16f6f629.diff
2026-11-26 17:26bot-cgFile Added: late_answer_server.py.txt