Проверить вложения и блоки в каналах

This commit is contained in:
AidarKC
2026-11-21 00:24:25 +03:00
parent 859dbee1f1
commit 792f368175
27 changed files with 786 additions and 137 deletions
@@ -34,9 +34,14 @@ dependencies {
implementation project(':shine-server-db') // модуль для работы с БД содержит и сущности из БД и саму работу с БД
implementation project(':shine-server-geo') // модуль для определения геолокации по IP
testImplementation 'org.junit.jupiter:junit-jupiter:5.11.0'
}
test {
useJUnitPlatform()
}
java {
sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17
@@ -0,0 +1,92 @@
package server.logic.ws_protocol.JSON.handlers.channels;
import java.nio.charset.StandardCharsets;
import java.util.HashSet;
import java.util.Set;
import java.util.regex.Pattern;
/** Только проверка небезопасных входящих маркеров v=2. Исходный TEXT не переписывается. */
final class AttachmentMarkerValidator {
private static final Pattern ROOT = Pattern.compile("[1-9A-HJ-NP-Za-km-z]{32,44}");
private static final Pattern SHA = Pattern.compile("[0-9a-f]{64}");
private static final Pattern TX_ID = Pattern.compile("[A-Za-z0-9_-]{43}");
private static final Pattern MIME = Pattern.compile("(?i)[a-z0-9!#$&^_.+-]+/[a-z0-9!#$&^_.+-]+");
private static final Set<String> ALLOWED = Set.of("v", "nm", "sz", "pr", "sha256", "mm", "ar");
private AttachmentMarkerValidator() { }
static boolean validateLeadingV2Markers(String raw) {
String text = raw == null ? "" : raw;
int offset = 0;
for (int i = 0; i < 10; i++) {
String prefix;
if (text.startsWith("<S:att;", offset)) prefix = "<S:att;";
else if (text.startsWith("<S:attach;", offset)) prefix = "<S:attach;";
else if (text.startsWith("<SHiNE:attach;", offset)) prefix = "<SHiNE:attach;";
else return true;
int start = offset + prefix.length();
int end = text.indexOf('>', start);
if (end < 0 || end - start > 2048 || text.substring(start, end).contains("\n")) return false;
String fields = text.substring(start, end);
if (java.util.Arrays.stream(fields.split(";", -1)).anyMatch(field -> field.matches("v\\s*=\\s*0*2"))) {
if (!validateV2(fields)) return false;
}
offset = end + 1;
if (offset >= text.length()) return true;
if (text.charAt(offset) != '\n') return false;
offset++;
}
// Больше десяти технических тегов трактуем как недопустимые метаданные.
return !text.startsWith("<S:att;", offset) && !text.startsWith("<S:attach;", offset)
&& !text.startsWith("<SHiNE:attach;", offset);
}
private static boolean validateV2(String rawFields) {
String[] fields = rawFields.split(";", -1);
if (fields.length < 4 || !fields[0].equals("v=2")) return false;
Set<String> seen = new HashSet<>();
String name = null, size = null, root = null, sha = null, mime = null, ar = null;
for (String part : fields) {
int index = part.indexOf('=');
if (index <= 0 || part.indexOf('=', index + 1) >= 0) return false;
String key = part.substring(0, index);
String value = part.substring(index + 1);
if (!ALLOWED.contains(key) || !seen.add(key) || value.isEmpty()) return false;
switch (key) {
case "v": if (!value.equals("2")) return false; break;
case "nm": name = value; break;
case "sz": size = value; break;
case "pr": root = value; break;
case "sha256": sha = value; break;
case "mm": mime = value; break;
case "ar": ar = value; break;
default: return false;
}
}
if (name == null || size == null || !seen.contains("v") || (root == null) == (sha == null)) return false;
if (!size.matches("[1-9][0-9]{0,18}")) return false;
try { if (Long.parseLong(size) < 1) return false; } catch (NumberFormatException e) { return false; }
if (root != null && !ROOT.matcher(root).matches()) return false;
if (sha != null && !SHA.matcher(sha).matches()) return false;
if (mime != null && (mime.length() > 127 || !MIME.matcher(mime).matches())) return false;
if (ar != null && !TX_ID.matcher(ar).matches()) return false;
StringBuilder decoded = new StringBuilder();
for (int i = 0; i < name.length(); i++) {
char ch = name.charAt(i);
if (ch == '%') {
if (i + 2 >= name.length()) return false;
String code = name.substring(i + 1, i + 3).toUpperCase(java.util.Locale.ROOT);
ch = switch (code) {
case "25" -> '%'; case "3B" -> ';'; case "3D" -> '=';
case "3C" -> '<'; case "3E" -> '>'; default -> 0;
};
if (ch == 0) return false;
i += 2;
} else if (ch == '<' || ch == '>' || ch == '=' || ch == ';') return false;
if (ch < 32 || ch == 127) return false;
decoded.append(ch);
}
return decoded.toString().getBytes(StandardCharsets.UTF_8).length <= 255;
}
}
@@ -5,6 +5,7 @@ import blockchain.body.BodyRecord;
import blockchain.body.CreateChannelBody;
import blockchain.body.TextLineBody;
import blockchain.body.TextReplyBody;
import server.logic.ws_protocol.JSON.handlers.channels.entyties.Net_GetChannelMessages_Response;
import shine.db.channels.ChannelNameRules;
import shine.db.MsgSubType;
import shine.db.sql.CurrentUsersSql;
@@ -226,6 +227,7 @@ final class ChannelsReadSupport {
} else if (e.body instanceof blockchain.body.StatusActionBody sab) {
ti.text = sab.message;
}
ti.attachmentMetadataValid = AttachmentMarkerValidator.validateLeadingV2Markers(ti.text);
return ti;
} catch (Exception ex) {
return new TextInfo();
@@ -236,7 +238,7 @@ final class ChannelsReadSupport {
String order = asc ? "ASC" : "DESC";
boolean bounded = limit > 0;
String sql = """
SELECT login,bch_name,block_number,block_hash,block_bytes,to_bch_name,to_block_number,to_block_hash,msg_sub_type,this_line_number
SELECT login,bch_name,block_number,block_hash,block_bytes,data_item_id,arweave_publish_pending,arweave_published_at_ms,to_bch_name,to_block_number,to_block_hash,msg_sub_type,this_line_number
FROM blocks
WHERE LOWER(login)=LOWER(?) AND msg_type=? AND msg_sub_type IN (?, ?, ?, ?, ?, ?) AND line_code=?
AND fork_number=shine_canonical_fork(login,(SELECT substring(blockchain_name from '([0-9]{3})$')::INTEGER FROM user_identity_current WHERE LOWER(login)=LOWER(?) LIMIT 1),block_number)
@@ -263,6 +265,9 @@ final class ChannelsReadSupport {
pb.blockNumber = rs.getInt("block_number");
pb.blockHash = rs.getBytes("block_hash");
pb.blockBytes = rs.getBytes("block_bytes");
pb.dataItemId = rs.getBytes("data_item_id");
pb.arweavePublishPending = rs.getBoolean("arweave_publish_pending");
pb.arweavePublishedAtMs = (Long) rs.getObject("arweave_published_at_ms");
pb.toBchName = rs.getString("to_bch_name");
pb.toBlockNumber = (Integer) rs.getObject("to_block_number");
pb.toBlockHash = rs.getBytes("to_block_hash");
@@ -286,7 +291,7 @@ final class ChannelsReadSupport {
static List<PostBlock> versionsForPost(Connection c, String ownerBch, int originalBlock, byte[] originalHash) throws SQLException {
String sql = """
SELECT login,bch_name,block_number,block_hash,block_bytes
SELECT login,bch_name,block_number,block_hash,block_bytes,data_item_id,arweave_publish_pending,arweave_published_at_ms
FROM blocks
WHERE LOWER(login)=LOWER(?) AND msg_type=? AND msg_sub_type=?
AND to_block_number=? AND to_block_hash=?
@@ -309,6 +314,9 @@ final class ChannelsReadSupport {
pb.blockNumber = rs.getInt("block_number");
pb.blockHash = rs.getBytes("block_hash");
pb.blockBytes = rs.getBytes("block_bytes");
pb.dataItemId = rs.getBytes("data_item_id");
pb.arweavePublishPending = rs.getBoolean("arweave_publish_pending");
pb.arweavePublishedAtMs = (Long) rs.getObject("arweave_published_at_ms");
out.add(pb);
}
return out;
@@ -703,12 +711,27 @@ final class ChannelsReadSupport {
|| subType == MsgSubType.TEXT_COURSE;
}
static String dataItemIdBase64Url(byte[] bytes) {
return bytes != null && bytes.length == 32
? java.util.Base64.getUrlEncoder().withoutPadding().encodeToString(bytes) : null;
}
static void setStorageInfo(Net_GetChannelMessages_Response.VersionItem out, byte[] id, boolean pending, Long publishedAt, byte[] raw) {
out.setArweaveDataItemId(dataItemIdBase64Url(id));
out.setArweavePublishPending(pending);
out.setArweavePublishedAtMs(publishedAt);
out.setSignedDataItemBytes(raw == null ? null : raw.length);
}
static final class PostBlock {
String login;
String bchName;
int blockNumber;
byte[] blockHash;
byte[] blockBytes;
byte[] dataItemId;
boolean arweavePublishPending;
Long arweavePublishedAtMs;
String toBchName;
Integer toBlockNumber;
byte[] toBlockHash;
@@ -717,6 +740,7 @@ final class ChannelsReadSupport {
}
static final class TextInfo {
boolean attachmentMetadataValid = true;
String text = "";
long createdAtMs = 0L;
}
@@ -152,7 +152,9 @@ public class Net_GetChannelMessages_Handler implements JsonMessageHandler {
v1.setBlockNumber(post.blockNumber);
v1.setBlockHash(ChannelsReadSupport.toHex(post.blockHash));
v1.setText(postText.text);
v1.setAttachmentMetadataValid(postText.attachmentMetadataValid);
v1.setCreatedAtMs(postText.createdAtMs);
ChannelsReadSupport.setStorageInfo(v1, post.dataItemId, post.arweavePublishPending, post.arweavePublishedAtMs, post.blockBytes);
versionsOut.add(v1);
if (ChannelsReadSupport.supportsEditPostVersions(post.msgSubType)) {
@@ -164,13 +166,20 @@ public class Net_GetChannelMessages_Handler implements JsonMessageHandler {
ve.setBlockNumber(edit.blockNumber);
ve.setBlockHash(ChannelsReadSupport.toHex(edit.blockHash));
ve.setText(editText.text);
ve.setAttachmentMetadataValid(editText.attachmentMetadataValid);
ve.setCreatedAtMs(editText.createdAtMs);
ChannelsReadSupport.setStorageInfo(ve, edit.dataItemId, edit.arweavePublishPending, edit.arweavePublishedAtMs, edit.blockBytes);
versionsOut.add(ve);
}
}
item.setVersions(versionsOut);
item.setVersionsTotal(versionsOut.size());
item.setAttachmentMetadataValid(v1.isAttachmentMetadataValid());
item.setArweaveDataItemId(v1.getArweaveDataItemId());
item.setArweavePublishPending(v1.getArweavePublishPending());
item.setArweavePublishedAtMs(v1.getArweavePublishedAtMs());
item.setSignedDataItemBytes(v1.getSignedDataItemBytes());
Net_GetChannelMessages_Response.VersionItem lastV = versionsOut.get(versionsOut.size() - 1);
item.setText(lastV.getText());
@@ -19,7 +19,6 @@ import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Comparator;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.Map;
import java.util.HashMap;
@@ -116,7 +115,7 @@ public class Net_GetMessageThread_Handler implements JsonMessageHandler {
private List<PostRow> findRepliesAndRatings(Connection c, String toBchName, int toBlockNumber, byte[] toBlockHash, int limit) throws Exception {
String targetLogin = ChannelsReadSupport.loginFromChainName(toBchName);
String sql = """
SELECT login,bch_name,block_number,block_hash,block_bytes,to_login,to_bch_name,to_block_number,to_block_hash,line_code,msg_sub_type,this_line_number
SELECT login,bch_name,block_number,block_hash,block_bytes,data_item_id,arweave_publish_pending,arweave_published_at_ms,to_login,to_bch_name,to_block_number,to_block_hash,line_code,msg_sub_type,this_line_number
FROM blocks
WHERE msg_type=1
AND to_block_number=? AND to_block_hash=?
@@ -153,7 +152,7 @@ public class Net_GetMessageThread_Handler implements JsonMessageHandler {
private PostRow findByLogicalTarget(Connection c, String login, int blockNumber, byte[] blockHash) throws Exception {
String sql = """
SELECT login,bch_name,block_number,block_hash,block_bytes,to_login,to_bch_name,to_block_number,to_block_hash,line_code,msg_sub_type,this_line_number
SELECT login,bch_name,block_number,block_hash,block_bytes,data_item_id,arweave_publish_pending,arweave_published_at_ms,to_login,to_bch_name,to_block_number,to_block_hash,line_code,msg_sub_type,this_line_number
FROM blocks
WHERE LOWER(login)=LOWER(?) AND block_number=? AND block_hash=?
AND fork_number=shine_canonical_fork(login,(SELECT substring(blockchain_name from '([0-9]{3})$')::INTEGER FROM solana_user_pda_current WHERE LOWER(login)=LOWER(?) LIMIT 1),block_number)
@@ -172,7 +171,7 @@ public class Net_GetMessageThread_Handler implements JsonMessageHandler {
private PostRow findByNumber(Connection c, String bchName, int blockNumber) throws Exception {
String sql = """
SELECT login,bch_name,block_number,block_hash,block_bytes,to_login,to_bch_name,to_block_number,to_block_hash,line_code,msg_sub_type,this_line_number
SELECT login,bch_name,block_number,block_hash,block_bytes,data_item_id,arweave_publish_pending,arweave_published_at_ms,to_login,to_bch_name,to_block_number,to_block_hash,line_code,msg_sub_type,this_line_number
FROM blocks
WHERE LOWER(login)=LOWER(?) AND block_number=?
AND fork_number=shine_canonical_fork(login,(SELECT substring(blockchain_name from '([0-9]{3})$')::INTEGER FROM solana_user_pda_current WHERE LOWER(login)=LOWER(?) LIMIT 1),block_number)
@@ -191,7 +190,7 @@ public class Net_GetMessageThread_Handler implements JsonMessageHandler {
private PostRow findByNumberAndHash(Connection c, String bchName, int blockNumber, byte[] blockHash) throws Exception {
String sql = """
SELECT login,bch_name,block_number,block_hash,block_bytes,to_login,to_bch_name,to_block_number,to_block_hash,line_code,msg_sub_type,this_line_number
SELECT login,bch_name,block_number,block_hash,block_bytes,data_item_id,arweave_publish_pending,arweave_published_at_ms,to_login,to_bch_name,to_block_number,to_block_hash,line_code,msg_sub_type,this_line_number
FROM blocks
WHERE LOWER(login)=LOWER(?) AND block_number=? AND block_hash=?
AND fork_number=shine_canonical_fork(login,(SELECT substring(blockchain_name from '([0-9]{3})$')::INTEGER FROM solana_user_pda_current WHERE LOWER(login)=LOWER(?) LIMIT 1),block_number)
@@ -226,6 +225,9 @@ public class Net_GetMessageThread_Handler implements JsonMessageHandler {
row.blockNumber = rs.getInt("block_number");
row.blockHash = rs.getBytes("block_hash");
row.blockBytes = rs.getBytes("block_bytes");
row.dataItemId = rs.getBytes("data_item_id");
row.arweavePublishPending = rs.getBoolean("arweave_publish_pending");
row.arweavePublishedAtMs = (Long) rs.getObject("arweave_published_at_ms");
row.toLogin = rs.getString("to_login");
row.toBchName = rs.getString("to_bch_name");
row.toBlockNumber = (Integer) rs.getObject("to_block_number");
@@ -259,7 +261,13 @@ public class Net_GetMessageThread_Handler implements JsonMessageHandler {
first.setBlockNumber(row.blockNumber);
first.setBlockHash(ChannelsReadSupport.toHex(row.blockHash));
first.setText(base.text);
first.setAttachmentMetadataValid(base.attachmentMetadataValid);
first.setCreatedAtMs(base.createdAtMs);
ChannelsReadSupport.setStorageInfo(first, row.dataItemId, row.arweavePublishPending, row.arweavePublishedAtMs, row.blockBytes);
node.setArweaveDataItemId(first.getArweaveDataItemId());
node.setArweavePublishPending(first.getArweavePublishPending());
node.setArweavePublishedAtMs(first.getArweavePublishedAtMs());
node.setSignedDataItemBytes(first.getSignedDataItemBytes());
versions.add(first);
if (row.msgSubType == MsgSubType.TEXT_REPLY
@@ -275,19 +283,18 @@ public class Net_GetMessageThread_Handler implements JsonMessageHandler {
v.setBlockNumber(edit.blockNumber);
v.setBlockHash(ChannelsReadSupport.toHex(edit.blockHash));
v.setText(et.text);
v.setAttachmentMetadataValid(et.attachmentMetadataValid);
v.setCreatedAtMs(et.createdAtMs);
ChannelsReadSupport.setStorageInfo(v, edit.dataItemId, edit.arweavePublishPending, edit.arweavePublishedAtMs, edit.blockBytes);
versions.add(v);
}
}
node.setVersions(versions);
node.setVersionsTotal(versions.size());
node.setAttachmentMetadataValid(first.isAttachmentMetadataValid());
node.setText(versions.get(versions.size() - 1).getText());
if (row.blockBytes != null) {
node.setRawBlockB64(Base64.getEncoder().encodeToString(row.blockBytes));
}
int[] stats = ChannelsReadSupport.loadStats(c, row.bchName, row.blockNumber, row.blockHash);
node.setLikesCount(stats[0]);
node.setPrimaryLikesCount(stats[3]);
@@ -310,7 +317,7 @@ public class Net_GetMessageThread_Handler implements JsonMessageHandler {
private List<PostRow> findEdits(Connection c, String bch, int targetBlock, byte[] targetHash, int subType) throws Exception {
String sql = """
SELECT login,bch_name,block_number,block_hash,block_bytes,to_login,to_bch_name,to_block_number,to_block_hash,line_code,msg_sub_type,this_line_number
SELECT login,bch_name,block_number,block_hash,block_bytes,data_item_id,arweave_publish_pending,arweave_published_at_ms,to_login,to_bch_name,to_block_number,to_block_hash,line_code,msg_sub_type,this_line_number
FROM blocks
WHERE LOWER(login)=LOWER(?) AND msg_type=1 AND msg_sub_type=?
AND to_block_number=? AND to_block_hash=?
@@ -338,6 +345,9 @@ public class Net_GetMessageThread_Handler implements JsonMessageHandler {
int blockNumber;
byte[] blockHash;
byte[] blockBytes;
byte[] dataItemId;
boolean arweavePublishPending;
Long arweavePublishedAtMs;
String toLogin;
String toBchName;
Integer toBlockNumber;
@@ -159,6 +159,11 @@ public class Net_GetChannelMessages_Response extends Net_Response {
private int repliesCount;
private int ratingsCount;
private int versionsTotal;
private boolean attachmentMetadataValid = true;
private String arweaveDataItemId;
private Boolean arweavePublishPending;
private Long arweavePublishedAtMs;
private Integer signedDataItemBytes;
private List<VersionItem> versions = new ArrayList<>();
public BlockRef getMessageRef() { return messageRef; }
@@ -221,6 +226,17 @@ public class Net_GetChannelMessages_Response extends Net_Response {
public int getRatingsCount() { return ratingsCount; }
public void setRatingsCount(int ratingsCount) { this.ratingsCount = ratingsCount; }
public boolean isAttachmentMetadataValid() { return attachmentMetadataValid; }
public void setAttachmentMetadataValid(boolean value) { this.attachmentMetadataValid = value; }
public String getArweaveDataItemId() { return arweaveDataItemId; }
public void setArweaveDataItemId(String value) { this.arweaveDataItemId = value; }
public Boolean getArweavePublishPending() { return arweavePublishPending; }
public void setArweavePublishPending(Boolean value) { this.arweavePublishPending = value; }
public Long getArweavePublishedAtMs() { return arweavePublishedAtMs; }
public void setArweavePublishedAtMs(Long value) { this.arweavePublishedAtMs = value; }
public Integer getSignedDataItemBytes() { return signedDataItemBytes; }
public void setSignedDataItemBytes(Integer value) { this.signedDataItemBytes = value; }
public int getVersionsTotal() { return versionsTotal; }
public void setVersionsTotal(int versionsTotal) { this.versionsTotal = versionsTotal; }
@@ -234,6 +250,22 @@ public class Net_GetChannelMessages_Response extends Net_Response {
private String blockHash;
private String text;
private long createdAtMs;
private boolean attachmentMetadataValid = true;
private String arweaveDataItemId;
private Boolean arweavePublishPending;
private Long arweavePublishedAtMs;
private Integer signedDataItemBytes;
public boolean isAttachmentMetadataValid() { return attachmentMetadataValid; }
public void setAttachmentMetadataValid(boolean value) { this.attachmentMetadataValid = value; }
public String getArweaveDataItemId() { return arweaveDataItemId; }
public void setArweaveDataItemId(String value) { this.arweaveDataItemId = value; }
public Boolean getArweavePublishPending() { return arweavePublishPending; }
public void setArweavePublishPending(Boolean value) { this.arweavePublishPending = value; }
public Long getArweavePublishedAtMs() { return arweavePublishedAtMs; }
public void setArweavePublishedAtMs(Long value) { this.arweavePublishedAtMs = value; }
public Integer getSignedDataItemBytes() { return signedDataItemBytes; }
public void setSignedDataItemBytes(Integer value) { this.signedDataItemBytes = value; }
public int getVersionIndex() { return versionIndex; }
public void setVersionIndex(int versionIndex) { this.versionIndex = versionIndex; }
@@ -21,13 +21,10 @@ public class Net_GetMessageThread_Response extends Net_Response {
public static class MessageNode extends Net_GetChannelMessages_Response.MessageItem {
private ChannelInfo channelInfo;
private String rawBlockB64;
public ChannelInfo getChannelInfo() { return channelInfo; }
public void setChannelInfo(ChannelInfo channelInfo) { this.channelInfo = channelInfo; }
public String getRawBlockB64() { return rawBlockB64; }
public void setRawBlockB64(String rawBlockB64) { this.rawBlockB64 = rawBlockB64; }
}
public static class ChannelInfo {
@@ -0,0 +1,25 @@
package server.logic.ws_protocol.JSON.handlers.channels;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class AttachmentMarkerValidatorTest {
private static final String PR = "4vJ9JU1bJJE96FWSJKvHsmmFADCg4gpZQff4P3bkLKi";
private static String marker(String fields) { return "<S:att;" + fields + ">\nтекст"; }
@Test void validUnicodeAndEscapes() {
assertTrue(AttachmentMarkerValidator.validateLeadingV2Markers(marker("v=2;nm=Водопад%3Bлето%3D2026.mp4;sz=1837243;pr=" + PR + ";mm=video/mp4")));
assertTrue(AttachmentMarkerValidator.validateLeadingV2Markers("Обычный текст"));
}
@Test void rejectsMalformedV2WithoutChangingBlock() {
for (String fields : new String[]{
"v=2;nm=abc;sz=10;sz=20;pr=" + PR,
"v=2;nm=abc%ZZ;sz=10;pr=" + PR,
"v=2;nm=abc;unknown=x;sz=10;pr=" + PR,
"v=2;nm=abc;sz=-1;pr=" + PR,
"v=2;nm=abc;sz=10;pr=bad",
"nm=abc;v=2;sz=10;pr=" + PR
}) assertFalse(AttachmentMarkerValidator.validateLeadingV2Markers(marker(fields)), fields);
}
}