SHA256
Включить диагностику ошибок браузера
This commit is contained in:
+84
-59
@@ -13,88 +13,113 @@ import server.logic.ws_protocol.JSON.utils.NetExceptionResponseFactory;
|
||||
import server.logic.ws_protocol.WireCodes;
|
||||
|
||||
import java.net.SocketAddress;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.util.HashMap;
|
||||
import java.util.Iterator;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* ClientErrorLog — технический endpoint для фронтенд-ошибок.
|
||||
* Не требует авторизации: клиент должен иметь возможность отправить ошибку
|
||||
* даже если логин/сессия ещё не установлены.
|
||||
*/
|
||||
/** Единая точка диагностики ошибок браузера (доступна до авторизации). */
|
||||
public class Net_ClientErrorLog_Handler implements JsonMessageHandler {
|
||||
private static final Logger log = LoggerFactory.getLogger("client.frontend");
|
||||
private static final long WINDOW_MS = 60_000L;
|
||||
private static final int MAX_PER_SOURCE = 60;
|
||||
private static final int MAX_ALL = 1200;
|
||||
private static final int MAX_SOURCES = 4096;
|
||||
private static final Map<String, Bucket> rateLimits = new HashMap<>();
|
||||
private static long globalWindow = 0;
|
||||
private static int globalCount = 0;
|
||||
private static int cleanCounter = 0;
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(Net_ClientErrorLog_Handler.class);
|
||||
private static final class Bucket {
|
||||
long start;
|
||||
int count;
|
||||
Bucket(long now) { start = now; }
|
||||
}
|
||||
|
||||
@Override
|
||||
public Net_Response handle(Net_Request baseRequest, ConnectionContext ctx) {
|
||||
Net_ClientErrorLog_Request req = (Net_ClientErrorLog_Request) baseRequest;
|
||||
|
||||
if (req.getMessage() == null || req.getMessage().isBlank()) {
|
||||
return NetExceptionResponseFactory.error(
|
||||
req,
|
||||
WireCodes.Status.BAD_REQUEST,
|
||||
"BAD_FIELDS",
|
||||
"Поле message обязательно для ClientErrorLog"
|
||||
);
|
||||
if (req.getMessage() == null || req.getMessage().isBlank() || invalidSize(req)) {
|
||||
return NetExceptionResponseFactory.error(req, WireCodes.Status.BAD_REQUEST,
|
||||
"BAD_FIELDS", "Недопустимый размер или отсутствие message в ClientErrorLog");
|
||||
}
|
||||
|
||||
long serverTs = System.currentTimeMillis();
|
||||
String login = safe(ctx != null ? ctx.getLogin() : null);
|
||||
String sessionId = safe(ctx != null ? ctx.getSessionId() : null);
|
||||
String remote = safe(remoteAddress(ctx));
|
||||
|
||||
log.error(
|
||||
"CLIENT_FRONTEND_ERROR kind={} clientTs={} serverTs={} login={} sessionId={} remote={} route={} href={} sourceUrl={} line={} column={} requestOp={} requestIdRef={} message={} userAgent={} context={}",
|
||||
clip(req.getKind(), 64),
|
||||
req.getClientTs(),
|
||||
serverTs,
|
||||
clip(login, 64),
|
||||
clip(sessionId, 128),
|
||||
clip(remote, 128),
|
||||
clip(req.getRoute(), 200),
|
||||
clip(req.getHref(), 240),
|
||||
clip(req.getSourceUrl(), 240),
|
||||
req.getLineNumber(),
|
||||
req.getColumnNumber(),
|
||||
clip(req.getRequestOp(), 64),
|
||||
clip(req.getRequestIdRef(), 128),
|
||||
clip(req.getMessage(), 500),
|
||||
clip(req.getUserAgent(), 240),
|
||||
clip(req.getContextJson(), 2000)
|
||||
);
|
||||
|
||||
if (req.getStack() != null && !req.getStack().isBlank()) {
|
||||
log.error("CLIENT_FRONTEND_ERROR_STACK requestId={} stack={}",
|
||||
clip(req.getRequestId(), 128),
|
||||
clip(req.getStack(), 8000));
|
||||
boolean accepted = allow(remoteAddress(ctx), serverTs);
|
||||
if (accepted) {
|
||||
log.error("CLIENT_FRONTEND_ERROR id={} clientVersion={} kind={} clientTs={} serverTs={} login={} "
|
||||
+ "route={} sourceUrl={} line={} column={} requestOp={} requestIdRef={} message={} "
|
||||
+ "userAgent={} context={} stack={}",
|
||||
clip(req.getErrorId(), 48), clip(req.getClientVersion(), 80),
|
||||
clip(req.getKind(), 64), req.getClientTs(), serverTs,
|
||||
clip(ctx != null ? ctx.getLogin() : null, 64), clip(req.getRoute(), 150),
|
||||
clip(req.getSourceUrl(), 240), req.getLineNumber(), req.getColumnNumber(),
|
||||
clip(req.getRequestOp(), 64), clip(req.getRequestIdRef(), 128),
|
||||
clip(req.getMessage(), 500), clip(req.getUserAgent(), 240),
|
||||
clip(req.getContextJson(), 800), clip(req.getStack(), 6000));
|
||||
}
|
||||
|
||||
Net_ClientErrorLog_Response resp = new Net_ClientErrorLog_Response();
|
||||
resp.setOp(req.getOp());
|
||||
resp.setRequestId(req.getRequestId());
|
||||
resp.setStatus(WireCodes.Status.OK);
|
||||
resp.setAccepted(true);
|
||||
resp.setAccepted(accepted); // false = ограничение частоты, отчёт не записан
|
||||
resp.setServerTs(serverTs);
|
||||
return resp;
|
||||
}
|
||||
|
||||
private static String remoteAddress(ConnectionContext ctx) {
|
||||
if (ctx == null) return "";
|
||||
Session ws = ctx.getWsSession();
|
||||
if (ws == null) return "";
|
||||
SocketAddress remote = ws.getRemoteAddress();
|
||||
return remote != null ? remote.toString() : "";
|
||||
private static boolean invalidSize(Net_ClientErrorLog_Request req) {
|
||||
return length(req.getMessage()) > 500 || length(req.getStack()) > 6000
|
||||
|| length(req.getContextJson()) > 800 || length(req.getKind()) > 64
|
||||
|| length(req.getSourceUrl()) > 240 || length(req.getUserAgent()) > 240
|
||||
|| length(req.getErrorId()) > 48 || length(req.getClientVersion()) > 80
|
||||
|| length(req.getRoute()) > 150 || length(req.getHref()) > 240
|
||||
|| length(req.getRequestOp()) > 64 || length(req.getRequestIdRef()) > 128;
|
||||
}
|
||||
|
||||
private static String safe(String value) {
|
||||
return value == null ? "" : value.trim();
|
||||
private static int length(String value) { return value == null ? 0 : value.length(); }
|
||||
|
||||
// Ограничение по IP WebSocket (не по полю JSON, которое клиент может подделать).
|
||||
private static synchronized boolean allow(String source, long now) {
|
||||
if (now - globalWindow >= WINDOW_MS) { globalWindow = now; globalCount = 0; }
|
||||
if (globalCount >= MAX_ALL) return false;
|
||||
if (rateLimits.size() >= MAX_SOURCES || ++cleanCounter % 128 == 0) {
|
||||
Iterator<Map.Entry<String, Bucket>> it = rateLimits.entrySet().iterator();
|
||||
while (it.hasNext()) {
|
||||
if (now - it.next().getValue().start >= WINDOW_MS) it.remove();
|
||||
}
|
||||
}
|
||||
Bucket bucket = rateLimits.get(source);
|
||||
if (bucket == null) {
|
||||
if (rateLimits.size() >= MAX_SOURCES) return false;
|
||||
bucket = new Bucket(now);
|
||||
rateLimits.put(source, bucket);
|
||||
}
|
||||
if (now - bucket.start >= WINDOW_MS) { bucket.start = now; bucket.count = 0; }
|
||||
if (bucket.count >= MAX_PER_SOURCE) return false;
|
||||
bucket.count++;
|
||||
globalCount++;
|
||||
return true;
|
||||
}
|
||||
|
||||
private static String remoteAddress(ConnectionContext ctx) {
|
||||
if (ctx == null) return "unknown";
|
||||
Session session = ctx.getWsSession();
|
||||
if (session == null) return "unknown";
|
||||
SocketAddress remote = session.getRemoteAddress();
|
||||
// Адрес не записывается в журнал и хранится только как ключ лимита на 1 минуту.
|
||||
if (remote instanceof InetSocketAddress inet) {
|
||||
return inet.getAddress() != null ? inet.getAddress().getHostAddress() : inet.getHostString();
|
||||
}
|
||||
return remote != null ? remote.toString() : "unknown";
|
||||
}
|
||||
|
||||
private static String clip(String value, int maxLen) {
|
||||
String cleaned = safe(value)
|
||||
.replace('\n', ' ')
|
||||
.replace('\r', ' ');
|
||||
if (cleaned.length() <= maxLen) {
|
||||
return cleaned;
|
||||
}
|
||||
return cleaned.substring(0, Math.max(0, maxLen - 3)) + "...";
|
||||
if (value == null) return "";
|
||||
String clean = value.replaceAll("[\\p{Cntrl}]", " ")
|
||||
.replaceAll("(?i)\\bBearer\\s+[^\\s,;]+", "Bearer [REDACTED]")
|
||||
.replaceAll("(?i)\\b(password|passwd|token|secret|privateKey|sessionId|authorization|apiKey|storagePwd)\\s*[:=]\\s*[^\\s,;}&]+", "$1=[REDACTED]")
|
||||
.replaceAll("[A-Za-z0-9_+/=-]{96,}", "[REDACTED_LONG_VALUE]")
|
||||
.replaceAll("(?i)[?&](token|key|password|secret|session|auth|code|signature)=[^&#\\s]+", "[REDACTED_PARAM]");
|
||||
return clean.length() <= maxLen ? clean : clean.substring(0, Math.max(0, maxLen - 3)) + "...";
|
||||
}
|
||||
}
|
||||
|
||||
+8
@@ -26,6 +26,8 @@ import server.logic.ws_protocol.JSON.entyties.Net_Request;
|
||||
*/
|
||||
public class Net_ClientErrorLog_Request extends Net_Request {
|
||||
|
||||
private String errorId;
|
||||
private String clientVersion;
|
||||
private String kind;
|
||||
private String message;
|
||||
private String stack;
|
||||
@@ -40,6 +42,12 @@ public class Net_ClientErrorLog_Request extends Net_Request {
|
||||
private String requestIdRef;
|
||||
private String contextJson;
|
||||
|
||||
public String getErrorId() { return errorId; }
|
||||
public void setErrorId(String errorId) { this.errorId = errorId; }
|
||||
|
||||
public String getClientVersion() { return clientVersion; }
|
||||
public void setClientVersion(String clientVersion) { this.clientVersion = clientVersion; }
|
||||
|
||||
public String getKind() { return kind; }
|
||||
public void setKind(String kind) { this.kind = kind; }
|
||||
|
||||
|
||||
@@ -18,6 +18,24 @@
|
||||
</encoder>
|
||||
</appender>
|
||||
|
||||
<!-- Отдельный журнал ошибок браузера: без дублирования в app.log. -->
|
||||
<appender name="CLIENT_ERRORS" class="ch.qos.logback.core.rolling.RollingFileAppender">
|
||||
<file>${LOG_DIR}/client-errors.log</file>
|
||||
<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
|
||||
<fileNamePattern>${LOG_DIR}/client-errors.%d{yyyy-MM-dd}.%i.log.gz</fileNamePattern>
|
||||
<maxFileSize>10MB</maxFileSize>
|
||||
<maxHistory>14</maxHistory>
|
||||
<totalSizeCap>150MB</totalSizeCap>
|
||||
</rollingPolicy>
|
||||
<encoder>
|
||||
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} %-5level %msg%n</pattern>
|
||||
</encoder>
|
||||
</appender>
|
||||
|
||||
<logger name="client.frontend" level="error" additivity="false">
|
||||
<appender-ref ref="CLIENT_ERRORS" />
|
||||
</logger>
|
||||
|
||||
<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
|
||||
<encoder>
|
||||
<pattern>%highlight(%-5level) %cyan(%logger{20}) - %msg%n</pattern>
|
||||
|
||||
Reference in New Issue
Block a user