Обновить хранение вложений R2

This commit is contained in:
AidarKC
2026-11-16 10:47:43 +03:00
parent fed28527ae
commit 1b86bca19a
17 changed files with 321 additions and 276 deletions
@@ -32,6 +32,7 @@ public final class DatabaseInitializer {
public static final int SCHEMA_VERSION_39 = 39;
public static final int SCHEMA_VERSION_40 = 40;
public static final int SCHEMA_VERSION_41 = 41;
public static final int SCHEMA_VERSION_42 = 42;
public static final String POSTGRES_SCHEMA_RESOURCE = "postgres/schema_v1.sql";
public static final String POSTGRES_MIGRATION_V31_RESOURCE = "postgres/migration_v31.sql";
public static final String POSTGRES_MIGRATION_V32_RESOURCE = "postgres/migration_v32.sql";
@@ -44,6 +45,7 @@ public final class DatabaseInitializer {
public static final String POSTGRES_MIGRATION_V39_RESOURCE = "postgres/migration_v39.sql";
public static final String POSTGRES_MIGRATION_V40_RESOURCE = "postgres/migration_v40.sql";
public static final String POSTGRES_MIGRATION_V41_RESOURCE = "postgres/migration_v41.sql";
public static final String POSTGRES_MIGRATION_V42_RESOURCE = "postgres/migration_v42.sql";
private DatabaseInitializer() {}
@@ -179,9 +181,13 @@ public final class DatabaseInitializer {
runSqlScript(conn, POSTGRES_MIGRATION_V41_RESOURCE);
currentVersion = readCurrentSchemaVersion(conn);
}
if (currentVersion != SCHEMA_VERSION_41) {
if (currentVersion == SCHEMA_VERSION_41) {
runSqlScript(conn, POSTGRES_MIGRATION_V42_RESOURCE);
currentVersion = readCurrentSchemaVersion(conn);
}
if (currentVersion != SCHEMA_VERSION_42) {
throw new SQLException(
"Unsupported SHiNE DB v2 schema version: expected 41, found " + currentVersion);
"Unsupported SHiNE DB v2 schema version: expected 42, found " + currentVersion);
}
normalizeBlockchainStateKeysToBase64(conn);
}
@@ -0,0 +1,27 @@
-- SHiNE v42: журнал выдачи разрешений R2 (не подтверждение успешного PUT).
-- В DM записываются только зашифрованные объекты (включая манифест), без имени и MIME.
BEGIN;
CREATE TABLE IF NOT EXISTS public_file_uploads (
id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
user_login TEXT NOT NULL,
file_hash TEXT NOT NULL,
file_size_bytes BIGINT NOT NULL CHECK (file_size_bytes > 0),
disposition TEXT NOT NULL CHECK (disposition IN ('upload_url_issued', 'already_exists')),
requested_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE INDEX IF NOT EXISTS public_file_uploads_user_time_idx ON public_file_uploads (user_login, requested_at DESC);
CREATE INDEX IF NOT EXISTS public_file_uploads_hash_idx ON public_file_uploads (file_hash);
CREATE TABLE IF NOT EXISTS dm_file_uploads (
id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
user_login TEXT NOT NULL,
file_hash TEXT NOT NULL,
file_size_bytes BIGINT NOT NULL CHECK (file_size_bytes > 0),
disposition TEXT NOT NULL CHECK (disposition IN ('upload_url_issued', 'already_exists')),
requested_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE INDEX IF NOT EXISTS dm_file_uploads_user_time_idx ON dm_file_uploads (user_login, requested_at DESC);
CREATE INDEX IF NOT EXISTS dm_file_uploads_hash_idx ON dm_file_uploads (file_hash);
UPDATE db_schema_version SET schema_version = 42, updated_at_ms = (EXTRACT(EPOCH FROM clock_timestamp()) * 1000)::BIGINT WHERE id = 1;
COMMIT;
@@ -93,6 +93,7 @@ public final class R2DmPrepareServlet extends HttpServlet {
}
}
}
R2UploadAuditRecorder.record(req, true, fileId, size, result.path("exists").asBoolean(false));
respond(resp, 200, result);
} catch (Exception error) {
getServletContext().log("R2 DM prepare failed", error);
@@ -85,6 +85,7 @@ public final class R2PrepareServlet extends HttpServlet {
}
}
}
R2UploadAuditRecorder.record(req, false, root, size, out.path("exists").asBoolean(false));
respond(resp, 200, out);
} catch (Exception e) {
getServletContext().log("R2 prepare failure", e);
@@ -0,0 +1,41 @@
package server.files;
import jakarta.servlet.http.HttpServletRequest;
import shine.db.DbController;
import shine.db.dao.ActiveSessionsDAO;
import shine.db.entities.ActiveSessionEntry;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
/**
* Учёт выдачи разрешений R2. ВАЖНО: запись не удостоверяет завершённый PUT.
* Не сохраняет исходные имена и MIME личных файлов.
*/
final class R2UploadAuditRecorder {
private R2UploadAuditRecorder() {}
static void record(HttpServletRequest request, boolean dm, String fileHash, long size, boolean exists)
throws SQLException {
// Заголовок используется только ПОСЛЕ проверки Ed25519-подписи в вызывающем servlet.
String sessionId = request.getHeader("X-Shine-Session-Id");
if (sessionId == null || sessionId.isBlank()) throw new SQLException("Upload session ID missing");
String table = dm ? "dm_file_uploads" : "public_file_uploads";
try (Connection connection = DbController.getInstance().getConnection()) {
ActiveSessionEntry session = ActiveSessionsDAO.getInstance().getBySessionId(connection, sessionId.trim());
if (session == null || session.getLogin() == null || session.getLogin().isBlank()) {
throw new SQLException("Upload session missing for audit");
}
String sql = "INSERT INTO " + table
+ " (user_login, file_hash, file_size_bytes, disposition) VALUES (?, ?, ?, ?)";
try (PreparedStatement statement = connection.prepareStatement(sql)) {
statement.setString(1, session.getLogin());
statement.setString(2, fileHash);
statement.setLong(3, size);
statement.setString(4, exists ? "already_exists" : "upload_url_issued");
statement.executeUpdate();
}
}
}
}