Skip to content

fix(log): implement the ADR-0024 control-byte-escaping field formatter - #101

Merged
gonzafg2 merged 3 commits into
mainfrom
fix/human-log-escape-formatter
Jul 6, 2026
Merged

gonzafg2 merged 3 commits into
mainfrom
fix/human-log-escape-formatter

Conversation

@gonzafg2

@gonzafg2 gonzafg2 commented Jul 6, 2026

Copy link
Copy Markdown
Owner

Qué

Implementa el field formatter que ADR-0024 declara parte de la decisión ("not an implementation afterthought") y que el binario no tenía: en formato humano, los bytes de control dentro de valores de campos se renderizan como \xNN visible, nunca vivos.

  • Nuevo módulo crates/quantumssh/src/log_fields.rs: EscapingFields, un FormatFields cuyo visitor escapa todo lo que char::is_control reporta (C0, DEL, C1 — todo ≤ U+009F). Cubre tanto record_str como record_debug — este último es el camino que toman los campos % (Display), incluido command.
  • Cableado solo en el arm LogFormat::Human de fmt_layer; el formato JSON queda intacto (serde ya escapa).
  • Dev-dependency tracing con feature std solo para el subscriber scoped de los tests (with_default); el set de dependencias de runtime no cambia.

Por qué

El vector de threat model §5.4.3: un cliente autenticado ejecuta ssh host $'\e]0;pwned\a\ninfo forged.event' y un operador corriendo con --log-format human (default cuando stderr es TTY) recibe escapes ANSI vivos (título de terminal, clear screen) más un salto de línea que forja una segunda línea de log. El default JSON (stderr no-TTY) ya mitigaba el despliegue típico; este PR cierra el caso interactivo que el ADR aceptado mandata. Era el único gap directo código↔ADR de Phase 1.

Validación

  • Test end-to-end que dispara el ataque OSC-title + línea forjada a través de un subscriber real y verifica que ningún byte de control sobrevive salvo el newline propio de la línea, más unit tests del escape (C0, DEL, C1, passthrough de UTF-8 normal).
  • cargo fmt / clippy --workspace --all-targets -- -D warnings / cargo test --workspace: verdes (110 tests, +3 nuevos).
  • Smoke manual: quantumssh --log-format human emite server.config_error por el layer nuevo correctamente.

Hallazgo de la revisión de seguridad del código Phase-1 mergeado (misma serie que #100, independiente de él).

https://claude.ai/code/session_017JuwgCHx6Uv5E13g1BHAud

ADR-0024 mandates that the human-readable formatter escape control
bytes in string field values to a visible \xNN form via a custom
field formatter — explicitly 'part of this decision and not an
implementation afterthought' — because stock tracing_subscriber
fmt() renders %-recorded (Display) field values verbatim. The
binary was using the stock layer, so an authenticated client's
command could replay ANSI sequences and forge log lines in an
operator's live terminal under --log-format human (threat model
§5.4.3).

Adds log_fields::EscapingFields, a FormatFields impl whose visitor
escapes everything char::is_control reports (C0, DEL, C1 — all
<= U+009F) as \xNN, wired into the LogFormat::Human arm only; the
JSON format keeps serde's escaping. Covered by unit tests plus an
end-to-end test that drives the OSC-title + forged-line attack
through a real subscriber and asserts nothing live survives.

The dev-dependency on tracing with the std feature exists only for
the scoped test subscriber (tracing::subscriber::with_default);
the runtime dependency set is unchanged.

Found by security review of the merged Phase-1 code: the one direct
code-vs-accepted-ADR gap.

Claude-Session: https://claude.ai/code/session_017JuwgCHx6Uv5E13g1BHAud
Signed-off-by: Gonzalo Fleming <[email protected]>

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR brings the quantumssh binary’s human log formatter in line with ADR-0024 by ensuring control characters inside field values are rendered as visible \xNN escapes (mitigating terminal escape injection / log-line forgery in interactive --log-format human use).

Changes:

  • Adds EscapingFields, a custom tracing_subscriber::fmt::FormatFields implementation that escapes char::is_control() characters when formatting field values (including %/Display-recorded fields via record_debug).
  • Wires the formatter into the LogFormat::Human branch of the binary’s fmt_layer, leaving JSON unchanged.
  • Adds unit + end-to-end subscriber tests for escaping behavior, plus a dev-dependency on tracing with std for scoped subscriber tests.

Reviewed changes

Copilot reviewed 3 out of 3 changed files in this pull request and generated 1 comment.

File Description
crates/quantumssh/src/main.rs Hooks the ADR-0024 escaping field formatter into the human tracing_subscriber fmt layer.
crates/quantumssh/src/log_fields.rs Implements EscapingFields + tests to ensure control bytes in field values are printed as visible \\xNN.
crates/quantumssh/Cargo.toml Adds tracing dev-dependency with std to support tracing::subscriber::with_default in tests.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread crates/quantumssh/src/log_fields.rs Resolved
@claude

claude Bot commented Jul 6, 2026

Copy link
Copy Markdown
Contributor

Code review

No issues found. Checked for bugs and CLAUDE.md compliance.

… adapter

Copilot review: record_debug allocated a String per non-str field
via format!. EscapingWriter implements fmt::Write over the layer's
Writer and escapes in write_str, so Debug/Display formatting streams
straight through write_escaped with no intermediate allocation.
Output is unchanged; the three log_fields tests pass as-is.

Claude-Session: https://claude.ai/code/session_017JuwgCHx6Uv5E13g1BHAud
Signed-off-by: Gonzalo Fleming <[email protected]>
@opencode-agent

opencode-agent Bot commented Jul 6, 2026

Copy link
Copy Markdown

Review: ADR-0024 control-byte-escaping field formatter

Classification: Rust under crates/ — apply hard security rules.

Verdict: Clean. No issues found.

Changes reviewed against the five MANIFIESTO commitments:

Commitment Finding
1. Memory-safe by construction No unsafe added. Allocations bounded by field-value length only. ✅
2. Post-quantum by default Not in scope (log formatting only). ✅
3. Zero legacy Not in scope. ✅
4. Small surface, sharp edges One new module (log_fields.rs, 174 lines), one dev-dependency feature (tracing/std — already a runtime dep). Justified in PR. No cargo deny impact. ✅
5. Permanently open Apache-2.0, unchanged. ✅

Applied hard security rules:

  • Pre-auth path — not touched. ✅
  • Fail closed — not touched. ✅
  • AEAD-only, key material never logged — write_escaped operates on field values only; key material is never a field value on any event per ADR-0024. ✅
  • Transport type-state — not touched. ✅
  • Audit log fields are mandated (ADR-0024) — this PR is the direct implementation of ADR-0024's \xNN escaping requirement for the human format, closing the gap identified in the PR body. ✅

Design notes (non-blocking):

  1. is_control() coverage is correct for the threat. char::is_control() covers C0 (U+0000–U+001F), DEL (U+007F), and C1 (U+0080–U+009F). The §5.4.3 OSC-title attack (\x1b]0;pwned\x07) and line-forgery (\n) are fully mitigated. Unicode format characters (e.g., U+200B ZWSP) pass through — these have no terminal-altering effect and are harmless.

  2. EscapingWriter allocation-avoidance is sound. The fmt::Write adapter (added in the follow-up review comment, dd4b9e7) streams Debug/Display formatting through write_escaped without a String allocation, matching the zero-alloc spirit of the codebase's pre-auth path (though this code runs post-auth).

  3. Module/doc conventions followed. //! doc citing ADR-0024 on log_fields.rs:1, //! doc on main.rs:1 updated implicitly (no change needed — it already cites ADR-0024 on line 2).

  4. Tests are thorough. Three tests: unit write_escaped (control bytes), unit write_escaped (UTF-8 passthrough), end-to-end subscriber test exercising the exact §5.4.3 attack vector. All assertions verify both the presence of visible escapes and the absence of live control bytes.

github run

@opencode-agent

opencode-agent Bot commented Jul 6, 2026

Copy link
Copy Markdown

cargo fmt --check and cargo clippy -- -D warnings both pass clean.


Review: ADR-0024 control-byte-escaping field formatter

Classification: Rust under crates/ — apply hard security rules.

Verdict: Clean. No issues found.

The PR directly implements the field formatter that ADR-0024 §"Decision – Consequences – Positive" mandates ("the field formatter is part of this decision and not an implementation afterthought"), closing the only Phase-1 gap between ADR text and binary code. The threat model's §5.4.3 OSC-title + line-forgery attack vector is tested end-to-end through a real subscriber.

Five commitments

# Commitment Finding
1 Memory-safe by construction No unsafe. EscapingWriter avoids intermediate String allocation (copilot's concern, already fixed in dd4b9e7).
2 Post-quantum by default Out of scope (log formatting).
3 Zero legacy Out of scope.
4 Small surface, sharp edges One module (174 lines), one dev-dependency feature (tracing/std — already a runtime dep, feature-gated behind [dev-dependencies]). Justified in PR.
5 Permanently open Apache-2.0, unchanged.

Hard security rules

  • Pre-auth path — not touched.
  • Fail closed — not touched.
  • Key material never logged — write_escaped operates on field values only; key material is never a field value per ADR-0024.
  • Transport type-state — not touched.
  • Audit log fields mandated (ADR-0024) — this PR is the implementation of the \xNN escaping requirement.

Design notes (non-blocking)

  1. is_control() coverage is correct for the threat. Covers C0 (incl. \x1b ESC, \x07 BEL), DEL (\x7f), and C1 (\x9b CSI). Unicode format chars (ZWSP, etc.) pass through — harmless for terminals as noted in the prior review.

  2. EscapingWriter zero-alloc streaming is sound. The record_debug path now flows Debug/Display formatting through write_escaped without intermediate String allocation (fixed in dd4b9e7).

  3. Tests are thorough. Unit tests for write_escaped (control bytes + UTF-8 passthrough), plus an end-to-end subscriber test exercising the exact §5.4.3 OSC-title + line-forgery attack, verifying both visible escapes and absence of live control bytes.

  4. Conventions followed. Module opens with //! doc citing ADR-0024 (log_fields.rs:1). Tests in #[cfg(test)] mod tests at file bottom. No mocks, stubs, or placeholder code.

fmt + clippy + 110 tests (including 3 new): all green.

github run

@gonzafg2
gonzafg2 merged commit a3d2318 into main Jul 6, 2026
11 checks passed
@gonzafg2
gonzafg2 deleted the fix/human-log-escape-formatter branch July 6, 2026 16:49
gonzafg2 added a commit that referenced this pull request Sep 22, 2026
…each edit touched

Claude checked the Links lines against the milestone PRs' file
lists and found four wrong attributions: server.rs (ADR-0016) and
everything ADR-0022 names landed in M0 (#62), not M5/M3;
transport.rs (ADR-0021) landed in M3 (#65), not M2; and
log_fields.rs (ADR-0024) came with #101 on 2026-07-06, after the
ADR's acceptance. All four corrected, with the banners' milestone
references.

Each banner now says which section the edit touched (Context in
0018/0019, Related in 0021/0023/0024, both in 0022) instead of the
same sentence everywhere. ADR-0020's Links line no longer carries a
note about the unimplemented package pin — that is decision-level
content and lives in ADR-0034 (#161). ADR-0023 no longer points at
"PR #50 in review" for the event schema, and ADR-0021 drops a "(TBD)"
next to the kex module.

docs/adr/README.md step 5 distinguishes the governance state from the
file's Status line and lists what actually happened (ADR-0027 merged
Accepted; 0028/0029 flipped in their implementing PRs; 0030-0032 in
#158) instead of calling one instance the practice.
docs/infrastructure.md says first-party unsafe would need a
superseding ADR, as ADR-0018 states, not an RFC. Findings by Claude
and opencode on #159.

Claude-Session: https://claude.ai/code/session_018UmL9wcgKBGFjdjGSSLafa
Signed-off-by: Gonzalo Fleming <[email protected]>
gonzafg2 added a commit that referenced this pull request Sep 22, 2026
…events; ADR-0020 and 0017 drafting-time sentences

ADR-0024's Related line and banner still grouped the subscriber
initialisation under M4/M5 after the Links line moved it to M0;
all three now agree (subscriber M0, events M4/M5, formatter #101).
ADR-0020's Consequences said the gate is wired up in the first-crate
PR; it was wired up in M5 (#84), once a connectable binary existed,
and the banner records the edit. ADR-0017's Context no longer calls
the workspace currently empty. Raised by Codex and opencode on #159.

Claude-Session: https://claude.ai/code/session_018UmL9wcgKBGFjdjGSSLafa
Signed-off-by: Gonzalo Fleming <[email protected]>
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.

2 participants