Skip to content

Commit 97d22d6

Browse files
committed
fix: Keep message payloads out of default log output
1 parent 65c65db commit 97d22d6

3 files changed

Lines changed: 186 additions & 1 deletion

File tree

‎docs/guide/client-api.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -651,6 +651,12 @@ peer.onChannel(channel -> { // channels the remote peer opens
651651
});
652652
```
653653

654+
`Message.toString()` reports only the message type and byte length. Access content
655+
explicitly with `text()` or `bytes()`. For diagnostics, `message.preview(64)` inspects
656+
at most 64 payload bytes and escapes control characters. Binary previews use hex.
657+
Use `message.preview(64, prefix -> redact(prefix))` to apply your own masking before
658+
escaping; the masking function must handle secrets truncated at the prefix boundary.
659+
The preview marks truncated content and also limits the masking function's output.
654660

655661
- A channel may be used right away: messages sent before it opens are held until it does.
656662
- Messages that arrive while a channel has no `onMessage` handler are kept for the next one, so none are lost while a handler is being set up.

‎webrtc/src/main/java/dev/onvoid/webrtc/client/Message.java‎

Lines changed: 91 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,12 @@
1616

1717
package dev.onvoid.webrtc.client;
1818

19+
import java.nio.ByteBuffer;
20+
import java.nio.CharBuffer;
21+
import java.nio.charset.CodingErrorAction;
1922
import java.nio.charset.StandardCharsets;
23+
import java.util.Objects;
24+
import java.util.function.UnaryOperator;
2025

2126
/**
2227
* A message received on a {@link DataChannel}. It holds a copy of the data and
@@ -62,8 +67,93 @@ public int size() {
6267
return data.length;
6368
}
6469

70+
/**
71+
* Returns message type and byte length, without exposing payload data.
72+
* Use {@link #text()}, {@link #bytes()} or {@link #preview(int)} explicitly
73+
* when content is needed.
74+
*/
6575
@Override
6676
public String toString() {
67-
return binary ? "Message[" + data.length + " bytes]" : "Message[" + text() + "]";
77+
return "Message[type=" + (binary ? "binary" : "text") + ", length=" + data.length + " bytes]";
78+
}
79+
80+
/**
81+
* Returns metadata with an escaped, bounded payload preview. Text uses
82+
* UTF-8; binary data uses hexadecimal. An incomplete trailing UTF-8
83+
* character is omitted. Control characters are escaped for single-line logs.
84+
*
85+
* @param maxBytes maximum input bytes to inspect; must be nonnegative.
86+
* @return the diagnostic representation.
87+
*/
88+
public String preview(int maxBytes) {
89+
return preview(maxBytes, UnaryOperator.identity());
90+
}
91+
92+
/**
93+
* Returns a bounded preview with application-defined masking, applied before
94+
* escaping. The mask receives only the bounded prefix, so masking rules must
95+
* also handle secrets cut off at its end. Its result is limited to twice
96+
* {@code maxBytes} UTF-16 units (enough for hexadecimal), then escaped.
97+
* At most six output characters are used per UTF-16 unit.
98+
*
99+
* @param maxBytes maximum input bytes to inspect; must be nonnegative.
100+
* @param mask transforms the prefix to remove sensitive values; must return
101+
* a non-null string.
102+
* @return metadata and the masked preview, with a truncation indicator.
103+
* @throws IllegalArgumentException if maxBytes is negative.
104+
* @throws NullPointerException if mask or its result is null.
105+
*/
106+
public String preview(int maxBytes, UnaryOperator<String> mask) {
107+
if (maxBytes < 0) {
108+
throw new IllegalArgumentException("Negative preview limit");
109+
}
110+
Objects.requireNonNull(mask, "mask");
111+
int count = Math.min(data.length, maxBytes);
112+
String prefix;
113+
boolean truncated = count < data.length;
114+
if (binary) {
115+
StringBuilder hex = new StringBuilder();
116+
for (int i = 0; i < count; i++) {
117+
int value = data[i] & 0xff;
118+
hex.append(Character.forDigit(value >>> 4, 16));
119+
hex.append(Character.forDigit(value & 15, 16));
120+
}
121+
prefix = hex.toString();
122+
}
123+
else {
124+
ByteBuffer input = ByteBuffer.wrap(data, 0, count);
125+
CharBuffer output = CharBuffer.allocate(count);
126+
StandardCharsets.UTF_8.newDecoder()
127+
.onMalformedInput(CodingErrorAction.REPLACE)
128+
.onUnmappableCharacter(CodingErrorAction.REPLACE)
129+
.decode(input, output, count == data.length);
130+
truncated |= input.hasRemaining();
131+
output.flip();
132+
prefix = output.toString();
133+
}
134+
String masked = Objects.requireNonNull(mask.apply(prefix), "mask result");
135+
int end = (int) Math.min(masked.length(), 2L * maxBytes);
136+
if (end > 0 && end < masked.length() && Character.isHighSurrogate(masked.charAt(end - 1))) {
137+
end--;
138+
}
139+
truncated |= end < masked.length();
140+
StringBuilder escaped = new StringBuilder();
141+
for (int i = 0; i < end; i++) {
142+
char ch = masked.charAt(i);
143+
if (ch == '\\' || ch == '"') {
144+
escaped.append('\\').append(ch);
145+
}
146+
else if (Character.isISOControl(ch) || Character.getType(ch) == Character.FORMAT
147+
|| ch == '\u2028' || ch == '\u2029') {
148+
escaped.append("\\u");
149+
for (int shift = 12; shift >= 0; shift -= 4) {
150+
escaped.append(Character.forDigit((ch >>> shift) & 15, 16));
151+
}
152+
}
153+
else {
154+
escaped.append(ch);
155+
}
156+
}
157+
return toString() + " preview=\"" + escaped + "\"" + (truncated ? " (truncated)" : "");
68158
}
69159
}
Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
1+
/*
2+
* Copyright 2026 Alex Andres
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
package dev.onvoid.webrtc.client;
18+
19+
import static org.junit.jupiter.api.Assertions.assertEquals;
20+
import static org.junit.jupiter.api.Assertions.assertFalse;
21+
import static org.junit.jupiter.api.Assertions.assertThrows;
22+
import static org.junit.jupiter.api.Assertions.assertTrue;
23+
24+
import java.nio.charset.StandardCharsets;
25+
import java.util.concurrent.atomic.AtomicReference;
26+
27+
import org.junit.jupiter.api.Test;
28+
29+
class MessageTests {
30+
31+
@Test
32+
void metadataOmitsContent() {
33+
assertEquals("Message[type=text, length=6 bytes]", text("secret").toString());
34+
assertEquals("Message[type=binary, length=3 bytes]",
35+
new Message(new byte[] { 1, 2, 3 }, true).toString());
36+
assertTrue(new Message(new byte[1_000_000], false).toString().length() < 64);
37+
assertEquals("secret", text("secret").text());
38+
}
39+
40+
@Test
41+
void boundedPreview() {
42+
assertEquals("Message[type=text, length=6 bytes] preview=\"sec\" (truncated)",
43+
text("secret").preview(3));
44+
assertTrue(text("secret").preview(0).endsWith("preview=\"\" (truncated)"));
45+
assertTrue(text("").preview(0).endsWith("preview=\"\""));
46+
assertTrue(text("é😀!").preview(4).endsWith("preview=\"é\" (truncated)"));
47+
assertTrue(text("é😀!").preview(6).endsWith("preview=\"é😀\" (truncated)"));
48+
assertTrue(text("é😀!").preview(7).endsWith("preview=\"é😀!\""));
49+
}
50+
51+
@Test
52+
void escapesLogControls() {
53+
String preview = text("a\n\r\t\u001b\u2028\u202e\"\\").preview(100);
54+
assertTrue(preview.endsWith("preview=\"a\\u000a\\u000d\\u0009\\u001b\\u2028\\u202e\\\"\\\\\""));
55+
assertFalse(preview.contains("\n"));
56+
}
57+
58+
@Test
59+
void masksBeforeEscaping() {
60+
AtomicReference<String> inspected = new AtomicReference<>();
61+
String preview = text("token=secret and more").preview(12, prefix -> {
62+
inspected.set(prefix);
63+
return prefix.replace("secret", "[hidden]");
64+
});
65+
assertEquals("token=secret", inspected.get());
66+
assertFalse(preview.contains("secret"));
67+
assertTrue(preview.contains("token=[hidden]"));
68+
assertTrue(text("abc").preview(2, prefix -> "123456789").endsWith("preview=\"1234\" (truncated)"));
69+
}
70+
71+
@Test
72+
void binaryPreview() {
73+
Message message = new Message(new byte[] { 0, (byte) 0xff, 42 }, true);
74+
assertTrue(message.preview(2).endsWith("preview=\"00ff\" (truncated)"));
75+
assertTrue(message.preview(3).endsWith("preview=\"00ff2a\""));
76+
assertTrue(message.preview(3, prefix -> "hidden").endsWith("preview=\"hidden\""));
77+
}
78+
79+
@Test
80+
void rejectsInvalidPreview() {
81+
assertThrows(IllegalArgumentException.class, () -> text("x").preview(-1));
82+
assertThrows(NullPointerException.class, () -> text("x").preview(1, null));
83+
assertThrows(NullPointerException.class, () -> text("x").preview(1, prefix -> null));
84+
}
85+
86+
private static Message text(String value) {
87+
return new Message(value.getBytes(StandardCharsets.UTF_8), false);
88+
}
89+
}

0 commit comments

Comments
 (0)