Skip to content

feat: hidden-character scan, content filter and output limit on the desktop gateway - #167

Merged
fylorn merged 1 commit into
mainfrom
feat/request-guards
Sep 24, 2026
Merged

fylorn merged 1 commit into
mainfrom
feat/request-guards

Conversation

@fylorn

@fylorn fylorn commented Sep 24, 2026

Copy link
Copy Markdown
Contributor

Brings the desktop gateway to feature parity with enterprise's request guards, with the engines moved into tw-guard so 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's hidden_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's content_filter engine)

  • enum Match { Contains, Regex }, enum Action { Log, Warn, Block } (ordered by severity), both with slug/from_slug, serde lowercase.
  • struct Builtin { id, name, pattern, matching, action, group, on_by_default }, fn builtins() -> &'static [Builtin] (from data/content.yaml: enterprise's basic/strict/chinese presets with stable ids; groups injection/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 }.
  • Contains is case-insensitive substring; regex is case-insensitive with bounded compile size.

tw_guard::output (new; enterprise's MaxLength guardrail)

  • 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 without alt=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)

security:
  hidden_text:            # default mode: observe
    mode: off|observe|enforce
    disable: [bidi]       # kinds: tag, bidi
  content:                # default mode: observe
    mode: off|observe|enforce
    enable: [act-as]      # built-in ids that ship off
    disable: [ignore-all-previous]
    actions: {jailbreak: record}   # block|record, only when it differs from the factory
    custom:
      - name: Project codename
        pattern: project falcon
        match: contains|regex      # default contains
        action: block|record       # default record
        disabled: true
  output_limit:           # default mode: off
    mode: off|observe|enforce
    max_chars: 100000     # default 100000, 1..=1000000, counted in characters

Enforce refuses the request (hidden text; content rules whose action is block) as a denied failure 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 (converter fail, or error_frame when passed through); a whole answer is withheld and replaced by an error body. Observe only records. WebSocket frames get the same checks (response.create is 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 in security_events with guard = hidden_text / content / output_limit, new action blocked, tool = "tool_result" when found in a tool result. SecurityCounts gains hidden_text(_blocked), content(_blocked), output_limit(_cut); SecurityView gains the three modes.

Control plane

  • GET /security: SecurityDetail gains hidden_text: GuardDetail (rules = the two kinds, matcher codepoints), content: GuardDetail (matcher contains or regex, 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 accepts hidden_text, content, output_limit where 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).
  • New SetSecurityLimit: PUT /security/{guard}/limit (LimitSave { max_chars, base_version }, output_limit only).
  • CustomRuleSave and SecurityTestRequest gain match (content only).
  • Msg codes: new 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 (replaces security.unknown_guard), security.no_action_of_its_own (replaces security.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

…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>
@fylorn
fylorn merged commit ea88389 into main Sep 24, 2026
3 checks passed
@fylorn
fylorn deleted the feat/request-guards branch September 24, 2026 07:45
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant