fix(gateway): hold unsettled text out of every streamed frame, split and seal

The first streamed-redaction pass held back only the trailing whitespace token, and only for
the seal path. The first-send splitter still hard-cut inside it, a multi-token secret
(Authorization + scheme + token, a PEM block) was sealed at an inner space or newline, and
preview/draft frames showed each partial key: first raw below the pattern floor, then as a
head/tail mask whose window slides as the key grows. On stream-is-the-message drafts every
re-mask is a non-prefix frame, so the connector re-appends it.

gateway/stream_consumer_redact.py computes a settled boundary. Text after it could still be,
or still complete, a secret: a trailing token that a secret prefix or a probed continuation
would mask, an auth/credential label with its value still open, a BEGIN block with no END, a
PuTTY body, a control-split run. Frames, sealed heads and both splitters stop at that
boundary. The settled text is redacted in place, and each tick only redacts the newly settled
text plus the start of its line, so redaction cost is linear. Before, the whole buffer was
redacted 2-3x per tick, which was quadratic. Turn/segment ends and finalize frames are still
redacted whole.

Fixes #56039
This commit is contained in:
Maciej Lisiewski
2026-11-11 22:37:38 +01:00
parent 971e15cd6d
commit efcf4e1bee
4 changed files with 363 additions and 39 deletions

View File

@@ -35,6 +35,7 @@ from gateway.response_filters import (
strip_trailing_silence_marker as _strip_trailing_silence_marker)
from gateway.stream_consumer_directives import has_pending_media_directive, strip_image_tags_for_display
from gateway.stream_consumer_fences import ensure_closed_code_fences
from gateway.stream_consumer_redact import redact_settled
from gateway.stream_consumer_transport import StreamTransportMixin
from gateway.stream_consumer_fallback import StreamFallbackMixin
from gateway.stream_consumer_think import StreamThinkFilterMixin
@@ -204,6 +205,8 @@ class GatewayStreamConsumer(StreamTransportMixin, StreamFallbackMixin, StreamThi
# ``_stream_ledger`` mirrors ``_accumulated`` but is NOT truncated when
# overflow splits seal head chunks (reconcilable turn-final payload).
self._accumulated = self._stream_ledger = ""
self._redacted_prefix = "" # settled, redacted head of _accumulated (see redact_settled)
self._settled_for = "" # the _accumulated _redacted_prefix was computed for
self._last_sent_text = "" # skip redundant edits
self._fallback_final_send = False
self._fallback_prefix = ""
@@ -263,10 +266,10 @@ class GatewayStreamConsumer(StreamTransportMixin, StreamFallbackMixin, StreamThi
if line:
self._queue.put((_TOOL_PROGRESS, line))
def _compose_frame_content(self) -> str:
"""Native frame content: text, with any tool-progress lines below a rule."""
progress = "\n".join(self._tool_progress_lines)
return "\n\n---\n".join(p for p in (self._accumulated, progress) if p)
def _compose_frame_content(self, text: str) -> str:
"""Native frame content: ``text`` (already redacted), with any tool-progress lines below a rule."""
progress = _redact_for_egress("\n".join(self._tool_progress_lines))
return "\n\n---\n".join(p for p in (text, progress) if p)
def _metadata_for_send(self, *, final: bool = False, expect_edits: bool = False) -> dict | None:
"""Per-send metadata. ``final`` → notify=True (Mattermost treats notify-worthy sends
@@ -616,7 +619,8 @@ class GatewayStreamConsumer(StreamTransportMixin, StreamFallbackMixin, StreamThi
# is split again below. A plain first send would let the adapter split it and
# adopt only the LAST chunk as the preview; the next seal then overwrites that
# chunk with the head of the whole remainder (duplicated + lost text, #25349).
sent_heads = await self._seal_overflow_heads(final=tick.got_done)
sent_heads = await self._seal_overflow_heads(
final=tick.got_done, done=self._tick_ends_text(tick))
if sent_heads and self._turn_reset(): # the sealing edit awaited: no split for a dead turn
await self._abandon_native_stream()
return
@@ -833,12 +837,15 @@ class GatewayStreamConsumer(StreamTransportMixin, StreamFallbackMixin, StreamThi
# Likewise defer while a MEDIA:/[[…]] directive is still being typed: the cleaner
# only strips complete deliverable tags, so a half-streamed one would be shown, and
# a media-only reply cleans to "" at finish, which never edits the bubble away.
cleaned = self._clean_for_display(self._accumulated)
cleaned = self._display_text(self._accumulated)
# The frame is the settled prefix: it can end inside a directive the buffer has completed.
settled = self._redact_settled_text(done=False)
frame = self._display_text(self._accumulated[:settled])
return (should_edit and not _is_partial_silence_marker(cleaned)
# Raw buffer: the cleaner already drops a COMPLETE trailing marker, but an interim
# frame carries the cursor after it, which hides the marker from the cleaner.
and not _ends_with_partial_silence_marker(self._accumulated)
and not has_pending_media_directive(cleaned))
and not has_pending_media_directive(cleaned) and not has_pending_media_directive(frame))
async def _split_first_send(self, tick: _Tick) -> bool:
"""No message to edit yet and the buffer overflows: seal only the head chunks; the
@@ -846,11 +853,19 @@ class GatewayStreamConsumer(StreamTransportMixin, StreamFallbackMixin, StreamThi
True when the turn finished here (the run loop returns)."""
if (handed_off := await self._ceiling_split_first_send(tick)) is not None:
return handed_off
self._redact_settled_text(done=tick.got_done)
chunks = self._truncate_for_stream(self._accumulated, self._safe_limit, self._len_fn)
if len(chunks) <= 1:
# Malformed/legacy adapter result must still be splittable.
chunks = self._split_text_chunks(self._accumulated, self._safe_limit, self._len_fn)
settled = self._redact_settled_text(done=self._tick_ends_text(tick))
# Only settled text is split: the held tail rides on as the live preview, so no head is
# sealed with a key (or a label whose value is still arriving) cut in two (#56039).
head, held = self._accumulated[:settled], self._accumulated[settled:]
if not head.strip():
return False # nothing settled yet: wait for the held text to complete
if self._len_fn(head) > self._safe_limit:
chunks = self._truncate_for_stream(head, self._safe_limit, self._len_fn)
if len(chunks) <= 1:
# Malformed/legacy adapter result must still be splittable.
chunks = self._split_text_chunks(head, self._safe_limit, self._len_fn)
else:
chunks = [head, ""] # the held tail is what overflows: seal the settled text whole
reply_to = self._initial_reply_to_id
heads_delivered = len(chunks) > 1
for index, chunk in enumerate(chunks[:-1]):
@@ -873,7 +888,7 @@ class GatewayStreamConsumer(StreamTransportMixin, StreamFallbackMixin, StreamThi
# preview later deltas extend, so a kept indicator ends up embedded mid-reply.
tail = chunks[-1]
indicator = f" ({len(chunks)}/{len(chunks)})"
self._accumulated = tail.removesuffix(indicator)
self._accumulated = tail.removesuffix(indicator) + held
# Flag BEFORE the tail send: fresh-final replaces every tracked preview
# with one message, which is only valid while the active message holds
# the whole answer — deleting sealed heads drops delivered text.
@@ -900,18 +915,22 @@ class GatewayStreamConsumer(StreamTransportMixin, StreamFallbackMixin, StreamThi
self._fallback_prefix = ""
return False
def _redact_settled_text(self, *, done: bool) -> int:
"""Redact the buffer before an overflow split; returns where the settled text ends.
def _tick_ends_text(self, tick: _Tick) -> bool:
"""No more text joins this message: the turn or segment ends, or commentary resets it."""
return (tick.got_done or tick.got_segment_break
or (tick.commentary_text is not None and not self._cumulative_transport()))
Split heads are sealed (never edited again) and a cut through a credential leaves halves
no pattern matches on its own, so the split must work on redacted text (#56039). The
token still arriving at the end of the buffer stays raw until a later delta completes it:
masking a partial key here would leave the rest of the key to be appended unmatched."""
text = self._accumulated
settled = len(text) if done else max(text.rfind(c) for c in " \t\n") + 1
if settled:
self._accumulated = _redact_for_egress(text[:settled]) + text[settled:]
return settled - (len(text) - len(self._accumulated)) if settled else 0
def _redact_settled_text(self, *, done: bool) -> int:
"""Redact _accumulated up to its settled boundary, in place; returns where that ends.
Every mid-stream egress (frames, sealed heads, split points) stops there: past it the
text may still be or complete a secret, which a pattern cannot see yet (#56039)."""
if not done and self._accumulated == self._settled_for:
return len(self._redacted_prefix) # several checks per tick, one scan
self._accumulated, settled = redact_settled(self._accumulated, self._redacted_prefix, done=done)
self._redacted_prefix = self._accumulated[:settled]
self._settled_for = "" if done else self._accumulated
return settled
def _overflows(self) -> bool:
return self._len_fn(self._accumulated) > self._safe_limit
@@ -919,22 +938,24 @@ class GatewayStreamConsumer(StreamTransportMixin, StreamFallbackMixin, StreamThi
def _first_send_overflows(self) -> bool:
return self._message_id is None and self._overflows()
async def _seal_overflow_heads(self, *, final: bool = False) -> bool:
async def _seal_overflow_heads(self, *, final: bool = False, done: bool = False) -> bool:
"""Existing message overflowing: seal it with the head, start a new message for the rest.
True when a head was sent; stops once /stop or /new invalidated the turn mid-seal."""
True when a head was sent; stops once /stop or /new invalidated the turn mid-seal.
``done``: no more text joins this message (``final`` implies it)."""
if final and self._ceiling_final_cut():
return False # the final edit would pass the reply's message cap: it goes out as a file
sent = False
while self._overflows() and self._message_id is not None and self._edit_supported:
if sent and self._turn_reset():
break
settled = self._redact_settled_text(done=False)
settled = self._redact_settled_text(done=done or final)
cp_budget = _custom_unit_to_cp(self._accumulated, self._safe_limit, self._len_fn)
split_at = self._accumulated.rfind("\n", 0, cp_budget)
if split_at < cp_budget // 2:
split_at = cp_budget
if 0 < settled < split_at:
split_at = settled # never seal the head of a token that is still arriving
split_at = min(split_at, settled) # never seal text that is not settled yet
if not self._accumulated[:split_at].strip():
break
if self._ceiling_seal_cut(split_at, final=final):
break # past the reply's message cap: it goes out as a file once complete
chunk = self._accumulated[:split_at]
@@ -952,11 +973,13 @@ class GatewayStreamConsumer(StreamTransportMixin, StreamFallbackMixin, StreamThi
return sent
async def _push_update(self, tick: _Tick) -> None:
"""Send/edit this tick's visible text (cursor-suffixed unless finalizing)."""
display_text = self._accumulated
"""Send/edit this tick's visible text (cursor-suffixed unless finalizing). Mid-segment
frames carry only the settled, redacted text (see _redact_settled_text)."""
settled = self._redact_settled_text(done=self._tick_ends_text(tick)) # rewrites _accumulated
display_text = self._accumulated[:settled]
if tick.is_interim:
if self._use_native_streaming:
display_text = self._compose_frame_content()
display_text = self._compose_frame_content(display_text)
if display_text and self.cfg.cursor:
display_text += self.cfg.cursor
else:
@@ -971,7 +994,7 @@ class GatewayStreamConsumer(StreamTransportMixin, StreamFallbackMixin, StreamThi
# answer.
tick.update_visible = await self._send_or_edit(
display_text, finalize=tick.got_done or tick.got_segment_break,
is_turn_final=tick.got_done)
is_turn_final=tick.got_done, redacted=True)
self._last_edit_time = time.monotonic()
# Lines stay in _tool_progress_lines for the next compose.
self._tool_progress_active = False
@@ -1122,5 +1145,11 @@ class GatewayStreamConsumer(StreamTransportMixin, StreamFallbackMixin, StreamThi
through here, so this is where streamed text gets the same forced secret redaction the
non-streamed final send applies in ``_sanitize_gateway_final_response`` (#56039).
"""
return _redact_for_egress(_strip_trailing_silence_marker(
strip_image_tags_for_display(_BasePlatformAdapter.strip_media_directives_for_display(text))))
return _redact_for_egress(GatewayStreamConsumer._display_text(text))
@staticmethod
def _display_text(text: str) -> str:
"""``_clean_for_display`` without the redaction: for per-tick checks and for frames
already redacted incrementally (``_redact_settled_text``)."""
return _strip_trailing_silence_marker(
strip_image_tags_for_display(_BasePlatformAdapter.strip_media_directives_for_display(text)))

View File

@@ -0,0 +1,133 @@
"""Streamed-egress secret redaction for GatewayStreamConsumer (#56039).
A streamed reply is redacted while it is still arriving, so a pattern can only be trusted on text
the redactor has seen in full context. Everything the consumer emits mid-stream (preview edits,
draft/native frames, sealed overflow heads, split points) therefore stops at a *settled* boundary:
text after it could still be, or still complete, a secret — the token being typed, an
``Authorization:``/``Bearer``/``password:`` label whose value has not arrived, an open quote after
such a label, a ``-----BEGIN`` block without its END, a PuTTY ``Private-Lines:`` body, a key
fragment the next line may continue. Withholding it keeps frames prefix-stable (a partial key is
never shown, then re-masked) and keeps a cut from separating a label from its value.
The settled text is redacted in place, incrementally: only the newly settled text plus a bounded
lookback is re-redacted per tick, so a long reply costs linear redaction work, not quadratic.
"""
from __future__ import annotations
import re
from agent.redact import _PREFIX_SUBSTRINGS, redact_for_egress
_TAIL_SCAN = 512 # how far back an open label/value can start
_BLOCK_SCAN = 16384 # how far back an open key block can start (an 8192-bit PEM is ~6.5 KB)
_LOOKBACK = 1024 # most settled text re-redacted with each newly settled chunk
# Continuations a still-arriving token is probed with: an opaque body (masked only when what came
# before makes it a key), and the separators that join one into a credential (``id.secret``,
# ``bot:token``, ``user@host``).
_PROBE = "Q7mZ2xW9rT4kL8vB3nH6pD1sF5gJ0cYa8Kd2LmP4"
_CONTINUATIONS = (_PROBE, "." + _PROBE, ":" + _PROBE, "-" + _PROBE, "_" + _PROBE, "@example.com/")
# Literal starts of secrets the prefix list does not carry (JWT, base64 PEM, age).
_LITERALS = tuple(lit for lit in (*_PREFIX_SUBSTRINGS, "eyJ", "LS0tLS1CRUdJTi", "AGE-SECRET-KEY-1") if lit)
_LITERAL_MAX = max(map(len, _LITERALS))
_NON_KEY_CHAR_RE = re.compile(r"[^A-Za-z0-9_\-]")
_KW = r"(?:key|token|secret|passw(?:or)?d|pass(?:phrase)?|pwd|pw|credentials?|auth\w*|cookie|sig\w*|bearer)"
_OPEN_VALUE = r"(?:\\?[\"'][^\"'\n]*|\S*)" # an open quoted value or a still-arriving token
_OPEN_TAIL_RE = re.compile(
rf"\b(?:proxy-)?authorization\s*(?::\s*(?:\S+[ \t]+)?\S*)?\Z" # header, scheme, credential
rf"|\bbearer\s*\S*\Z"
rf"|(?<![\w-])-{{1,2}}[\w-]*{_KW}[\w-]*(?:\s*=\s*|\s+){_OPEN_VALUE}\Z" # CLI flag + value
rf"|(?<![\w-])-p\s+\S*\Z" # docker login -p
rf"|(?<![\w.-])\\?[\"']?[\w.-]*{_KW}[\w.-]*\\?[\"']?\s*(?:[:=]\s*{_OPEN_VALUE})?\Z" # NAME[:=] value
rf"|\b(?:password|pwd)[ \t]*=[^\n]*\Z" # connection string: a later host=/user= masks it
rf"|\b(?:set-)?cookie:[ \t]*(?:[^\s;]+;[ \t]*)*\S*\Z",
re.IGNORECASE,
)
_PEM_END_RE = re.compile(r"-----END[A-Z0-9 ]*-----")
_PPK_OPEN_RE = re.compile(
r"Private-Lines:[ \t]*\d*[ \t]*"
r"(?:(?:\r?\n|\\r\\n|\\n)[ \t]*(?:\d+[|:\t][ \t]*)?[A-Za-z0-9+/=]*[ \t]*)*")
# A token run broken only by control/zero-width characters: the redactor joins it (#77484).
_CONTROL_SPLIT_RUN_RE = re.compile(
r"[A-Za-z0-9_.\-\x00-\x1f\u200b-\u200f\u2028-\u202f\u2060\ufeff]*"
r"[\x00-\x1f\u200b-\u200f\u2028-\u202f\u2060\ufeff]\Z")
def _token_may_be_secret(context: str, token: str) -> bool:
"""True when the trailing, still-arriving ``token`` is, or could grow into, a secret: it
holds a secret's literal start or ends in the beginning of one, is masked already, or is
masked once a continuation is appended."""
if any(lit in token for lit in _LITERALS):
return True
for i in range(max(0, len(token) - _LITERAL_MAX), len(token)):
if (not i or not token[i - 1].isalnum()) and any(lit.startswith(token[i:]) for lit in _LITERALS):
return True
base = redact_for_egress(context + token)
return (base != context + token and not base.endswith(token)) or any(
redact_for_egress(context + token + c) != base + c for c in _CONTINUATIONS)
def _probe_start(text: str, token_start: int) -> int:
"""Where to probe the trailing token from. A token longer than any secret (``....`` rules,
long paths) is probed from a character no key body holds, within _TAIL_SCAN of the end, so
a key still arriving is seen whole; -1 when there is none (an opaque blob: hold all of it)."""
n = len(text)
if n - token_start <= _TAIL_SCAN:
return token_start
m = _NON_KEY_CHAR_RE.search(text, n - _TAIL_SCAN, n)
return -1 if m is None else m.start()
def settled_end(text: str) -> int:
"""Index where the text that can no longer become part of a secret ends."""
n = len(text)
if not n:
return 0
end = n
token_start = max(text.rfind(c) for c in " \t\r\n") + 1
if token_start < n:
probe_start = _probe_start(text, token_start)
line_start = max(text.rfind("\n", 0, probe_start) + 1, probe_start - _TAIL_SCAN)
if probe_start < 0 or _token_may_be_secret(text[line_start:probe_start], text[probe_start:]):
end = token_start
if m := _OPEN_TAIL_RE.search(text, max(0, n - _TAIL_SCAN)):
end = min(end, m.start())
block_lo = max(0, n - _BLOCK_SCAN)
begin = text.rfind("-----BEGIN", block_lo)
if begin >= 0 and not _PEM_END_RE.search(text, begin):
end = min(end, begin)
ppk = text.rfind("Private-Lines:", block_lo)
if ppk >= 0 and _PPK_OPEN_RE.fullmatch(text, ppk):
end = min(end, ppk)
if (m := _CONTROL_SPLIT_RUN_RE.search(text, max(0, n - _TAIL_SCAN))) and m.start() < end:
run = m.group(0)
if redact_for_egress(run + _PROBE) != redact_for_egress(run) + _PROBE:
end = m.start()
return end
def _lookback_start(text: str, upto: int) -> int:
"""Where re-redaction restarts: the start of the line holding ``upto`` (line-anchored
patterns such as YAML keys and connection strings need it), at most _LOOKBACK back.
Multi-line candidates never reach back here: settled_end holds them until complete."""
lo = max(0, upto - _LOOKBACK)
newline = text.rfind("\n", lo, upto)
if newline >= 0 or lo == 0:
return newline + 1
return max(text.rfind(" ", 0, lo), text.rfind("\t", 0, lo)) + 1
def redact_settled(text: str, redacted_prefix: str, *, done: bool) -> tuple[str, int]:
"""Redact ``text`` up to its settled boundary (all of it when ``done``); returns the new text
and where its settled part ends. ``redacted_prefix`` is the settled part returned last time:
while ``text`` still starts with it, only the new text plus a bounded lookback is redacted."""
settled = len(text) if done else settled_end(text)
upto = min(settled, len(redacted_prefix)) if text.startswith(redacted_prefix) else 0
if upto == settled and redacted_prefix:
return text, settled
start = _lookback_start(text, upto)
if settled <= start:
return text, settled
redacted = redact_for_egress(text[start:settled])
return text[:start] + redacted + text[settled:], start + len(redacted)

View File

@@ -347,12 +347,13 @@ class StreamTransportMixin:
self._message_created_ts = None
@stops_reply_clock
async def _send_or_edit(
self, text: str, *, finalize: bool = False, is_turn_final: bool = True) -> bool:
async def _send_or_edit(self, text: str, *, finalize: bool = False, is_turn_final: bool = True,
redacted: bool = False) -> bool:
"""Send or edit the streaming message; True if delivered. ``finalize`` marks the
last edit. Transport order: native frame → draft frame → edit existing → first
send; a transport returns None to fall through to the next."""
text = self._clean_for_display(text)
send; a transport returns None to fall through to the next. ``redacted``: an interim
frame already redacted up to its settled boundary; a finalize is redacted whole regardless."""
text = self._display_text(text) if redacted and not finalize else self._clean_for_display(text)
# Stream-is-the-message draft frames must stay prefix-stable: a closing ```
# on a mid-code-block frame makes frame N not a prefix of N+1 and the
# connector re-appends the whole snapshot. The final is still fence-closed.

View File

@@ -0,0 +1,161 @@
"""Streamed egress never emits text past the settled boundary (#56039).
A secret still arriving — a key whose tail is in a later delta, ``Bearer`` before its token, a
PEM block before its END — must not be sealed into a split head, cut by a splitter, or shown in a
preview/draft frame, where a later re-mask cannot reach it. Assertions are on what the chat ends
up showing per message (sends + edits replayed), and on every frame the transport received.
"""
import asyncio
from itertools import pairwise
from types import SimpleNamespace
import pytest
from gateway.platforms.base import BasePlatformAdapter
from gateway.stream_consumer import GatewayStreamConsumer, StreamConsumerConfig
from tests.waiting import async_wait_until
_BODY = "Q7mZ2xW9rT4kL8vB3nH6pD1sF5gJ0cY"
_KEY = "sk-proj-" + _BODY
_TOKEN = "Zq8vN3mK1pX7wL4tR9yB2cF6hJ0dS5gAxx"
_AUTH = "Authorization: " + "Bearer "
_PEM_LINES = ("MIIEpAIBAAKCAQEA1x2y3z4abcdefghijklmnopqrstuvwxyz0123456789ABCD",
"QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm0123456789ab",
"ZXCVBNMasdfghjklQWERTYUIOP0987654321zyxwvutsrqponmlkjihgfedcbaXY")
_PEM_BEGIN, _PEM_END = "-----BEGIN RSA PRIVATE KEY-----", "-----END RSA PRIVATE KEY-----"
def _adapter(**attrs):
cls = type("ChatAdapter", (BasePlatformAdapter,), {"MAX_MESSAGE_LENGTH": 1000})
cls.__abstractmethods__ = frozenset()
adapter = cls.__new__(cls)
adapter._typing_paused = set()
adapter._fatal_error_message = None
adapter.ops = []
ids = iter(f"m{i}" for i in range(100))
async def send(**kw):
adapter.ops.append(("send", next(ids), kw["content"]))
return SimpleNamespace(success=True, message_id=adapter.ops[-1][1])
async def edit_message(**kw):
adapter.ops.append(("edit", kw["message_id"], kw["content"]))
return SimpleNamespace(success=True, message_id=kw["message_id"])
adapter.send, adapter.edit_message = send, edit_message
for name, value in attrs.items():
setattr(adapter, name, value)
return adapter
def _on_screen(adapter) -> dict[str, str]:
shown = {}
for _op, message_id, content in adapter.ops:
shown[message_id] = content
return shown
async def _stream(adapter, *deltas: str, **cfg) -> None:
consumer = GatewayStreamConsumer(adapter, "chat", StreamConsumerConfig(
edit_interval=0.01, buffer_threshold=5, cursor="", **cfg))
drains = []
drain = consumer._drain_queue
consumer._drain_queue = lambda: (drains.append(None), drain())[1]
task = asyncio.create_task(consumer.run())
for delta in deltas:
# One delta per tick: the next drain after the one that took this delta starts only
# once that tick is over (a held delta reaches no wire, so the wire is no signal).
consumer.on_delta(delta)
await async_wait_until(lambda: consumer._queue.empty(), timeout=5, what="delta drained")
seen = len(drains)
await async_wait_until(lambda: len(drains) > seen, timeout=5, what="tick done")
consumer.finish()
await task
def _raw_runs(texts, secret: str, width: int = 8) -> list[str]:
runs = {secret[i:i + width] for i in range(len(secret) - width + 1)}
return sorted({r for r in runs for t in texts if r in t})
@pytest.mark.asyncio
@pytest.mark.parametrize("pad", [880, 885, 890, 893])
async def test_first_send_split_does_not_hard_cut_a_key_still_arriving(pad):
adapter = _adapter()
await _stream(adapter, "/" * pad + _KEY[:22], _KEY[22:] + " done")
# A small pad lets the masked reply fit one message; the larger ones split.
assert not _raw_runs(_on_screen(adapter).values(), _BODY)
@pytest.mark.asyncio
@pytest.mark.parametrize("deltas", [
("Starting the report.", " word" * 170 + " " + _AUTH, _TOKEN + " done"), # seal path
(" word" * 176 + " " + _AUTH, _TOKEN + " done"), # first-send path
("/" * 888 + _AUTH + _TOKEN[:15], _TOKEN[15:] + " done"), # hard cut in the token
], ids=["seal", "first-send", "first-send-hard-cut"])
async def test_bearer_token_after_its_scheme_word_is_never_split_off(deltas):
adapter = _adapter()
await _stream(adapter, *deltas)
shown = _on_screen(adapter)
assert len(shown) >= 2
assert not _raw_runs(shown.values(), _TOKEN)
@pytest.mark.asyncio
@pytest.mark.parametrize("deltas", [
("Starting the report.", " word" * 150 + "\n" + _PEM_BEGIN + "\n" + _PEM_LINES[0] + "\n"
+ _PEM_LINES[1] + "\n", _PEM_LINES[2] + "\n" + _PEM_END + "\nDone."),
(" word" * 175 + "\n" + _PEM_BEGIN + "\n" + _PEM_LINES[0] + "\n", _PEM_LINES[1] + "\n"
+ _PEM_LINES[2] + "\n" + _PEM_END + "\nDone."),
], ids=["seal", "first-send"])
async def test_pem_block_open_at_the_split_is_never_sealed_line_by_line(deltas):
adapter = _adapter()
await _stream(adapter, *deltas)
shown = _on_screen(adapter)
assert len(shown) >= 2
for line in _PEM_LINES:
assert not _raw_runs(shown.values(), line, width=16), line
@pytest.mark.asyncio
async def test_preview_frames_never_show_a_partial_or_sliding_key_window():
adapter = _adapter()
await _stream(adapter, "Your key is ", *[_KEY[i:i + 2] for i in range(0, len(_KEY), 2)],
" - keep it safe.")
frames = [content for _op, _id, content in adapter.ops]
assert frames
assert not any(_KEY[:10] in f for f in frames) # no raw prefix below the pattern floor
# A mask shows the key's last 4 chars; frames of a growing key would slide that window.
assert _raw_runs(frames, _BODY, width=4) == [_BODY[-4:]]
@pytest.mark.asyncio
async def test_stream_is_the_message_drafts_stay_prefix_stable_while_a_key_streams():
frames = []
async def send_draft(*, chat_id, draft_id, content, metadata=None):
frames.append(content)
return SimpleNamespace(success=True)
adapter = _adapter(draft_stream_is_message=True, send_draft=send_draft,
supports_draft_streaming=lambda chat_type=None, metadata=None, **kw: True)
await _stream(adapter, "Your key is ", *[_KEY[i:i + 3] for i in range(0, len(_KEY), 3)],
" - keep it safe.", transport="auto", chat_type="dm")
assert len(frames) >= 2
# The connector appends a prefix-extending frame and re-appends any other one whole.
assert all(later.startswith(earlier) for earlier, later in pairwise(frames)), frames
finals = [content for _op, _id, content in adapter.ops]
assert not _raw_runs([*frames, *finals], _BODY, width=5)
@pytest.mark.asyncio
async def test_reply_and_finish_drained_in_one_tick_is_sent_redacted_whole():
# No interim tick redacts the buffer first: the finalize frame is the first and only redaction.
adapter = _adapter()
consumer = GatewayStreamConsumer(adapter, "chat", StreamConsumerConfig(cursor=""))
consumer.on_delta(f"Your key is {_KEY} - keep it safe.")
consumer.finish()
await consumer.run()
shown = _on_screen(adapter)
assert list(shown.values()) == [f"Your key is sk-pro...{_KEY[-4:]} - keep it safe."]