SHA256
WIP: добавить MVP загрузки вложений в Cloudflare R2
Работа ещё не готова: предпросмотр публичных R2-вложений в UI пока не завершён.
This commit is contained in:
@@ -10,5 +10,6 @@ public final class PublicFileApiConfigurator {
|
||||
|
||||
public static void register(ServletContextHandler context) {
|
||||
context.addServlet(new ServletHolder(new PublicFileServlet()), "/files/*");
|
||||
context.addServlet(new ServletHolder(new R2PrepareServlet()), "/api/files/prepare");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -336,6 +336,28 @@ public final class PublicFileServlet extends HttpServlet {
|
||||
return new StoredObjectCheck(Objects.equals(expectedFileId, actual), size);
|
||||
}
|
||||
|
||||
/** Authorize a signed preparation request without exposing the session key. */
|
||||
static void verifyR2Prepare(HttpServletRequest req, String root, long size, String mime) throws IOException {
|
||||
String sessionId = req.getHeader("X-Shine-Session-Id");
|
||||
String timeRaw = req.getHeader("X-Shine-Time-Ms");
|
||||
String signatureRaw = req.getHeader("X-Shine-Signature");
|
||||
if (sessionId == null || timeRaw == null || signatureRaw == null) throw new SecurityException("Missing signed session headers");
|
||||
try {
|
||||
long timeMs = Long.parseLong(timeRaw);
|
||||
if (Math.abs(System.currentTimeMillis() - timeMs) > MAX_AUTH_SKEW_MS) throw new SecurityException("Expired signature");
|
||||
ActiveSessionEntry session = ActiveSessionsDAO.getInstance().getBySessionId(sessionId);
|
||||
if (session == null || session.getSessionKey() == null || session.getSessionKey().isBlank()) throw new SecurityException("Session not found");
|
||||
byte[] signature = Base64Ws.decodeLen(signatureRaw, Ed25519Util.SIGNATURE_LEN, "signature");
|
||||
byte[] publicKey = AuthKeyUtils.parseEd25519PublicKey(session.getSessionKey(), "sessionKey");
|
||||
String preimage = "PUBLIC_R2_PREPARE_V1:" + sessionId + ':' + root + ':' + size + ':' + mime + ':' + timeMs;
|
||||
if (!Ed25519Util.verify(preimage.getBytes(StandardCharsets.UTF_8), signature, publicKey)) throw new SecurityException("Invalid signature");
|
||||
} catch (SQLException e) {
|
||||
throw new IOException("Session database unavailable", e);
|
||||
} catch (RuntimeException e) {
|
||||
throw new SecurityException("Invalid upload 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,114 @@
|
||||
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.Map;
|
||||
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 Pattern MIME = Pattern.compile("^[a-zA-Z0-9!#$&^_.+-]+/[a-zA-Z0-9!#$&^_.+-]+$");
|
||||
private static final long MAX_BYTES = 500L * 1024L * 1024L;
|
||||
|
||||
@Override protected void doOptions(HttpServletRequest req, HttpServletResponse resp) {
|
||||
cors(req, resp); resp.setStatus(204);
|
||||
}
|
||||
|
||||
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
|
||||
cors(req, resp);
|
||||
try {
|
||||
if (req.getContentLengthLong() > 4096) { fail(resp, 413, "Request too large"); return; }
|
||||
JsonNode input = JSON.readTree(req.getInputStream());
|
||||
if (input == null) { fail(resp, 400, "Missing JSON body"); return; }
|
||||
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) {
|
||||
fail(resp, 400, "Invalid root, size or MIME"); return;
|
||||
}
|
||||
// The same authenticated session signing pattern as /files, with a distinct domain separator.
|
||||
try { PublicFileServlet.verifyR2Prepare(req, root, size, mime); }
|
||||
catch (SecurityException e) { 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.publicBucket");
|
||||
if (bucket == null || bucket.isBlank()) bucket = "shine-files";
|
||||
if (endpoint == null || accessKey == null || secret == null) { fail(resp, 503, "R2 is not configured"); return; }
|
||||
var creds = StaticCredentialsProvider.create(AwsBasicCredentials.create(accessKey, secret));
|
||||
var httpEndpoint = URI.create(endpoint);
|
||||
ObjectNode out = JSON.createObjectNode();
|
||||
out.put("fileUrl", "https://files.shineup.me/" + root);
|
||||
try (S3Client s3 = S3Client.builder().region(Region.of("auto")).endpointOverride(httpEndpoint)
|
||||
.credentialsProvider(creds).forcePathStyle(true).build()) {
|
||||
try {
|
||||
var head = s3.headObject(HeadObjectRequest.builder().bucket(bucket).key(root).build());
|
||||
if (head.contentLength() != size) { fail(resp, 409, "Existing object size mismatch"); return; }
|
||||
out.put("exists", true);
|
||||
} catch (software.amazon.awssdk.services.s3.model.S3Exception e) {
|
||||
if (e.statusCode() != 404) throw e;
|
||||
out.put("exists", false);
|
||||
// Signature binds Content-Type and the no-overwrite condition. No permanent API key in browser.
|
||||
var put = PutObjectRequest.builder().bucket(bucket).key(root).contentType(mime)
|
||||
.ifNoneMatch("*").build();
|
||||
try (S3Presigner presigner = S3Presigner.builder().region(Region.of("auto"))
|
||||
.endpointOverride(httpEndpoint).credentialsProvider(creds).serviceConfiguration(
|
||||
software.amazon.awssdk.services.s3.S3Configuration.builder().pathStyleAccessEnabled(true).build()).build()) {
|
||||
var signed = presigner.presignPutObject(PutObjectPresignRequest.builder()
|
||||
.signatureDuration(Duration.ofMinutes(30)).putObjectRequest(put).build());
|
||||
out.put("uploadUrl", signed.url().toString());
|
||||
ObjectNode headers = out.putObject("requiredHeaders");
|
||||
for (Map.Entry<String, java.util.List<String>> entry : signed.signedHeaders().entrySet()) {
|
||||
if (!entry.getKey().equalsIgnoreCase("host")) headers.put(entry.getKey(), String.join(",", entry.getValue()));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
respond(resp, 200, out);
|
||||
} catch (Exception e) {
|
||||
getServletContext().log("R2 prepare failure", e);
|
||||
fail(resp, 503, "R2 upload preparation failed");
|
||||
}
|
||||
}
|
||||
|
||||
private static String setting(String env, String property) {
|
||||
String value = System.getenv(env);
|
||||
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 response, int status, String message) throws IOException {
|
||||
var json = JSON.createObjectNode(); json.put("error", message); respond(response, status, json);
|
||||
}
|
||||
private static void respond(HttpServletResponse response, int status, ObjectNode json) throws IOException {
|
||||
response.setStatus(status); response.setContentType("application/json;charset=UTF-8");
|
||||
JSON.writeValue(response.getOutputStream(), json);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user