Repository navigation
feat: hidden-character scan, content filter and output limit on the desktop gateway - #167
Merged
Merged
Conversation
…esktop gateway
tw-guard gains two shared engines and a request-side scan:
- hidden::scan_request / scan_smuggled: tag characters and bidi controls in
the caller's messages and tool results, one item per kind and place, with
the tag text decoded.
- content: contains/regex rules (case-insensitive, bounded regex), block >
warn > log, every hit reported per rule, worst() for the verdict; the
presets live in data/content.yaml with stable ids and groups.
- output: Limit (bytes or chars) with check_whole for a whole answer and a
Meter that counts text deltas in the client's format (SSE or Gemini's
JSON array) and reports the frame that crossed the limit.
The desktop wires them in: security.hidden_text, security.content and
security.output_limit in config.yaml (off/observe/enforce; the first two
ship in observe, the limit ships off), refusals as denied failures, the
stream cut on a frame and closed in the client's format, a whole answer
withheld, the same checks on WebSocket frames. New events HiddenTextFound,
ContentMatched and OutputLimited land in the security log; the control
plane lists, toggles, retunes and tests the new rules and sets the limit
(PUT /security/{guard}/limit).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This was referenced Sep 24, 2026
Merged
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Brings the desktop gateway to feature parity with enterprise's request guards, with the engines moved into
tw-guardso both gateways share them (enterprise switches over in a follow-up).tw-guard (shared, layer one)
tw_guard::hidden(additions)SMUGGLING: [Kind; 2]=[Kind::Tag, Kind::Bidi];Kind::from_slug,Kind::ranges().struct Smuggled { kind: Kind, in_tool_result: bool, count: usize, example: String /* "U+E0049" */, revealed: String /* tag text decoded, ≤ REVEAL_MAX = 120 chars */ }fn scan_request(&ir::Request, kinds: &[Kind]) -> Vec<Smuggled>— user messages and tool results only (not system, not assistant turns), one item per kind × place. Same semantics as enterprise'shidden_text::scan(which can become a thin mapping over it).fn scan_smuggled(text, in_tool_result, kinds, &mut Vec<Smuggled>)for text without structure.tw_guard::content(new; enterprise'scontent_filterengine)enum Match { Contains, Regex },enum Action { Log, Warn, Block }(ordered by severity), both withslug/from_slug, serde lowercase.struct Builtin { id, name, pattern, matching, action, group, on_by_default },fn builtins() -> &'static [Builtin](fromdata/content.yaml: enterprise's basic/strict/chinese presets with stable ids; groupsinjection/persona/chinese; only the three explicit instruction-override phrases are on by default),fn builtin(id).struct RuleInput<'a> { id, name, custom, pattern, matching, action }(From<&Builtin>),Rule::new(RuleInput) -> Result<Rule, BadRule>,Rules::build(iter) -> Result<Rules, BadRule>(strict; a lenient caller builds rule by rule).Rules::scan_request(&ir::Request) -> Vec<Hit>(user messages + tool results, first hit per rule),Rules::scan_text(&str) -> Vec<Hit>,fn worst(&[Hit]) -> Option<&Hit>.struct Hit { rule, name, custom, action, bytes: Range<usize>, snippet /* ≤ 120 chars, … marks cuts */, in_tool_result }.tw_guard::output(new; enterprise'sMaxLengthguardrail)enum Unit { Bytes, Chars },struct Limit { max, unit },Limit::measure,Limit::check_whole(body, client: Dialect) -> Option<usize>(text blocks only),fn assistant_text(body, Dialect).Meter::sse(Limit, client: Dialect)/Meter::json_array(Limit)(Gemini withoutalt=sse);feed(chunk) -> Option<Trip { seen, safe_prefix }>reports the first frame that crosses the limit and how many bytes of this chunk precede it; never changes bytes.Desktop
config.yaml (
security.*, all global; defaults are not written)Enforce refuses the request (hidden text; content rules whose action is block) as a
deniedfailure before anything reaches an upstream, or cuts the answer (output limit): a stream stops before the frame that crosses the limit and is closed in the client's format (converterfail, orerror_framewhen passed through); a whole answer is withheld and replaced by an error body. Observe only records. WebSocket frames get the same checks (response.createis decoded as a Responses request; undecodable frames get the hidden-character scan only).Events (
tw_api::Event):HiddenTextFound { id, provider, blocked, items: Vec<HiddenItem>, at_ms },ContentMatched { id, provider, rule, custom, action, blocked, in_tool_result, excerpt, at_ms },OutputLimited { id, provider, max_chars, seen_chars, cut, at_ms }. The recorder stores them insecurity_eventswithguard=hidden_text/content/output_limit, new actionblocked,tool = "tool_result"when found in a tool result.SecurityCountsgainshidden_text(_blocked),content(_blocked),output_limit(_cut);SecurityViewgains the three modes.Control plane
GET /security:SecurityDetailgainshidden_text: GuardDetail(rules = the two kinds, matchercodepoints),content: GuardDetail(matchercontainsorregex,kind= group,action/default_action=block/record),output_limit: OutputLimitDetail { mode, max_chars, default_max_chars, ceiling }.{guard}in the existing security endpoints now also acceptshidden_text,content,output_limitwhere it makes sense (mode for all five; builtin toggle for redact/inspect_tools/content/hidden_text; builtin action for inspect_tools/content; custom rules for redact/inspect_tools/content; test for all but output_limit).SetSecurityLimit: PUT /security/{guard}/limit(LimitSave { max_chars, base_version }, output_limit only).CustomRuleSaveandSecurityTestRequestgainmatch(content only).gw.hidden_text.refused_message,gw.hidden_text.refused_tool_result,gw.content.refused,gw.output_limit.cut,gw.output_limit.withheld,config.output_limit_range,security.guard_unknown(replacessecurity.unknown_guard),security.no_action_of_its_own(replacessecurity.no_action),security.unknown_content_action,security.unknown_match,security.bad_content_pattern,security.no_custom_rules,security.no_limit,security.limit_range,security.nothing_to_test.Also fixed on the way: a whole-body conversion (
convert_whole) that was cut or broke wrote nothing to the client; it now writes an error in the client's format.Tests
tw-guard unit tests for all three engines (framing across every byte split, JSON-array streams, case folding, bounded regexes), tw-config policy/validation tests, recorder tests,
tw-gateway/tests/m5_request_guards.rs(refusals, observe/off, stream cut with passthrough and with conversion, whole answer withheld), two WebSocket tests, and control-plane tests.🤖 Generated with Claude Code