Split the S3 keys of the API and the reconciler, drop root from one-offs

The API key now has only GetObject, PutObject and DeleteObject on the
attachment objects: the server never lists the bucket, never runs
multipart uploads and has its region set. The reconciler gets its own
user messenger-reconciler with ListBucket, GetObject and DeleteObject,
created by s3-init from a secret of its own, so the API replicas can no
longer list the bucket. The cost seeding writes objects and therefore
runs in a one-off API container under the API key. s3-check proves the
API key cannot list and checks the reconciler key; its snapshot drops
dated fields with a JSON filter instead of grep, which left a dangling
comma, and its first line carries the date and the commit.

s3-init and s3-cli run as uid 65534, and migrate and reconciler get an
init process, so SIGTERM reaches python and docker stop ends a pass in
a fraction of a second instead of waiting for SIGKILL. limits.py and CI
check the users of the one-off services. Stack tests move a 3 MiB file
up and down through the balancer at 256 and 192 KiB/s, longer than the
request timeout, and check 401 before the declared size.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01V1d3RLHNBBMA6UqBLLJv27
This commit is contained in:
Artyom
2026-10-30 08:53:39 +03:00
co-authored by Claude Opus 5.5
parent 54099e1da3
commit 2891b37e75
13 changed files with 234 additions and 48 deletions
+106 -2
View File
@@ -134,14 +134,23 @@ def replica_at(address: str) -> str:
def raw(
path: str, headers: dict[str, str], body: bytes, *, hang_up: bool
path: str,
headers: dict[str, str],
body: bytes,
*,
hang_up: bool,
piece: int = 0,
delay: float = 0.0,
) -> tuple[int, dict[str, Any], float]:
parts = urlsplit(BASE_URL)
head = f"POST {path} HTTP/1.1\r\nHost: {parts.netloc}\r\nConnection: close\r\n"
head += "".join(f"{name}: {value}\r\n" for name, value in headers.items()) + "\r\n"
started = time.perf_counter()
with socket.create_connection((parts.hostname, parts.port or 80), timeout=30) as sock:
sock.sendall(head.encode("latin-1") + body)
sock.sendall(head.encode("latin-1"))
for start in range(0, len(body), piece or max(len(body), 1)):
sock.sendall(body[start : start + (piece or len(body))])
time.sleep(delay)
if hang_up:
return 0, {}, 0.0
response = HTTPResponse(sock)
@@ -149,6 +158,56 @@ def raw(
return response.status, json.loads(response.read()), time.perf_counter() - started
READER = """
import hashlib, http.client, sys, time
path, token, request_id, piece, delay = sys.argv[1:6]
connection = http.client.HTTPConnection("lb", 8080, timeout=30)
headers = {"Authorization": "Bearer " + token, "X-Request-Id": request_id}
connection.request("GET", path, headers=headers)
response, digest, started = connection.getresponse(), hashlib.sha256(), time.monotonic()
while chunk := response.read(int(piece)):
digest.update(chunk)
time.sleep(float(delay))
print(response.status, digest.hexdigest(), round(time.monotonic() - started, 2))
"""
def slow_read(path: str, token: str, request_id: str, piece: int, delay: float) -> list[str]:
template = "{{range $name, $_ := .NetworkSettings.Networks}}{{$name}} {{end}}"
networks = subprocess.run(
["docker", "inspect", "-f", template, compose("ps", "-q", "lb")],
check=True,
capture_output=True,
text=True,
).stdout.split()
image = subprocess.run(
["docker", "inspect", "-f", "{{.Config.Image}}", compose("ps", "-q", "api").split()[0]],
check=True,
capture_output=True,
text=True,
).stdout.strip()
command = [
"docker",
"run",
"--rm",
"--network",
next(name for name in networks if name.endswith("_edge")),
"--sysctl",
"net.ipv4.tcp_rmem=4096 16384 65536",
"--entrypoint",
"python",
image,
"-c",
READER,
path,
token,
request_id,
str(piece),
str(delay),
]
return subprocess.run(command, check=True, capture_output=True, text=True).stdout.split()
@pytest.fixture
async def http() -> AsyncIterator[AsyncClient]:
async with AsyncClient(base_url=BASE_URL, timeout=30, trust_env=False) as client:
@@ -466,3 +525,48 @@ async def test_stalled_upload_is_cut_and_leaves_nothing(http: AsyncClient, fault
assert elapsed <= REQUEST_TIMEOUT + 2
assert seen(name) is None
assert (await upload(http, s["alice"], s["chats"][0])).status_code == 201
async def test_token_is_checked_before_the_declared_size(http: AsyncClient) -> None:
s = await scene(http)
headers = {"Content-Type": "image/png", "Content-Length": str(LIMIT + 1)}
path = f"/api/v1/chats/{s['chats'][0]}/attachments?filename=a.png"
status, body, _ = await asyncio.to_thread(raw, path, headers, SAMPLE[:1024], hang_up=False)
print(f"без токена, Content-Length {LIMIT + 1}: {status} {body['error']['code']}")
assert (status, body["error"]["code"]) == (401, "unauthorized")
async def test_slow_but_steady_transfers_outlive_the_request_timeout(http: AsyncClient) -> None:
since = moment()
s = await scene(http)
picture = png(16, 16, size=3 << 20)
sent, read = f"slow-upload-{uuid4().hex}", f"slow-download-{uuid4().hex}"
headers = {
**bearer(s["alice"]),
"Content-Type": "image/png",
"Content-Length": str(len(picture)),
"X-Request-Id": sent,
}
path = f"/api/v1/chats/{s['chats'][0]}/attachments?filename=slow.png"
status, body, up = await asyncio.to_thread(
raw, path, headers, picture, hang_up=False, piece=64 << 10, delay=0.25
)
assert status == 201, body
assert body["sha256"] == sha256(picture).hexdigest()
content = f"/api/v1/attachments/{body['id']}/content"
code, digest, down = await asyncio.to_thread(slow_read, content, s["bob"], read, 64 << 10, 0.33)
assert (code, digest) == ("200", body["sha256"])
def handled() -> dict[str, tuple[int, float]]:
return {
e["request_id"]: (e["status"], e["duration_ms"] / 1000)
for e in logs(since)
if e.get("event") == "request.handled" and e.get("request_id") in (sent, read)
}
await waited(lambda: len(handled()) == 2, 15)
replica = handled()
print(f"upload 3 MiB ≈ 256 KiB/s: клиент {up:.1f} с, реплика {replica[sent]}")
print(f"скачивание 3 MiB ≈ 192 KiB/s из сети edge: клиент {down} с, реплика {replica[read]}")
assert replica[sent][0] == 201 and replica[sent][1] > REQUEST_TIMEOUT
assert replica[read][0] == 200 and replica[read][1] > REQUEST_TIMEOUT