SHA256
Перевести вложения DM на R2 и обновить файловый API
This commit is contained in:
@@ -10,5 +10,6 @@ public final class DmFileApiConfigurator {
|
||||
|
||||
public static void register(ServletContextHandler context) {
|
||||
context.addServlet(new ServletHolder(new DmFileServlet()), "/dm-files/*");
|
||||
context.addServlet(new ServletHolder(new R2DmPrepareServlet()), "/api/dm-files/prepare");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -247,6 +247,36 @@ public final class DmFileServlet extends HttpServlet {
|
||||
|
||||
private record StoredObjectCheck(boolean valid, long size) {}
|
||||
|
||||
/** Проверка отдельной Ed25519-подписи запроса временной ссылки R2, без передачи ciphertext. */
|
||||
static void verifyR2Prepare(HttpServletRequest req, String fileId, long encryptedSize) throws IOException {
|
||||
String sessionId = req.getHeader(HEADER_SESSION_ID);
|
||||
String timestamp = req.getHeader(HEADER_TIME_MS);
|
||||
String signatureText = req.getHeader(HEADER_SIGNATURE);
|
||||
if (sessionId == null || timestamp == null || signatureText == null) {
|
||||
throw new SecurityException("Missing signed session headers");
|
||||
}
|
||||
try {
|
||||
long timeMs = Long.parseLong(timestamp);
|
||||
if (Math.abs(System.currentTimeMillis() - timeMs) > MAX_AUTH_SKEW_MS) {
|
||||
throw new SecurityException("Expired signed request");
|
||||
}
|
||||
ActiveSessionEntry session = ActiveSessionsDAO.getInstance().getBySessionId(sessionId);
|
||||
if (session == null || session.getSessionKey() == null || session.getSessionKey().isBlank()) {
|
||||
throw new SecurityException("Session not found");
|
||||
}
|
||||
byte[] sig = Base64Ws.decodeLen(signatureText, Ed25519Util.SIGNATURE_LEN, "signature");
|
||||
byte[] pub = AuthKeyUtils.parseEd25519PublicKey(session.getSessionKey(), "sessionKey");
|
||||
String message = "DM_R2_PREPARE_V1:" + sessionId + ':' + fileId + ':' + encryptedSize + ':' + timeMs;
|
||||
if (!Ed25519Util.verify(message.getBytes(StandardCharsets.UTF_8), sig, pub)) {
|
||||
throw new SecurityException("Invalid signature");
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
throw new IOException("Session lookup failed", e);
|
||||
} catch (RuntimeException e) {
|
||||
throw new SecurityException("Invalid DM R2 authorization", e);
|
||||
}
|
||||
}
|
||||
|
||||
private UploadAuth readAndVerifyUploadAuth(HttpServletRequest req, String fileId) throws AuthFailure {
|
||||
String sessionId = requiredHeader(req, HEADER_SESSION_ID);
|
||||
String timeRaw = requiredHeader(req, HEADER_TIME_MS);
|
||||
|
||||
@@ -0,0 +1,129 @@
|
||||
package server.files;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import jakarta.servlet.http.HttpServlet;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
|
||||
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
|
||||
import software.amazon.awssdk.regions.Region;
|
||||
import software.amazon.awssdk.services.s3.S3Client;
|
||||
import software.amazon.awssdk.services.s3.model.HeadObjectRequest;
|
||||
import software.amazon.awssdk.services.s3.model.PutObjectRequest;
|
||||
import software.amazon.awssdk.services.s3.presigner.S3Presigner;
|
||||
import software.amazon.awssdk.services.s3.presigner.model.PutObjectPresignRequest;
|
||||
import utils.config.AppConfig;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.URI;
|
||||
import java.time.Duration;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* Выдача временных PUT в shine-dm. Сервер не получает ciphertext, AES-key и MIME исходного файла.
|
||||
* Идентификатор объекта: Base58(SHA-256(ciphertext)); доступ к GET — по публичному домену R2.
|
||||
*/
|
||||
public final class R2DmPrepareServlet extends HttpServlet {
|
||||
private static final ObjectMapper JSON = new ObjectMapper();
|
||||
private static final Pattern FILE_ID = Pattern.compile("^[1-9A-HJ-NP-Za-km-z]{32,44}$");
|
||||
private static final long MAX_OBJECT_BYTES = 8L * 1024L * 1024L + 16L;
|
||||
private static final String CONTENT_TYPE = "application/octet-stream";
|
||||
private static final String PUBLIC_BASE = "https://dm-files.shineup.me/";
|
||||
|
||||
@Override protected void doOptions(HttpServletRequest req, HttpServletResponse resp) {
|
||||
cors(req, resp);
|
||||
resp.setStatus(HttpServletResponse.SC_NO_CONTENT);
|
||||
}
|
||||
|
||||
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
|
||||
cors(req, resp);
|
||||
try {
|
||||
if (req.getContentLengthLong() > 2048) { fail(resp, 413, "Request too large"); return; }
|
||||
JsonNode input = JSON.readTree(req.getInputStream());
|
||||
if (input == null) { fail(resp, 400, "Missing JSON body"); return; }
|
||||
String fileId = input.path("fileId").asText("").trim();
|
||||
long size = input.path("size").asLong(-1L);
|
||||
if (!FILE_ID.matcher(fileId).matches() || size < 16 || size > MAX_OBJECT_BYTES) {
|
||||
fail(resp, 400, "Invalid ciphertext ID or size"); return;
|
||||
}
|
||||
try { DmFileServlet.verifyR2Prepare(req, fileId, size); }
|
||||
catch (SecurityException denied) { fail(resp, 401, "Unauthorized"); return; }
|
||||
String endpoint = setting("R2_ENDPOINT", "r2.endpoint");
|
||||
String accessKey = setting("R2_ACCESS_KEY_ID", "r2.accessKeyId");
|
||||
String secret = setting("R2_SECRET_ACCESS_KEY", "r2.secretAccessKey");
|
||||
String bucket = AppConfig.getInstance().getParam("r2.dmBucket");
|
||||
if (bucket == null || bucket.isBlank()) bucket = "shine-dm";
|
||||
if (endpoint == null || accessKey == null || secret == null) {
|
||||
fail(resp, 503, "R2 is not configured"); return;
|
||||
}
|
||||
var credentials = StaticCredentialsProvider.create(AwsBasicCredentials.create(accessKey, secret));
|
||||
var apiEndpoint = URI.create(endpoint);
|
||||
ObjectNode result = JSON.createObjectNode();
|
||||
result.put("fileUrl", PUBLIC_BASE + fileId);
|
||||
try (S3Client s3 = S3Client.builder().region(Region.of("auto"))
|
||||
.endpointOverride(apiEndpoint).credentialsProvider(credentials).forcePathStyle(true).build()) {
|
||||
try {
|
||||
var head = s3.headObject(HeadObjectRequest.builder().bucket(bucket).key(fileId).build());
|
||||
if (head.contentLength() != size) { fail(resp, 409, "Existing object size mismatch"); return; }
|
||||
result.put("exists", true);
|
||||
} catch (software.amazon.awssdk.services.s3.model.S3Exception notFound) {
|
||||
if (notFound.statusCode() != 404) throw notFound;
|
||||
result.put("exists", false);
|
||||
var put = PutObjectRequest.builder().bucket(bucket).key(fileId)
|
||||
.contentType(CONTENT_TYPE).contentLength(size).ifNoneMatch("*").build();
|
||||
try (S3Presigner signer = S3Presigner.builder().region(Region.of("auto"))
|
||||
.endpointOverride(apiEndpoint).credentialsProvider(credentials)
|
||||
.serviceConfiguration(software.amazon.awssdk.services.s3.S3Configuration.builder()
|
||||
.pathStyleAccessEnabled(true).build()).build()) {
|
||||
var signed = signer.presignPutObject(PutObjectPresignRequest.builder()
|
||||
.signatureDuration(Duration.ofMinutes(30)).putObjectRequest(put).build());
|
||||
result.put("uploadUrl", signed.url().toString());
|
||||
ObjectNode headers = result.putObject("requiredHeaders");
|
||||
for (Map.Entry<String, List<String>> entry : signed.signedHeaders().entrySet()) {
|
||||
// Content-Length браузер выставляет автоматически из Uint8Array.
|
||||
if (!entry.getKey().equalsIgnoreCase("host")
|
||||
&& !entry.getKey().equalsIgnoreCase("content-length")) {
|
||||
headers.put(entry.getKey(), String.join(",", entry.getValue()));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
respond(resp, 200, result);
|
||||
} catch (Exception error) {
|
||||
getServletContext().log("R2 DM prepare failed", error);
|
||||
fail(resp, 503, "R2 DM upload preparation failed");
|
||||
}
|
||||
}
|
||||
|
||||
private static String setting(String environment, String property) {
|
||||
String value = System.getenv(environment);
|
||||
if (value == null || value.isBlank()) value = AppConfig.getInstance().getParam(property);
|
||||
return value == null || value.isBlank() ? null : value.trim();
|
||||
}
|
||||
|
||||
private static void cors(HttpServletRequest req, HttpServletResponse resp) {
|
||||
String origin = req.getHeader("Origin");
|
||||
if ("https://shineup.me".equals(origin) || "https://www.shineup.me".equals(origin)
|
||||
|| "https://test.shineup.me".equals(origin)
|
||||
|| "https://t2.shineup.me".equals(origin)) {
|
||||
resp.setHeader("Access-Control-Allow-Origin", origin);
|
||||
resp.setHeader("Vary", "Origin");
|
||||
}
|
||||
resp.setHeader("Access-Control-Allow-Methods", "POST, OPTIONS");
|
||||
resp.setHeader("Access-Control-Allow-Headers", "Content-Type, X-Shine-Session-Id, X-Shine-Time-Ms, X-Shine-Signature");
|
||||
}
|
||||
|
||||
private static void fail(HttpServletResponse resp, int status, String message) throws IOException {
|
||||
ObjectNode obj = JSON.createObjectNode(); obj.put("error", message); respond(resp, status, obj);
|
||||
}
|
||||
private static void respond(HttpServletResponse resp, int status, ObjectNode json) throws IOException {
|
||||
resp.setStatus(status);
|
||||
resp.setContentType("application/json;charset=UTF-8");
|
||||
JSON.writeValue(resp.getOutputStream(), json);
|
||||
}
|
||||
}
|
||||
@@ -18,6 +18,7 @@ import utils.config.AppConfig;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.URI;
|
||||
import java.math.BigInteger;
|
||||
import java.time.Duration;
|
||||
import java.util.Map;
|
||||
import java.util.regex.Pattern;
|
||||
@@ -25,7 +26,8 @@ import java.util.regex.Pattern;
|
||||
/** Only signs single-object uploads. File contents never pass through SHiNE. */
|
||||
public final class R2PrepareServlet extends HttpServlet {
|
||||
private static final ObjectMapper JSON = new ObjectMapper();
|
||||
private static final Pattern ROOT = Pattern.compile("^[A-Za-z0-9_-]{43}$");
|
||||
private static final String BASE58_ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
|
||||
private static final Pattern ROOT = Pattern.compile("^[1-9A-HJ-NP-Za-km-z]{32,44}$");
|
||||
private static final Pattern MIME = Pattern.compile("^[a-zA-Z0-9!#$&^_.+-]+/[a-zA-Z0-9!#$&^_.+-]+$");
|
||||
private static final long MAX_BYTES = 500L * 1024L * 1024L;
|
||||
|
||||
@@ -42,7 +44,7 @@ public final class R2PrepareServlet extends HttpServlet {
|
||||
String root = input.path("pr").asText("");
|
||||
String mime = input.path("mm").asText("application/octet-stream").trim();
|
||||
long size = input.path("size").asLong(-1);
|
||||
if (!ROOT.matcher(root).matches() || size < 1 || size > MAX_BYTES || !MIME.matcher(mime).matches() || mime.length() > 127) {
|
||||
if (!validPiecesRoot(root) || size < 1 || size > MAX_BYTES || !MIME.matcher(mime).matches() || mime.length() > 127) {
|
||||
fail(resp, 400, "Invalid root, size or MIME"); return;
|
||||
}
|
||||
// The same authenticated session signing pattern as /files, with a distinct domain separator.
|
||||
@@ -90,6 +92,22 @@ public final class R2PrepareServlet extends HttpServlet {
|
||||
}
|
||||
}
|
||||
|
||||
/** Только канонический Base58 от ровно 32 байт Merkle-корня (не Base64URL). */
|
||||
static boolean validPiecesRoot(String root) {
|
||||
if (root == null || !ROOT.matcher(root).matches()) return false;
|
||||
int leadingZeroBytes = 0;
|
||||
while (leadingZeroBytes < root.length() && root.charAt(leadingZeroBytes) == '1') leadingZeroBytes++;
|
||||
BigInteger value = BigInteger.ZERO;
|
||||
for (int i = leadingZeroBytes; i < root.length(); i++) {
|
||||
int digit = BASE58_ALPHABET.indexOf(root.charAt(i));
|
||||
if (digit < 0) return false;
|
||||
value = value.multiply(BigInteger.valueOf(58)).add(BigInteger.valueOf(digit));
|
||||
}
|
||||
// BigInteger не хранит ведущие нулевые байты; их кодируют символы '1'.
|
||||
int dataBytes = value.signum() == 0 ? 0 : (value.bitLength() + 7) / 8;
|
||||
return leadingZeroBytes + dataBytes == 32;
|
||||
}
|
||||
|
||||
private static String setting(String env, String property) {
|
||||
String value = System.getenv(env);
|
||||
if (value == null || value.isBlank()) value = AppConfig.getInstance().getParam(property);
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
package server.files;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class R2PrepareServletTest {
|
||||
|
||||
@Test
|
||||
void acceptsCanonicalBase58PiecesRootsOf32Bytes() {
|
||||
assertTrue(R2PrepareServlet.validPiecesRoot("11111111111111111111111111111111"));
|
||||
assertTrue(R2PrepareServlet.validPiecesRoot("4vJ9JU1bJJE96FWSJKvHsmmFADCg4gpZQff4P3bkLKi"));
|
||||
assertTrue(R2PrepareServlet.validPiecesRoot("JEKNVnkbo3jma5nREBBJCDoXFVeKkD56V3xKrvRmWxFG"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsNonBase58AndWrongSizeRoots() {
|
||||
assertFalse(R2PrepareServlet.validPiecesRoot(null));
|
||||
assertFalse(R2PrepareServlet.validPiecesRoot(""));
|
||||
assertFalse(R2PrepareServlet.validPiecesRoot("A".repeat(42) + "_"));
|
||||
assertFalse(R2PrepareServlet.validPiecesRoot("A".repeat(42) + "-"));
|
||||
assertFalse(R2PrepareServlet.validPiecesRoot("O".repeat(44)));
|
||||
assertFalse(R2PrepareServlet.validPiecesRoot("1".repeat(31)));
|
||||
assertFalse(R2PrepareServlet.validPiecesRoot("1".repeat(33)));
|
||||
assertFalse(R2PrepareServlet.validPiecesRoot("A".repeat(45)));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user