From 0a478b600c57d1df10a91a4918e9ffc125df4c04 Mon Sep 17 00:00:00 2001 From: Command1264 Date: Mon, 28 Sep 2026 07:12:46 +0800 Subject: [PATCH] feat: add offline player anonymization across storage backends --- .gitignore | 1 + README.md | 2 +- docs/README.zh-TW.md | 2 + docs/adr/0005-offline-player-anonymization.md | 30 ++ docs/operations/json-storage.md | 2 +- docs/operations/mysql-storage.md | 2 +- docs/operations/offline-anonymization.md | 48 +++ docs/spec/invitecode-1.0.md | 2 +- .../core/InvitationAdministration.kt | 4 +- .../platform/bukkit/NetworkAddressHasher.kt | 15 + .../bukkit/NetworkAddressHasherTest.kt | 13 + invitecode-plugin/build.gradle.kts | 2 + .../invitecode/plugin/InviteCodePlugin.kt | 11 +- .../invitecode/plugin/JsonRuntimeBootstrap.kt | 28 +- .../plugin/MysqlRuntimeBootstrap.kt | 3 +- .../invitecode/plugin/OfflineAnonymizeMain.kt | 210 ++++++++++++ .../plugin/SqliteRuntimeBootstrap.kt | 5 +- .../plugin/OfflineAnonymizeMainTest.kt | 43 +++ .../storage/json/JsonInviteCodeStorage.kt | 63 +++- .../json/JsonOfflineAnonymizationTest.kt | 64 ++++ .../storage/sql/CodeReservationKey.kt | 10 + .../storage/sql/MysqlInviteCodeStorage.kt | 7 +- .../storage/sql/MysqlSchemaMigrator.kt | 64 +++- .../storage/sql/OfflinePlayerAnonymizer.kt | 302 ++++++++++++++++++ .../storage/sql/SqliteIdentityRecords.kt | 26 +- .../storage/sql/SqliteInviteCodeStorage.kt | 70 +++- .../storage/sql/SqliteSchemaMigrator.kt | 12 + .../mysql/V2__reserved_code_hashes.sql | 6 + .../storage/sql/MysqlIntegrationTest.kt | 57 +++- .../sql/OfflinePlayerAnonymizerTest.kt | 279 ++++++++++++++++ 30 files changed, 1332 insertions(+), 51 deletions(-) create mode 100644 docs/adr/0005-offline-player-anonymization.md create mode 100644 docs/operations/offline-anonymization.md create mode 100644 invitecode-plugin/src/main/kotlin/io/github/command1264/invitecode/plugin/OfflineAnonymizeMain.kt create mode 100644 invitecode-plugin/src/test/kotlin/io/github/command1264/invitecode/plugin/OfflineAnonymizeMainTest.kt create mode 100644 invitecode-storage-json/src/test/kotlin/io/github/command1264/invitecode/storage/json/JsonOfflineAnonymizationTest.kt create mode 100644 invitecode-storage-sql/src/main/kotlin/io/github/command1264/invitecode/storage/sql/CodeReservationKey.kt create mode 100644 invitecode-storage-sql/src/main/kotlin/io/github/command1264/invitecode/storage/sql/OfflinePlayerAnonymizer.kt create mode 100644 invitecode-storage-sql/src/main/resources/mysql/V2__reserved_code_hashes.sql create mode 100644 invitecode-storage-sql/src/test/kotlin/io/github/command1264/invitecode/storage/sql/OfflinePlayerAnonymizerTest.kt diff --git a/.gitignore b/.gitignore index 96aec93..1a1fafa 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,5 @@ .gradle/ +.kotlin/ **/build/ .idea/ *.iml diff --git a/README.md b/README.md index 662d009..4e3e5e2 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@ InviteCode is a Kotlin invitation and referral rewards plugin for Spigot and Pap The project is currently `0.1.0-SNAPSHOT`. It builds one Java 8 compatible plugin JAR and keeps newer Minecraft APIs behind isolated adapters. SQLite and MySQL 8.4 are production storage backends; JSON is available for small single-instance installations. Folia 26.1.2 has passed an isolated experimental smoke test; optional integrations and the final player experience still require release-stage acceptance. -The complete maintainer guide is in [繁體中文](docs/README.zh-TW.md) and is the primary maintained documentation. See also the [product specification](docs/spec/invitecode-1.0.md), [Bukkit operations](docs/operations/bukkit-workflow.md), [JSON setup](docs/operations/json-storage.md), and [MySQL setup](docs/operations/mysql-storage.md). These documents are maintained in Traditional Chinese. +The complete maintainer guide is in [繁體中文](docs/README.zh-TW.md) and is the primary maintained documentation. See also the [product specification](docs/spec/invitecode-1.0.md), [Bukkit operations](docs/operations/bukkit-workflow.md), [JSON setup](docs/operations/json-storage.md), [MySQL setup](docs/operations/mysql-storage.md), and [offline anonymization](docs/operations/offline-anonymization.md). These documents are maintained in Traditional Chinese. ## Build diff --git a/docs/README.zh-TW.md b/docs/README.zh-TW.md index 63d3b08..96aa0f1 100644 --- a/docs/README.zh-TW.md +++ b/docs/README.zh-TW.md @@ -72,6 +72,8 @@ JSON 以版本化、可閱讀的資料快照作為持久化來源,沿用 SQLit Claim 防濫用只保存具期限的 HMAC-SHA-256 網路雜湊,不保存原始 IP;預設保留 30 天,並可設定相符時 `ALLOW`、`WARN` 或 `DENY`。SQLite 的 `anti-abuse.key` 由首次初始化建立,需隨 SQLite 備份且不得提交版本控制;MySQL 則使用所有實例共用的外部密鑰。 +玩家資料匿名化須在所有實例停止後,透過獨立維護工具預覽、備份並執行;它保留歷史關係,但同一 Minecraft UUID 再登入會視為新玩家。SQLite schema 9、MySQL schema 2 及 JSON snapshot schema 9 的既有資料升級方式與完整驗證步驟見 [`offline-anonymization.md`](./operations/offline-anonymization.md)。 + ## Qualification Policy `QualificationPolicy` 使用 OR group 包含 AND condition;每次解析都會依正規化內容產生不可變的 SHA-256 revision。`QualificationEvaluator` 對 condition 依序短路求值,provider 缺失或執行失敗時安全地產生 `UNKNOWN`/設定的 `UNSATISFIED`,不會因此讓 Invitation qualified。 diff --git a/docs/adr/0005-offline-player-anonymization.md b/docs/adr/0005-offline-player-anonymization.md new file mode 100644 index 0000000..1e5ff1e --- /dev/null +++ b/docs/adr/0005-offline-player-anonymization.md @@ -0,0 +1,30 @@ +# 離線匿名化玩家資料 + +狀態:已接受(2026-09-28,Issue #25) + +## 背景 + +`CONTEXT.md` 的 Anonymized Player 必須保留 Invitation、Qualification、Reward 與稽核的歷史關係,但不能繼續以 Minecraft UUID、名稱或 IP 雜湊識別原玩家。現有三種 backend 的 `player_id` 都直接使用 Minecraft UUID,且 Reward、Audit 與自由文字欄位可能再次暴露身分。單純清空 `last_known_name` 不是匿名化。 + +## 已確認的產品決定 + +- 匿名化後,原玩家重新加入時視為全新玩家;舊 Minecraft UUID 不得再與歷史紀錄建立資料庫對應。 +- 若相關 Reward Action 為 `PENDING`、`PROCESSING` 或 `UNCERTAIN`,拒絕匿名化,先由管理員依現有復原流程處理。 +- 相關稽核原因與獎勵內容中的自由文字可以不可逆地遮蔽,但保留事件種類、狀態與時間。 +- 以離線維護工具執行:先停止所有連至該 backend 的 InviteCode 實例並備份,不從遊戲中的 `/ic` 指令執行。 + +## 決定方案 + +維護工具在選定 backend 的單一交易中,為目標玩家產生隨機且未使用的歷史 UUID,重新指向所有歷史關係及獎勵收件者,刪除舊玩家主體、名稱、網路雜湊與登入日期。這個歷史 UUID 只供內部維持關聯;它不是新的 Minecraft 玩家 UUID。所有直接含有舊 UUID 或玩家名稱的相關文字須遮蔽或替換。既有 Reward 的冪等鍵與衍生識別碼也要檢查,避免可用已知 Minecraft UUID 反算;完成前不得開放服務。 + +管理員名稱可能出現在其他玩家的稽核或獎勵轉移紀錄;這些純文字操作者/原因會依名稱搜尋並遮蔽,不只依玩家外鍵選取。交易結束前檢查原 UUID 與名稱是否殘留於內部資料;若仍留在不可安全改寫的非關聯獎勵 payload 等欄位,整筆回滾並要求管理員先處理,以免影響其他玩家尚未交付的獎勵。 + +舊 Invite Code 必須失效,且不得再連到隨機歷史 UUID。為避免舊碼被重新發給其他玩家,以既有防濫用密鑰的獨立用途 HMAC 保存碼保留值,並在新碼產生時檢查;只有資料庫而沒有密鑰時,不應能有效枚舉短碼,保留值也不記錄原 Minecraft UUID。密鑰外洩時仍可能枚舉,須與資料庫分開保護。這需要明確的 SQLite/MySQL schema 版本與 JSON 格式處理,既有資料只走明確 migration。 + +工具先唯讀預檢:backend 與版本、密鑰、目標玩家、所有關聯及未完成獎勵;執行時再確認目的歷史 ID 不存在,並顯示將變更的資料範圍。只有管理員明確提供指定 UUID、停止所有實例及備份確認才執行。稽核事件採固定的隱私請求理由,不在資料庫保存可能重新識別玩家的自由文字原因。失敗或中斷時,交易回滾且來源可重試;若回滾狀態無法判斷,停止並要求檢查,不自動再次執行。JSON 必須沿用其原子快照寫入與前一份資料備份。 + +## 驗證界線 + +自動化驗證要檢查三個 backend 的歷史關係、名稱/網路雜湊移除、舊 UUID 不可查、新登入建立新玩家、舊碼不可再 Claim 或重新分配、Reward 狀態與時間保留,以及冪等鍵重建後仍保持唯一;另測故障回滾、並行維護工具、JSON 重啟與工具只接受明確目標。不使用正式玩家資料。MySQL 整合案例需要隔離的 8.4 測試服務,沒有該環境時不得把跳過誤報為通過。 + +匿名化不能抹去既有備份、伺服器 log、第三方插件或玩家自行保存的截圖/聊天紀錄;維運文件須說明備份保留及外部資料的獨立處理。保留精確的歷史時間與關係,也可能讓持有外部對照資料的人推測身分,不能宣稱絕對不可識別。 diff --git a/docs/operations/json-storage.md b/docs/operations/json-storage.md index 4668218..cf29433 100644 --- a/docs/operations/json-storage.md +++ b/docs/operations/json-storage.md @@ -4,6 +4,6 @@ JSON backend 適合小型單一伺服器、測試與資料交換。將 `plugins/ JSON 檔是唯一的持久化資料來源,內含 `format-version`、`schema-version` 與按資料表分組的記錄;執行時使用暫存 SQLite 工作檔沿用現有交易、唯一性及稽核約束。每次成功寫入都會重新輸出整份 JSON,以同資料夾暫存檔原子替換正式檔,並將替換前的快照保留為 `invitecode.json.previous`(實際名稱跟隨 `json.file`)。`.lock` sidecar 以作業系統檔案鎖阻止兩個程序同時開啟;程序異常結束後檔案可能留存,鎖會由作業系統釋放,不應僅因檔案存在而刪除它。 -每次寫入的成本隨整體資料量成長,不能像 MySQL 一樣讓多個插件實例共用同一份資料,也不應用於高併發或大型伺服器。JSON 格式供檢視與交換,但手動更改記錄可能破壞領域約束。切換 backend 不會自動搬移資料。JSON 格式與內部 schema 版本不相符時會拒絕開啟;目前沒有既有 JSON 檔的線上升級指令。 +每次寫入的成本隨整體資料量成長,不能像 MySQL 一樣讓多個插件實例共用同一份資料,也不應用於高併發或大型伺服器。JSON 格式供檢視與交換,但手動更改記錄可能破壞領域約束。切換 backend 不會自動搬移資料。JSON 格式與內部 schema 版本不相符時會拒絕開啟;schema 8 升至 9 須使用[離線維護工具](./offline-anonymization.md),沒有線上升級指令。 若 JSON 損毀或版本不支援,插件會進入維護模式,保留原檔,**不會**把它當成空白資料重新初始化。先停止伺服器並備份正式 JSON、`.previous` 及 `anti-abuse.key`。檢查錯誤訊息與版本;若上一份快照有效,可在伺服器停機時由管理員將 `.previous` 複製回正式檔,再啟動驗證。這會失去上一份快照之後的變更。不要重新產生 `anti-abuse.key`:它是 HMAC 密鑰,應與 JSON 同時備份。若寫入或原子替換失敗,當次程序會停止後續寫入;修正磁碟問題後重啟並檢查最後一份有效快照。 diff --git a/docs/operations/mysql-storage.md b/docs/operations/mysql-storage.md index 8335a5d..afcf2d6 100644 --- a/docs/operations/mysql-storage.md +++ b/docs/operations/mysql-storage.md @@ -42,7 +42,7 @@ $env:INVITECODE_NETWORK_SECRET = [Convert]::ToBase64String( 新 database 首次啟動時,插件會取得 MySQL advisory lock,寫入含 checksum 的 migration ledger,依序建立表並逐一檢查欄位、索引、外鍵與儲存引擎。MySQL DDL 無法像 SQLite 一樣完整交易回滾;若在建表途中中斷,ledger 會維持 `APPLYING`。下次啟動只在既有表通過結構檢查時建立剩餘的表;結構不同時進入維護模式,保留資料供人工檢查。完成後 ledger 為 `APPLIED`,後續啟動只檢查版本與結構。 -既有 schema 的版本更新須先備份、暫停所有使用同一 database 的插件實例,再執行 `/invitecode admin storage migrate MYSQL `。`doctor` 僅讀取健康狀態,不執行 migration。只有資料庫已建立而 schema 為全新的情況才會在一般啟動時自動建表;選擇不同 backend 並不搬移既有資料。不要在兩個 backend 同時收集正式玩家資料後直接改回設定。 +既有 schema 的版本更新須先備份、暫停所有使用同一 database 的插件實例,再執行 `/invitecode admin storage migrate MYSQL `;schema 1 升至 2 也可使用[離線維護工具](./offline-anonymization.md)與既有 dump。`doctor` 僅讀取健康狀態,不執行 migration。只有資料庫已建立而 schema 為全新的情況才會在一般啟動時自動建表;選擇不同 backend 並不搬移既有資料。不要在兩個 backend 同時收集正式玩家資料後直接改回設定。 ## 驗證 diff --git a/docs/operations/offline-anonymization.md b/docs/operations/offline-anonymization.md new file mode 100644 index 0000000..da184a3 --- /dev/null +++ b/docs/operations/offline-anonymization.md @@ -0,0 +1,48 @@ +# 離線匿名化玩家資料 + +此維護工具只處理指定 Minecraft UUID。它把歷史關係改掛到隨機歷史 ID、刪除名稱、登入日期和網路雜湊、遮蔽相關自由文字,並以防濫用密鑰的獨立 HMAC 保留舊邀請碼,避免重新分配。匿名化後同一玩家再加入會建立全新資料。工具不從遊戲指令執行。 + +## 執行前 + +1. 停止**所有**連到相同 backend 的 InviteCode 實例,確認沒有仍在執行的伺服器或維護工具。`--stopped` 是操作者確認,工具無法證明其他 MySQL 寫入者已停止。 +2. 保留原始資料、anti-abuse 密鑰與設定檔的可還原備份。MySQL 另須先完成一致性資料庫 dump,並把其路徑傳給 `--backup`;工具只檢查 dump 檔存在且非空,不會驗證 dump 可還原。SQLite/JSON 的 `--backup` 指向**尚不存在**的新檔案,工具會先複製並核對 SHA-256 才修改來源。 +3. 確認目標 UUID 正確,先執行不帶 `--apply` 的預覽。任何相關 Reward Delivery 或 Action 尚為 `PENDING`、`PROCESSING`、`UNCERTAIN` 時會拒絕;先依獎勵復原流程處理。正式交易若在其他資料的自由文字中找到仍無法安全移除的原 UUID/名稱,也會回滾並提示所在資料表;不得為了通過檢查而直接清空未交付獎勵內容。 +4. 以專案選定的 mise Java 執行已建置的 `InviteCode-0.1.0-SNAPSHOT.jar`。下列 `JAR`、路徑及 UUID 要替換成實際值;**不要**把密碼或密鑰寫在命令列。 + +### SQLite + +現有 schema 8 必須先明確升級到 9;升級及匿名化各自保留一份不同名稱的備份: + +```powershell +mise exec -- java -cp $JAR io.github.command1264.invitecode.plugin.OfflineAnonymizeMain --migrate-sqlite --backend sqlite --source $DB --backup $SCHEMA_BACKUP --stopped +mise exec -- java -cp $JAR io.github.command1264.invitecode.plugin.OfflineAnonymizeMain --backend sqlite --source $DB --secret $KEY --player $UUID +mise exec -- java -cp $JAR io.github.command1264.invitecode.plugin.OfflineAnonymizeMain --backend sqlite --source $DB --secret $KEY --player $UUID --apply --stopped --backup $DATA_BACKUP +``` + +初次建立的 schema 9 不需升級。若仍有 `-wal`/`-shm` 檔案,工具會停止備份與修改;先檢查是否有實例使用資料庫,完成 checkpoint 與完整備份,不要直接刪除檔案。 + +### JSON + +現有 snapshot schema 8 必須先明確升級到 9;升級仍使用原子快照機制,另外留下 `.previous`: + +```powershell +mise exec -- java -cp $JAR io.github.command1264.invitecode.plugin.OfflineAnonymizeMain --migrate-json --backend json --source $JSON --backup $SCHEMA_BACKUP --stopped +mise exec -- java -cp $JAR io.github.command1264.invitecode.plugin.OfflineAnonymizeMain --backend json --source $JSON --secret $KEY --player $UUID +mise exec -- java -cp $JAR io.github.command1264.invitecode.plugin.OfflineAnonymizeMain --backend json --source $JSON --secret $KEY --player $UUID --apply --stopped --backup $DATA_BACKUP +``` + +### MySQL + +現有 schema 1 必須先升級到 2。`$MYSQL_BACKUP` 是已完成的非空 dump 檔;密碼與共用的 32-byte Base64 anti-abuse 密鑰分別從指定環境變數讀取。TLS 預設 `VERIFY_IDENTITY`,必要時可明確加 `--tls VERIFY_CA` 或 `--tls REQUIRED`。 + +```powershell +mise exec -- java -cp $JAR io.github.command1264.invitecode.plugin.OfflineAnonymizeMain --migrate-mysql --backend mysql --host $HOSTNAME --port $PORT --database $DATABASE --username $USERNAME --password-env INVITECODE_MYSQL_PASSWORD --secret-env INVITECODE_NETWORK_SECRET --backup $MYSQL_BACKUP --stopped +mise exec -- java -cp $JAR io.github.command1264.invitecode.plugin.OfflineAnonymizeMain --backend mysql --host $HOSTNAME --port $PORT --database $DATABASE --username $USERNAME --password-env INVITECODE_MYSQL_PASSWORD --secret-env INVITECODE_NETWORK_SECRET --player $UUID +mise exec -- java -cp $JAR io.github.command1264.invitecode.plugin.OfflineAnonymizeMain --backend mysql --host $HOSTNAME --port $PORT --database $DATABASE --username $USERNAME --password-env INVITECODE_MYSQL_PASSWORD --secret-env INVITECODE_NETWORK_SECRET --player $UUID --apply --stopped --backup $MYSQL_BACKUP +``` + +## 驗證與復原 + +工具顯示受影響的邀請、獎勵與舊碼數量。執行後確認:原 UUID 在 Player 查詢中不存在;歷史 ID 保留舊邀請關係;舊碼不能 Claim 或重新配發;資料可重新開啟;同 UUID 再加入會是新玩家。不要公開歷史 ID 與備份對照。交易失敗時 SQL 會回滾;若回滾狀態不明,停止所有寫入並檢查。JSON 快照失敗會停止當次寫入;檢查原檔與 `.previous` 後再處理。 + +匿名化不能刪除既有備份、log、終端機歷史、程序參數、第三方插件或玩家自行保存的資料。精確的歷史時間及關係仍可能被持有外部對照的人推測身分;備份與操作紀錄應依獨立保留政策保護與清除。工具不輸出新舊 ID 的對照。每次操作會新增固定理由的 `PLAYER_ANONYMIZED` 稽核事件,不在資料庫保留可能含身分的自由文字理由。 diff --git a/docs/spec/invitecode-1.0.md b/docs/spec/invitecode-1.0.md index 37b4f7a..864323a 100644 --- a/docs/spec/invitecode-1.0.md +++ b/docs/spec/invitecode-1.0.md @@ -51,7 +51,7 @@ InviteCode 在一名 Inviter 與一名 Invitee 之間建立一筆持久的 Invit - 已存在 backend 的 schema 升級不得在一般啟動時自動執行。 - Storage 發生錯誤時採拒絕操作的安全失敗模式;插件不得退回 memory 或其他 backend。 - IP 防濫用機制保存 keyed hash 30 天,不保存原始位址。 -- Anonymization 移除名稱、IP hash 與顯示資料,同時保留歷史一致性。 +- Anonymization 只能在所有實例停止且完成備份後以離線工具執行;舊 Minecraft UUID 改為隨機歷史 ID,移除名稱、IP hash、登入日期及相關自由文字,保留歷史一致性。未處理獎勵會阻止操作;舊 Invite Code 以獨立用途的 keyed hash 保留防止重發,同一玩家再次加入視為新玩家。詳見 ADR 0005。 - Log 不得包含憑證與 IP hash。 ## 設定與維運 diff --git a/invitecode-core/src/main/kotlin/io/github/command1264/invitecode/core/InvitationAdministration.kt b/invitecode-core/src/main/kotlin/io/github/command1264/invitecode/core/InvitationAdministration.kt index fd01710..e8be4e1 100644 --- a/invitecode-core/src/main/kotlin/io/github/command1264/invitecode/core/InvitationAdministration.kt +++ b/invitecode-core/src/main/kotlin/io/github/command1264/invitecode/core/InvitationAdministration.kt @@ -23,6 +23,7 @@ enum class InvitationAuditAction { ELIGIBILITY_RESET, CODE_ROTATED, STORAGE_MIGRATED, + PLAYER_ANONYMIZED, } data class AuditRecord( @@ -107,7 +108,8 @@ data class AuditedInvitationTransition( "Eligibility Reset cannot audit an Invitation transition.", ) InvitationAuditAction.CODE_ROTATED, - InvitationAuditAction.STORAGE_MIGRATED -> throw IllegalArgumentException( + InvitationAuditAction.STORAGE_MIGRATED, + InvitationAuditAction.PLAYER_ANONYMIZED -> throw IllegalArgumentException( "${auditRecord.action} cannot audit an Invitation transition.", ) } diff --git a/invitecode-platform-bukkit/src/main/kotlin/io/github/command1264/invitecode/platform/bukkit/NetworkAddressHasher.kt b/invitecode-platform-bukkit/src/main/kotlin/io/github/command1264/invitecode/platform/bukkit/NetworkAddressHasher.kt index 1300f0b..68f6922 100644 --- a/invitecode-platform-bukkit/src/main/kotlin/io/github/command1264/invitecode/platform/bukkit/NetworkAddressHasher.kt +++ b/invitecode-platform-bukkit/src/main/kotlin/io/github/command1264/invitecode/platform/bukkit/NetworkAddressHasher.kt @@ -7,6 +7,7 @@ import java.nio.file.StandardOpenOption import java.nio.file.attribute.PosixFilePermission import java.security.SecureRandom import java.security.MessageDigest +import java.nio.charset.StandardCharsets import java.util.Base64 import java.util.concurrent.atomic.AtomicBoolean import javax.crypto.Mac @@ -40,6 +41,20 @@ class NetworkAddressHasher private constructor( } } + /** Domain-separated digest for permanently reserved Invite Codes; never hash a short code without a key. */ + fun hashReservedCode(normalizedCode: String): String { + check(!closed.get()) { "Network address hasher is closed." } + require(normalizedCode.isNotBlank()) { "Invite Code must not be blank." } + val mac = Mac.getInstance(ALGORITHM) + mac.init(SecretKeySpec(key, ALGORITHM)) + val input = ("invitecode:reserved-code:v1:" + normalizedCode).toByteArray(StandardCharsets.UTF_8) + return try { + mac.doFinal(input).joinToString("") { byte -> "%02x".format(byte.toInt() and 0xff) } + } finally { + input.fill(0) + } + } + override fun close() { if (closed.compareAndSet(false, true)) key.fill(0) } diff --git a/invitecode-platform-bukkit/src/test/kotlin/io/github/command1264/invitecode/platform/bukkit/NetworkAddressHasherTest.kt b/invitecode-platform-bukkit/src/test/kotlin/io/github/command1264/invitecode/platform/bukkit/NetworkAddressHasherTest.kt index 72af7a6..5bfa37d 100644 --- a/invitecode-platform-bukkit/src/test/kotlin/io/github/command1264/invitecode/platform/bukkit/NetworkAddressHasherTest.kt +++ b/invitecode-platform-bukkit/src/test/kotlin/io/github/command1264/invitecode/platform/bukkit/NetworkAddressHasherTest.kt @@ -50,4 +50,17 @@ class NetworkAddressHasherTest { NetworkAddressHasher.fromBase64(Base64.getEncoder().encodeToString(ByteArray(16))) } } + + @Test + fun `reserved Invite Code HMAC is stable and separate from address digest`() { + val first = NetworkAddressHasher.loadOrCreate(temporaryDirectory.resolve("anti-abuse.key")).use { + it.hashReservedCode("A1B2C3") to it.hash(byteArrayOf(10, 0, 0, 1)) + } + val second = NetworkAddressHasher.loadExisting(temporaryDirectory.resolve("anti-abuse.key")).use { + it.hashReservedCode("A1B2C3") + } + assertEquals(first.first, second) + assertNotEquals(first.first, first.second) + assertEquals(64, second.length) + } } diff --git a/invitecode-plugin/build.gradle.kts b/invitecode-plugin/build.gradle.kts index fe7ffc2..7870fbe 100644 --- a/invitecode-plugin/build.gradle.kts +++ b/invitecode-plugin/build.gradle.kts @@ -148,6 +148,7 @@ val verifyPluginJar by tasks.registering(VerifyPluginJar::class) { "config/messages/zh_TW.yml", "config/messages/en_US.yml", "io/github/command1264/invitecode/plugin/InviteCodePlugin.class", + "io/github/command1264/invitecode/plugin/OfflineAnonymizeMain.class", "org/sqlite/JDBC.class", "com/mysql/cj/jdbc/Driver.class", "com/zaxxer/hikari/HikariDataSource.class", @@ -155,6 +156,7 @@ val verifyPluginJar by tasks.registering(VerifyPluginJar::class) { "io/github/command1264/invitecode/storage/json/JsonInviteCodeStorage.class", "org/slf4j/impl/JDK14LoggerFactory.class", "mysql/V1__initial_schema.sql", + "mysql/V2__reserved_code_hashes.sql", "org/sqlite/native/Linux/x86_64/libsqlitejdbc.so", "org/sqlite/native/Windows/x86_64/sqlitejdbc.dll", "META-INF/services/java.sql.Driver", diff --git a/invitecode-plugin/src/main/kotlin/io/github/command1264/invitecode/plugin/InviteCodePlugin.kt b/invitecode-plugin/src/main/kotlin/io/github/command1264/invitecode/plugin/InviteCodePlugin.kt index 29b6530..7136b63 100644 --- a/invitecode-plugin/src/main/kotlin/io/github/command1264/invitecode/plugin/InviteCodePlugin.kt +++ b/invitecode-plugin/src/main/kotlin/io/github/command1264/invitecode/plugin/InviteCodePlugin.kt @@ -19,6 +19,7 @@ import io.github.command1264.invitecode.platform.bukkit.PluginRuntimeState import io.github.command1264.invitecode.platform.bukkit.RuntimePhase import io.github.command1264.invitecode.platform.bukkit.RuntimeConfigurationReload import io.github.command1264.invitecode.platform.bukkit.NetworkAddressHasher +import io.github.command1264.invitecode.storage.sql.CodeReservationKey import io.github.command1264.invitecode.platform.bukkit.PlatformTaskDispatcher import io.github.command1264.invitecode.platform.modern.ModernPlatformCapabilities import io.github.command1264.invitecode.platform.modern.ModernPlatformIntegration @@ -294,19 +295,23 @@ class InviteCodePlugin : JavaPlugin() { "SQLite database path escapes the plugin data directory." } val version = SqliteSchemaMigrator(database, guard).migrate() - val opened = SqliteInviteCodeStorage.open(database, guard) var newHasher: NetworkAddressHasher? = null + var opened: SqliteInviteCodeStorage? = null try { val loadedHasher = networkHasher.get() newHasher = if (loadedHasher == null) { NetworkAddressHasher.loadOrCreate(dataDirectory.resolve(NETWORK_SECRET_FILE)) } else null - opened.purgeNetworkHashesWithDifferentKey((loadedHasher ?: requireNotNull(newHasher)).keyId) + val activeHasher = loadedHasher ?: requireNotNull(newHasher) + opened = SqliteInviteCodeStorage.open( + database, guard, CodeReservationKey(activeHasher.keyId, activeHasher::hashReservedCode), + ) + opened.purgeNetworkHashesWithDifferentKey(activeHasher.keyId) opened.saveAuditRecord(AuditRecord(UUID.randomUUID(), InvitationAuditAction.STORAGE_MIGRATED, actor, reason, Instant.now())) StorageMigrationResult(version, opened, newHasher) } catch (error: Exception) { newHasher?.close() - opened.close() + opened?.close() throw error } } diff --git a/invitecode-plugin/src/main/kotlin/io/github/command1264/invitecode/plugin/JsonRuntimeBootstrap.kt b/invitecode-plugin/src/main/kotlin/io/github/command1264/invitecode/plugin/JsonRuntimeBootstrap.kt index 7f8a35c..9aa03c3 100644 --- a/invitecode-plugin/src/main/kotlin/io/github/command1264/invitecode/plugin/JsonRuntimeBootstrap.kt +++ b/invitecode-plugin/src/main/kotlin/io/github/command1264/invitecode/plugin/JsonRuntimeBootstrap.kt @@ -5,6 +5,7 @@ import io.github.command1264.invitecode.core.InvitationAuditAction import io.github.command1264.invitecode.platform.bukkit.NetworkAddressHasher import io.github.command1264.invitecode.storage.json.JsonInviteCodeStorage import io.github.command1264.invitecode.storage.sql.BlockingOperationGuard +import io.github.command1264.invitecode.storage.sql.CodeReservationKey import java.nio.file.Files import java.nio.file.Path import java.time.Instant @@ -27,34 +28,29 @@ internal class JsonRuntimeBootstrap( "JSON storage path ${file.toAbsolutePath()} exists but is not a regular file." } val initialize = !Files.exists(file) - val secretExisted = Files.isRegularFile(networkSecret) var storage: JsonInviteCodeStorage? = null var hasher: NetworkAddressHasher? = null try { - // Acquire the JSON writer lock before touching the shared anti-abuse key. - storage = JsonInviteCodeStorage.open(file, guard) - hasher = if (initialize) NetworkAddressHasher.loadOrCreate(networkSecret) - else NetworkAddressHasher.loadExisting(networkSecret) - storage.purgeNetworkHashesWithDifferentKey(hasher.keyId) + storage = JsonInviteCodeStorage.openWithKeyProvider(file, guard) { + val activeHasher = if (initialize) NetworkAddressHasher.loadOrCreate(networkSecret) + else NetworkAddressHasher.loadExisting(networkSecret) + hasher = activeHasher + CodeReservationKey(activeHasher.keyId, activeHasher::hashReservedCode) + } + val readyHasher = requireNotNull(hasher) + storage.purgeNetworkHashesWithDifferentKey(readyHasher.keyId) if (initialize) { storage.saveAuditRecord(AuditRecord( UUID.randomUUID(), InvitationAuditAction.STORAGE_MIGRATED, "system", "automatic first initialization", now(), )) } - return JsonBootstrapResult(storage, hasher, initialize) + return JsonBootstrapResult(storage, readyHasher, initialize) } catch (error: Exception) { - val ownedStorage = storage != null storage?.close() hasher?.close() - if (initialize && ownedStorage) { - listOf(file, file.resolveSibling("${file.fileName}.previous")).forEach { created -> - try { Files.deleteIfExists(created) } catch (cleanup: Exception) { error.addSuppressed(cleanup) } - } - if (!secretExisted) { - try { Files.deleteIfExists(networkSecret) } catch (cleanup: Exception) { error.addSuppressed(cleanup) } - } - } + // Preserve a possibly initialized snapshot/key for inspection; another process may acquire + // the JSON lock immediately after close, so deleting them here could race that process. throw error } } diff --git a/invitecode-plugin/src/main/kotlin/io/github/command1264/invitecode/plugin/MysqlRuntimeBootstrap.kt b/invitecode-plugin/src/main/kotlin/io/github/command1264/invitecode/plugin/MysqlRuntimeBootstrap.kt index c440367..dba92d5 100644 --- a/invitecode-plugin/src/main/kotlin/io/github/command1264/invitecode/plugin/MysqlRuntimeBootstrap.kt +++ b/invitecode-plugin/src/main/kotlin/io/github/command1264/invitecode/plugin/MysqlRuntimeBootstrap.kt @@ -5,6 +5,7 @@ import io.github.command1264.invitecode.core.InvitationAuditAction import io.github.command1264.invitecode.core.MysqlConfiguration import io.github.command1264.invitecode.platform.bukkit.NetworkAddressHasher import io.github.command1264.invitecode.storage.sql.BlockingOperationGuard +import io.github.command1264.invitecode.storage.sql.CodeReservationKey import io.github.command1264.invitecode.storage.sql.MysqlInviteCodeStorage import io.github.command1264.invitecode.storage.sql.MysqlSchemaMigrator import io.github.command1264.invitecode.storage.sql.MysqlStorageException @@ -47,7 +48,7 @@ internal class MysqlRuntimeBootstrap( MysqlSchemaMigrator(pool, guard).migrate() } pool.connection.use { connection -> MysqlSchemaMigrator.bindNetworkKey(connection, hasher.keyId) } - storage = MysqlInviteCodeStorage.open(pool, guard) + storage = MysqlInviteCodeStorage.open(pool, guard, CodeReservationKey(hasher.keyId, hasher::hashReservedCode)) if (!initializedBefore) { storage.saveAuditRecord( AuditRecord( diff --git a/invitecode-plugin/src/main/kotlin/io/github/command1264/invitecode/plugin/OfflineAnonymizeMain.kt b/invitecode-plugin/src/main/kotlin/io/github/command1264/invitecode/plugin/OfflineAnonymizeMain.kt new file mode 100644 index 0000000..bce33e9 --- /dev/null +++ b/invitecode-plugin/src/main/kotlin/io/github/command1264/invitecode/plugin/OfflineAnonymizeMain.kt @@ -0,0 +1,210 @@ +package io.github.command1264.invitecode.plugin + +import io.github.command1264.invitecode.core.MysqlConfiguration +import io.github.command1264.invitecode.core.MysqlTlsMode +import io.github.command1264.invitecode.platform.bukkit.NetworkAddressHasher +import io.github.command1264.invitecode.storage.json.JsonInviteCodeStorage +import io.github.command1264.invitecode.storage.sql.BlockingOperationGuard +import io.github.command1264.invitecode.storage.sql.CodeReservationKey +import io.github.command1264.invitecode.storage.sql.MysqlInviteCodeStorage +import io.github.command1264.invitecode.storage.sql.SqliteInviteCodeStorage +import io.github.command1264.invitecode.storage.sql.SqliteSchemaMigrator +import io.github.command1264.invitecode.storage.sql.MysqlSchemaMigrator +import io.github.command1264.invitecode.storage.sql.AnonymizationPreview +import java.nio.file.Files +import java.nio.file.LinkOption.NOFOLLOW_LINKS +import java.nio.file.Path +import java.nio.file.Paths +import java.nio.file.StandardCopyOption.COPY_ATTRIBUTES +import java.security.MessageDigest +import java.time.Duration +import java.util.UUID +import java.util.Locale + +/** Invoke directly from the shaded plugin JAR while all InviteCode servers are stopped. */ +object OfflineAnonymizeMain { + @JvmStatic + fun main(args: Array) { + try { + execute(args) + } catch (error: Exception) { + System.err.println("離線匿名化已拒絕:${error.message}") + kotlin.system.exitProcess(1) + } + } + + internal fun execute(args: Array) { + val options = parse(args) + if ("migrate-json" in options) { + require(options.required("backend").equals("json", ignoreCase = true) && "stopped" in options) { + "JSON 升級需要 --backend json --stopped。" + } + val source = path(options.required("source")) + makeBackup(source, path(options.required("backup"))) + JsonInviteCodeStorage.migrateV8ToV9(source, BlockingOperationGuard { }) + println("JSON 快照已升級至 schema 9;請驗證快照並保留備份。") + return + } + if ("migrate-sqlite" in options) { + require(options.required("backend").equals("sqlite", ignoreCase = true) && "stopped" in options) { + "SQLite 升級需要 --backend sqlite --stopped。" + } + val source = path(options.required("source")) + makeBackup(source, path(options.required("backup"))) + val version = SqliteSchemaMigrator(source, BlockingOperationGuard { }).migrate() + println("SQLite schema 已升級至 $version;請驗證資料庫並保留備份。") + return + } + if ("migrate-mysql" in options) { + require(options.required("backend").equals("mysql", ignoreCase = true) && "stopped" in options) { + "MySQL 升級需要 --backend mysql --stopped。" + } + requireBackupDump(path(options.required("backup"))) + val password = environment(options.required("password-env")) + NetworkAddressHasher.fromBase64(environment(options.required("secret-env"))).use { hasher -> + val pool = MysqlInviteCodeStorage.createPool(mysqlConfig(options), password) + pool.use { + val version = MysqlSchemaMigrator(it, BlockingOperationGuard { }).migrate() + it.connection.use { connection -> MysqlSchemaMigrator.bindNetworkKey(connection, hasher.keyId) } + println("MySQL schema 已升級至 $version;請驗證資料庫並保留 dump。") + } + } + return + } + val playerId = UUID.fromString(options.required("player")) + val apply = "apply" in options + val backend = options.required("backend").lowercase(Locale.ROOT) + require(backend in setOf("sqlite", "json", "mysql")) { "不支援的儲存 backend。" } + if (apply) { + require("stopped" in options) { "停止所有 InviteCode 實例後才可指定 --stopped。" } + require("backup" in options) { "變更玩家資料前必須指定 --backup。" } + } + val guard = BlockingOperationGuard { } + if (backend == "mysql") { + val password = environment(options.required("password-env")) + val secret = environment(options.required("secret-env")) + NetworkAddressHasher.fromBase64(secret).use { hasher -> + val config = mysqlConfig(options) + val pool = MysqlInviteCodeStorage.createPool(config, password) + val key = CodeReservationKey(hasher.keyId, hasher::hashReservedCode) + pool.use { + MysqlInviteCodeStorage.open(it, guard, key).use { storage -> + val preview = storage.previewAnonymization(playerId) + printPreview(preview) + if (apply) { + requireBackupDump(path(options.required("backup"))) + storage.anonymizePlayer(playerId) + println("玩家資料已匿名化;請驗證資料並保留備份。") + } + } + } + } + } else { + val source = path(options.required("source")) + val secret = path(options.required("secret")) + require(Files.isRegularFile(source, NOFOLLOW_LINKS)) { "儲存來源必須是既有的一般檔案。" } + NetworkAddressHasher.loadExisting(secret).use { hasher -> + val key = CodeReservationKey(hasher.keyId, hasher::hashReservedCode) + if (backend == "sqlite") { + SqliteInviteCodeStorage.open(source, guard, key).use { storage -> + val preview = storage.previewAnonymization(playerId) + printPreview(preview) + if (apply) { + makeBackup(source, path(options.required("backup"))) + storage.anonymizePlayer(playerId) + println("玩家資料已匿名化;請驗證資料並保留備份。") + } + } + } else { + JsonInviteCodeStorage.open(source, guard, key).use { storage -> + val preview = storage.previewAnonymization(playerId) + printPreview(preview) + if (apply) { + makeBackup(source, path(options.required("backup"))) + storage.anonymizePlayer(playerId) + println("玩家資料已匿名化;請驗證資料並保留備份。") + } + } + } + } + } + } + + private fun printPreview(preview: AnonymizationPreview) { + println("影響範圍:邀請 ${preview.invitations} 筆、獎勵交付 ${preview.rewardDeliveries} 筆、舊邀請碼 ${preview.retiredCodes} 組。") + } + + private fun mysqlConfig(options: Map): MysqlConfiguration = MysqlConfiguration( + options.required("host"), options.required("port").toInt(), options.required("database"), + options.required("username"), "${'$'}{INVITECODE_OFFLINE_PASSWORD}", + "${'$'}{INVITECODE_OFFLINE_SECRET}", Duration.ofSeconds(10), + MysqlTlsMode.valueOf(options.getOrDefault("tls", "VERIFY_IDENTITY")), + ) + + private fun requireBackupDump(backup: Path) { + require(Files.isRegularFile(backup, NOFOLLOW_LINKS) && Files.size(backup) > 0) { + "執行前必須提供既有且非空的 MySQL 備份 dump。" + } + } + + private fun makeBackup(source: Path, destination: Path) { + require(Files.isRegularFile(source, NOFOLLOW_LINKS)) { "儲存來源必須是既有的一般檔案。" } + require(source != destination) { "備份路徑不能與來源相同。" } + require(!Files.exists(destination, NOFOLLOW_LINKS)) { "備份檔已存在;請選擇新路徑。" } + require(Files.isDirectory(destination.parent)) { "備份檔的上層資料夾必須存在。" } + // A leftover WAL can contain committed rows absent from the main SQLite file. + if (!source.fileName.toString().endsWith(".json", ignoreCase = true)) { + require(!Files.exists(source.resolveSibling("${source.fileName}-wal")) && + !Files.exists(source.resolveSibling("${source.fileName}-shm"))) { + "SQLite 仍有 WAL/SHM 檔案;請先確認實例已停止、執行 checkpoint 並完整備份。" + } + } + Files.copy(source, destination, COPY_ATTRIBUTES) + require(digest(destination).contentEquals(digest(source))) { "備份與來源的 SHA-256 不一致;已停止操作。" } + } + + private fun digest(path: Path): ByteArray = MessageDigest.getInstance("SHA-256").let { sha -> + Files.newInputStream(path).use { input -> + val chunk = ByteArray(8192) + while (true) { + val count = input.read(chunk) + if (count < 0) break + sha.update(chunk, 0, count) + } + } + sha.digest() + } + + private fun path(raw: String): Path = Paths.get(raw).toAbsolutePath().normalize() + + private fun environment(name: String): String { + require(Regex("[A-Za-z_][A-Za-z0-9_]*").matches(name)) { "環境變數名稱無效。" } + return System.getenv(name)?.takeIf(String::isNotBlank) + ?: throw IllegalArgumentException("環境變數 $name 不存在或為空。") + } + + private fun parse(args: Array): Map { + val flags = setOf("apply", "stopped", "migrate-json", "migrate-sqlite", "migrate-mysql") + val values = setOf("backend", "source", "secret", "player", "backup", "host", "port", "database", + "username", "password-env", "secret-env", "tls") + val result = mutableMapOf() + var index = 0 + while (index < args.size) { + val name = args[index].removePrefix("--") + require(args[index].startsWith("--") && name in flags + values) { "未知選項 ${args[index]}。" } + require(name !in result) { "選項 --$name 不可重複。" } + if (name in flags) { + result[name] = "true" + index++ + } else { + require(index + 1 < args.size && !args[index + 1].startsWith("--")) { "選項 --$name 需要值。" } + result[name] = args[index + 1] + index += 2 + } + } + return result + } + + private fun Map.required(name: String): String = get(name)?.takeIf(String::isNotBlank) + ?: throw IllegalArgumentException("缺少 --$name。") +} diff --git a/invitecode-plugin/src/main/kotlin/io/github/command1264/invitecode/plugin/SqliteRuntimeBootstrap.kt b/invitecode-plugin/src/main/kotlin/io/github/command1264/invitecode/plugin/SqliteRuntimeBootstrap.kt index b77c042..c350469 100644 --- a/invitecode-plugin/src/main/kotlin/io/github/command1264/invitecode/plugin/SqliteRuntimeBootstrap.kt +++ b/invitecode-plugin/src/main/kotlin/io/github/command1264/invitecode/plugin/SqliteRuntimeBootstrap.kt @@ -4,6 +4,7 @@ import io.github.command1264.invitecode.core.AuditRecord import io.github.command1264.invitecode.core.InvitationAuditAction import io.github.command1264.invitecode.platform.bukkit.NetworkAddressHasher import io.github.command1264.invitecode.storage.sql.BlockingOperationGuard +import io.github.command1264.invitecode.storage.sql.CodeReservationKey import io.github.command1264.invitecode.storage.sql.SqliteInviteCodeStorage import io.github.command1264.invitecode.storage.sql.SqliteSchemaMigrator import java.nio.file.Files @@ -38,7 +39,9 @@ internal class SqliteRuntimeBootstrap( } else { hasher = NetworkAddressHasher.loadExisting(networkSecret) } - storage = SqliteInviteCodeStorage.open(database, blockingOperationGuard) + storage = SqliteInviteCodeStorage.open( + database, blockingOperationGuard, CodeReservationKey(hasher.keyId, hasher::hashReservedCode), + ) storage.purgeNetworkHashesWithDifferentKey(hasher.keyId) if (initialize) { storage.saveAuditRecord( diff --git a/invitecode-plugin/src/test/kotlin/io/github/command1264/invitecode/plugin/OfflineAnonymizeMainTest.kt b/invitecode-plugin/src/test/kotlin/io/github/command1264/invitecode/plugin/OfflineAnonymizeMainTest.kt new file mode 100644 index 0000000..9719b75 --- /dev/null +++ b/invitecode-plugin/src/test/kotlin/io/github/command1264/invitecode/plugin/OfflineAnonymizeMainTest.kt @@ -0,0 +1,43 @@ +package io.github.command1264.invitecode.plugin + +import io.github.command1264.invitecode.core.StoredPlayer +import io.github.command1264.invitecode.platform.bukkit.NetworkAddressHasher +import io.github.command1264.invitecode.storage.sql.BlockingOperationGuard +import io.github.command1264.invitecode.storage.sql.SqliteInviteCodeStorage +import io.github.command1264.invitecode.storage.sql.SqliteSchemaMigrator +import org.junit.jupiter.api.Assertions.assertNotNull +import org.junit.jupiter.api.Assertions.assertNull +import org.junit.jupiter.api.Assertions.assertTrue +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.io.TempDir +import java.nio.file.Files +import java.nio.file.Path +import java.time.Instant +import java.util.UUID + +class OfflineAnonymizeMainTest { + @TempDir lateinit var directory: Path + + @Test + fun `offline command copies and verifies backup before anonymizing the requested player`() { + val database = directory.resolve("players.db") + val secret = directory.resolve("anti-abuse.key") + val backup = directory.resolve("players.before-anonymization.db") + val playerId = UUID.randomUUID() + val guard = BlockingOperationGuard { } + NetworkAddressHasher.loadOrCreate(secret).close() + SqliteSchemaMigrator(database, guard).migrate() + SqliteInviteCodeStorage.open(database, guard).use { storage -> + storage.savePlayer(StoredPlayer(playerId, Instant.parse("2026-01-01T00:00:00Z"), "Alice")) + } + + OfflineAnonymizeMain.execute(arrayOf( + "--backend", "sqlite", "--source", database.toString(), "--secret", secret.toString(), + "--player", playerId.toString(), "--apply", "--stopped", "--backup", backup.toString(), + )) + + assertTrue(Files.isRegularFile(backup)) + SqliteInviteCodeStorage.open(backup, guard).use { assertNotNull(it.player(playerId)) } + SqliteInviteCodeStorage.open(database, guard).use { assertNull(it.player(playerId)) } + } +} diff --git a/invitecode-storage-json/src/main/kotlin/io/github/command1264/invitecode/storage/json/JsonInviteCodeStorage.kt b/invitecode-storage-json/src/main/kotlin/io/github/command1264/invitecode/storage/json/JsonInviteCodeStorage.kt index cc551d6..ea46f04 100644 --- a/invitecode-storage-json/src/main/kotlin/io/github/command1264/invitecode/storage/json/JsonInviteCodeStorage.kt +++ b/invitecode-storage-json/src/main/kotlin/io/github/command1264/invitecode/storage/json/JsonInviteCodeStorage.kt @@ -6,6 +6,9 @@ import com.google.gson.JsonParser import com.google.gson.GsonBuilder import io.github.command1264.invitecode.core.* import io.github.command1264.invitecode.storage.sql.BlockingOperationGuard +import io.github.command1264.invitecode.storage.sql.CodeReservationKey +import io.github.command1264.invitecode.storage.sql.AnonymizationPreview +import io.github.command1264.invitecode.storage.sql.AnonymizationResult import io.github.command1264.invitecode.storage.sql.SqliteInviteCodeStorage import io.github.command1264.invitecode.storage.sql.SqliteSchemaMigrator import io.github.command1264.invitecode.storage.sql.SqliteSnapshotAccess @@ -96,6 +99,9 @@ class JsonInviteCodeStorage private constructor( override fun atomically(playerIds: Set, operation: (InvitationTransaction) -> T): T = persist { delegate.atomically(playerIds, operation) } + fun previewAnonymization(playerId: UUID): AnonymizationPreview = delegate.previewAnonymization(playerId) + fun anonymizePlayer(playerId: UUID): AnonymizationResult = persist { delegate.anonymizePlayer(playerId) } + override fun close() = synchronized(this) { if (closed) return@synchronized closed = true @@ -109,7 +115,51 @@ class JsonInviteCodeStorage private constructor( companion object { const val FORMAT_VERSION = 1 - fun open(file: Path, guard: BlockingOperationGuard): JsonInviteCodeStorage { + /** Offline-only, explicit snapshot migration; the .previous file keeps the original snapshot. */ + fun migrateV8ToV9(file: Path, guard: BlockingOperationGuard) { + guard.checkAllowed() + val target = file.toAbsolutePath().normalize() + require(Files.isRegularFile(target)) { "JSON storage must exist before migration." } + val lockChannel = FileChannel.open(target.resolveSibling("${target.fileName}.lock"), CREATE, WRITE) + val lock = try { + lockChannel.tryLock() ?: throw JsonStorageException("JSON storage is already open; stop every instance.") + } catch (error: Exception) { + lockChannel.close() + throw error + } + val workingDirectory = try { Files.createTempDirectory("invitecode-json-migrate-") } catch (error: Exception) { + lock.release() + lockChannel.close() + throw error + } + val database = workingDirectory.resolve("working.db") + try { + SqliteSchemaMigrator(database, guard, SqliteSchemaMigrator.DEFAULT_MIGRATIONS.take(8)).migrate() + importSnapshot(target, database, guard, expectedSchemaVersion = 8) + SqliteSchemaMigrator(database, guard).migrate() + writeSnapshot(target, exportSnapshot(database, guard)) + } finally { + try { + Files.deleteIfExists(database) + Files.deleteIfExists(workingDirectory) + } finally { + lock.release() + lockChannel.close() + } + } + } + + fun open(file: Path, guard: BlockingOperationGuard, reservationKey: CodeReservationKey? = null): JsonInviteCodeStorage = + openAfterLock(file, guard) { reservationKey } + + /** Loads the shared key only after the JSON writer lock has been acquired. */ + fun openWithKeyProvider( + file: Path, guard: BlockingOperationGuard, provider: () -> CodeReservationKey, + ): JsonInviteCodeStorage = openAfterLock(file, guard, provider) + + private fun openAfterLock( + file: Path, guard: BlockingOperationGuard, provider: () -> CodeReservationKey?, + ): JsonInviteCodeStorage { guard.checkAllowed() val target = file.toAbsolutePath().normalize() Files.createDirectories(requireNotNull(target.parent)) @@ -133,7 +183,7 @@ class JsonInviteCodeStorage private constructor( try { SqliteSchemaMigrator(database, guard).migrate() if (Files.exists(target)) importSnapshot(target, database, guard) - val delegate = SqliteInviteCodeStorage.open(database, guard) + val delegate = SqliteInviteCodeStorage.open(database, guard, provider()) try { if (!Files.exists(target)) writeSnapshot(target, exportSnapshot(database, guard)) return JsonInviteCodeStorage( @@ -209,7 +259,10 @@ class JsonInviteCodeStorage private constructor( root } - private fun importSnapshot(file: Path, database: Path, guard: BlockingOperationGuard) { + private fun importSnapshot( + file: Path, database: Path, guard: BlockingOperationGuard, + expectedSchemaVersion: Int = SqliteSchemaMigrator.currentVersion, + ) { val root = try { Files.newBufferedReader(file, StandardCharsets.UTF_8).use { JsonParser.parseReader(it).asJsonObject } } catch (error: Exception) { @@ -224,8 +277,8 @@ class JsonInviteCodeStorage private constructor( "JSON format version $format is unsupported; expected $FORMAT_VERSION. Preserve the file and upgrade InviteCode." } val schemaVersion = root.get("schema-version")?.asString?.takeIf { it.matches(Regex("[0-9]+")) }?.toIntOrNull() - require(schemaVersion == SqliteSchemaMigrator.currentVersion) { - "JSON schema version $schemaVersion is unsupported; expected ${SqliteSchemaMigrator.currentVersion}. " + + require(schemaVersion == expectedSchemaVersion) { + "JSON schema version $schemaVersion is unsupported; expected $expectedSchemaVersion. " + "Preserve the file and run an explicit migration with a compatible InviteCode version." } require(root.keySet() == setOf("format-version", "schema-version", "tables")) { diff --git a/invitecode-storage-json/src/test/kotlin/io/github/command1264/invitecode/storage/json/JsonOfflineAnonymizationTest.kt b/invitecode-storage-json/src/test/kotlin/io/github/command1264/invitecode/storage/json/JsonOfflineAnonymizationTest.kt new file mode 100644 index 0000000..577671c --- /dev/null +++ b/invitecode-storage-json/src/test/kotlin/io/github/command1264/invitecode/storage/json/JsonOfflineAnonymizationTest.kt @@ -0,0 +1,64 @@ +package io.github.command1264.invitecode.storage.json + +import com.google.gson.JsonParser +import io.github.command1264.invitecode.core.StoredPlayer +import io.github.command1264.invitecode.storage.sql.BlockingOperationGuard +import io.github.command1264.invitecode.storage.sql.CodeReservationKey +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertNotNull +import org.junit.jupiter.api.Assertions.assertNull +import org.junit.jupiter.api.Assertions.assertTrue +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.io.TempDir +import java.nio.charset.StandardCharsets +import java.nio.file.Files +import java.nio.file.Path +import java.time.Instant +import java.util.UUID + +class JsonOfflineAnonymizationTest { + @TempDir lateinit var directory: Path + private val guard = BlockingOperationGuard { } + private val key = CodeReservationKey("a".repeat(64)) { "b".repeat(64) } + + @Test + fun `anonymization persists across JSON restart`() { + val file = directory.resolve("players.json") + val oldId = UUID.randomUUID() + var historicalId: UUID? = null + JsonInviteCodeStorage.open(file, guard, key).use { storage -> + storage.savePlayer(StoredPlayer(oldId, Instant.parse("2026-01-01T00:00:00Z"), "Alice")) + historicalId = storage.anonymizePlayer(oldId).historicalId + } + JsonInviteCodeStorage.open(file, guard, key).use { storage -> + assertNull(storage.player(oldId)) + assertNotNull(storage.player(requireNotNull(historicalId))) + assertNull(storage.player(requireNotNull(historicalId))?.lastKnownName) + storage.savePlayer(StoredPlayer(oldId, Instant.now(), "AliceAgain")) + assertTrue(storage.invitationsByInviter(oldId).isEmpty()) + } + } + + @Test + fun `explicit version-eight migration preserves JSON player`() { + val file = directory.resolve("legacy.json") + val playerId = UUID.randomUUID() + JsonInviteCodeStorage.open(file, guard).use { storage -> + storage.savePlayer(StoredPlayer(playerId, Instant.parse("2026-01-01T00:00:00Z"), "Alice")) + } + val root = Files.newBufferedReader(file, StandardCharsets.UTF_8).use { + JsonParser.parseReader(it).asJsonObject + } + root.addProperty("schema-version", 8) + val tables = root.getAsJsonObject("tables") + tables.remove("invitecode_reserved_code_hashes") + tables.getAsJsonArray("invitecode_schema_version")[0].asJsonObject.addProperty("version", 8) + Files.newBufferedWriter(file, StandardCharsets.UTF_8).use { it.write(root.toString()) } + + JsonInviteCodeStorage.migrateV8ToV9(file, guard) + assertTrue(Files.exists(file.resolveSibling("legacy.json.previous"))) + JsonInviteCodeStorage.open(file, guard).use { storage -> + assertEquals("Alice", storage.player(playerId)?.lastKnownName) + } + } +} diff --git a/invitecode-storage-sql/src/main/kotlin/io/github/command1264/invitecode/storage/sql/CodeReservationKey.kt b/invitecode-storage-sql/src/main/kotlin/io/github/command1264/invitecode/storage/sql/CodeReservationKey.kt new file mode 100644 index 0000000..35f0c55 --- /dev/null +++ b/invitecode-storage-sql/src/main/kotlin/io/github/command1264/invitecode/storage/sql/CodeReservationKey.kt @@ -0,0 +1,10 @@ +package io.github.command1264.invitecode.storage.sql + +/** The caller owns the secret and must close/erase it when the storage session ends. */ +class CodeReservationKey(val keyId: String, private val digest: (String) -> String) { + init { require(Regex("[0-9a-f]{64}").matches(keyId)) { "Anti-abuse key ID is invalid." } } + + fun hash(normalizedCode: String): String = digest(normalizedCode).also { + require(Regex("[0-9a-f]{64}").matches(it)) { "Reserved-code digest is invalid." } + } +} diff --git a/invitecode-storage-sql/src/main/kotlin/io/github/command1264/invitecode/storage/sql/MysqlInviteCodeStorage.kt b/invitecode-storage-sql/src/main/kotlin/io/github/command1264/invitecode/storage/sql/MysqlInviteCodeStorage.kt index d4e36a1..1e710af 100644 --- a/invitecode-storage-sql/src/main/kotlin/io/github/command1264/invitecode/storage/sql/MysqlInviteCodeStorage.kt +++ b/invitecode-storage-sql/src/main/kotlin/io/github/command1264/invitecode/storage/sql/MysqlInviteCodeStorage.kt @@ -4,16 +4,19 @@ import com.zaxxer.hikari.HikariConfig import com.zaxxer.hikari.HikariDataSource import io.github.command1264.invitecode.core.InviteCodeStorage import io.github.command1264.invitecode.core.MysqlConfiguration +import java.util.UUID class MysqlInviteCodeStorage private constructor( private val pool: HikariDataSource, private val delegate: JdbcInviteCodeStorage, ) : InviteCodeStorage by delegate { override fun close() = pool.close() + fun previewAnonymization(playerId: UUID): AnonymizationPreview = delegate.previewAnonymization(playerId) + fun anonymizePlayer(playerId: UUID): AnonymizationResult = delegate.anonymizePlayer(playerId) companion object { - fun open(pool: HikariDataSource, guard: BlockingOperationGuard): MysqlInviteCodeStorage = - MysqlInviteCodeStorage(pool, JdbcInviteCodeStorage.openMysql(pool, guard)) + fun open(pool: HikariDataSource, guard: BlockingOperationGuard, reservationKey: CodeReservationKey? = null): MysqlInviteCodeStorage = + MysqlInviteCodeStorage(pool, JdbcInviteCodeStorage.openMysql(pool, guard, reservationKey)) fun createPool(config: MysqlConfiguration, password: String): HikariDataSource { val hikari = HikariConfig().apply { diff --git a/invitecode-storage-sql/src/main/kotlin/io/github/command1264/invitecode/storage/sql/MysqlSchemaMigrator.kt b/invitecode-storage-sql/src/main/kotlin/io/github/command1264/invitecode/storage/sql/MysqlSchemaMigrator.kt index 58b87de..41d5782 100644 --- a/invitecode-storage-sql/src/main/kotlin/io/github/command1264/invitecode/storage/sql/MysqlSchemaMigrator.kt +++ b/invitecode-storage-sql/src/main/kotlin/io/github/command1264/invitecode/storage/sql/MysqlSchemaMigrator.kt @@ -54,7 +54,7 @@ class MysqlSchemaMigrator( connection.createStatement().use { statement -> statement.execute(LEDGER_DDL) } } val otherVersions = connection.createStatement().use { statement -> - statement.executeQuery("SELECT COUNT(*) FROM $LEDGER WHERE version <> $CURRENT_VERSION").use { rows -> + statement.executeQuery("SELECT COUNT(*) FROM $LEDGER WHERE version NOT IN (1, 2)").use { rows -> rows.next() rows.getInt(1) } @@ -65,19 +65,25 @@ class MysqlSchemaMigrator( val state = connection.prepareStatement( "SELECT checksum, state FROM $LEDGER WHERE version = ?", ).use { statement -> - statement.setInt(1, CURRENT_VERSION) + statement.setInt(1, 1) statement.executeQuery().use { rows -> if (rows.next()) rows.getString(1) to rows.getString(2) else null } } if (state == null) { + val hasLaterVersion = connection.createStatement().use { statement -> + statement.executeQuery("SELECT 1 FROM $LEDGER WHERE version = 2").use { it.next() } + } + if (hasLaterVersion) throw MysqlStorageException( + "MySQL migration ledger contains version 2 without version 1; preserve the database.", + ) if (TABLES.any { tableExists(connection, schema, it.name) }) { throw MysqlStorageException("MySQL schema ledger has no version record, but InviteCode tables exist; inspect manually.") } connection.prepareStatement( "INSERT INTO $LEDGER(version, checksum, state) VALUES (?, ?, 'APPLYING')", ).use { statement -> - statement.setInt(1, CURRENT_VERSION) + statement.setInt(1, 1) statement.setString(2, CHECKSUM) statement.executeUpdate() } @@ -99,14 +105,39 @@ class MysqlSchemaMigrator( } if (state?.second != "APPLIED") { connection.prepareStatement("UPDATE $LEDGER SET state = 'APPLIED' WHERE version = ? AND state = 'APPLYING'").use { - it.setInt(1, CURRENT_VERSION) + it.setInt(1, 1) check(it.executeUpdate() == 1) { "MySQL schema ledger changed during migration." } } } + val second = connection.prepareStatement("SELECT checksum, state FROM $LEDGER WHERE version = 2").use { statement -> + statement.executeQuery().use { rows -> if (rows.next()) rows.getString(1) to rows.getString(2) else null } + } + if (second == null) { + if (tableExists(connection, schema, V2_TABLE.name)) throw MysqlStorageException( + "MySQL reserved-code table exists without a migration record; inspect the database.", + ) + connection.prepareStatement("INSERT INTO $LEDGER(version, checksum, state) VALUES (2, ?, 'APPLYING')").use { + it.setString(1, V2_CHECKSUM) + it.executeUpdate() + } + } else if (second.first != V2_CHECKSUM || second.second !in setOf("APPLYING", "APPLIED")) { + throw MysqlStorageException("MySQL reserved-code migration checksum or state differs; preserve the database.") + } + if (!tableExists(connection, schema, V2_TABLE.name)) { + if (second?.second == "APPLIED") throw MysqlStorageException("MySQL reserved-code table is missing; preserve the database.") + connection.createStatement().use { it.execute(V2_TABLE.ddl) } + afterTable(V2_TABLE.name) + } + verifyTable(connection, schema, V2_TABLE) + if (second?.second != "APPLIED") { + connection.prepareStatement("UPDATE $LEDGER SET state = 'APPLIED' WHERE version = 2 AND state = 'APPLYING'").use { + check(it.executeUpdate() == 1) { "MySQL reserved-code migration ledger changed." } + } + } } companion object { - const val CURRENT_VERSION = 1 + const val CURRENT_VERSION = 2 private const val LEDGER = "invitecode_schema_migrations" private const val LEDGER_DDL = """ CREATE TABLE invitecode_schema_migrations ( @@ -127,12 +158,20 @@ class MysqlSchemaMigrator( TableDefinition(match.groupValues[1], ddl) } private val CHECKSUM = sha256(RESOURCE) + private val V2_RESOURCE = requireNotNull(MysqlSchemaMigrator::class.java.getResource("/mysql/V2__reserved_code_hashes.sql")) { + "Bundled MySQL reserved-code migration resource is missing." + }.readText(StandardCharsets.UTF_8) + private val V2_TABLE = TableDefinition( + "invitecode_reserved_code_hashes", + V2_RESOURCE.substringAfter("-- @table invitecode_reserved_code_hashes").trim().removeSuffix(";"), + ) + private val V2_CHECKSUM = sha256(V2_RESOURCE) fun isInitialized(connection: Connection): Boolean { val schema = schemaName(connection) if (!tableExists(connection, schema, LEDGER)) return false return connection.prepareStatement("SELECT state FROM $LEDGER WHERE version = ?").use { statement -> - statement.setInt(1, CURRENT_VERSION) + statement.setInt(1, 1) statement.executeQuery().use { rows -> rows.next() && rows.getString(1) == "APPLIED" } } } @@ -143,7 +182,7 @@ class MysqlSchemaMigrator( "MySQL schema is not initialized; run explicit storage migration or use an empty database for first startup.", ) val otherVersions = connection.createStatement().use { statement -> - statement.executeQuery("SELECT COUNT(*) FROM $LEDGER WHERE version <> $CURRENT_VERSION").use { rows -> + statement.executeQuery("SELECT COUNT(*) FROM $LEDGER WHERE version NOT IN (1, 2)").use { rows -> rows.next() rows.getInt(1) } @@ -152,7 +191,7 @@ class MysqlSchemaMigrator( "MySQL schema contains another version; use a matching InviteCode version or explicit migration.", ) val row = connection.prepareStatement("SELECT checksum, state FROM $LEDGER WHERE version = ?").use { statement -> - statement.setInt(1, CURRENT_VERSION) + statement.setInt(1, 1) statement.executeQuery().use { rows -> if (rows.next()) rows.getString(1) to rows.getString(2) else null } @@ -161,6 +200,15 @@ class MysqlSchemaMigrator( "MySQL schema version/checksum is not current; run explicit storage migration after inspecting the database.", ) TABLES.forEach { verifyTable(connection, schema, it) } + val version2 = connection.prepareStatement("SELECT checksum, state FROM $LEDGER WHERE version = 2").use { statement -> + statement.executeQuery().use { rows -> + if (rows.next()) rows.getString(1) to rows.getString(2) else null + } + } + if (version2 != (V2_CHECKSUM to "APPLIED")) throw MysqlStorageException( + "MySQL reserved-code migration is not current; run explicit migration after a backup.", + ) + verifyTable(connection, schema, V2_TABLE) } fun bindNetworkKey(connection: Connection, keyId: String) { diff --git a/invitecode-storage-sql/src/main/kotlin/io/github/command1264/invitecode/storage/sql/OfflinePlayerAnonymizer.kt b/invitecode-storage-sql/src/main/kotlin/io/github/command1264/invitecode/storage/sql/OfflinePlayerAnonymizer.kt new file mode 100644 index 0000000..637b109 --- /dev/null +++ b/invitecode-storage-sql/src/main/kotlin/io/github/command1264/invitecode/storage/sql/OfflinePlayerAnonymizer.kt @@ -0,0 +1,302 @@ +package io.github.command1264.invitecode.storage.sql + +import java.sql.Connection +import java.sql.ResultSet +import java.sql.Types +import java.time.Instant +import java.util.UUID +import java.util.Locale +import io.github.command1264.invitecode.core.AuditRecord +import io.github.command1264.invitecode.core.InvitationAuditAction + +/** Only the maintenance entry point calls this; all callers must stop every writer and take a backup first. */ +data class AnonymizationPreview( + val invitations: Int, + val rewardDeliveries: Int, + val retiredCodes: Int, +) + +data class AnonymizationResult(val historicalId: UUID, val preview: AnonymizationPreview) + +internal object OfflinePlayerAnonymizer { + private const val REDACTED = "[anonymized]" + private val unsettled = setOf("PENDING", "PROCESSING", "UNCERTAIN") + + fun preview(connection: Connection, playerId: UUID): AnonymizationPreview = collect(connection, playerId).preview + + fun anonymize( + connection: Connection, + playerId: UUID, + keyId: String, + hashCode: (String) -> String, + ): AnonymizationResult { + require(Regex("[0-9a-f]{64}").matches(keyId)) { "Anti-abuse key ID is invalid." } + if (connection.isMysql()) { + val locked = connection.prepareStatement( + "SELECT player_id FROM invitecode_players WHERE player_id = ? FOR UPDATE", + ).use { statement -> + statement.setString(1, playerId.toString()) + statement.executeQuery().use { it.next() } + } + check(locked) { "Player $playerId is absent; it may already be anonymized." } + } + val scope = collect(connection, playerId) + val old = playerId.toString() + val historical = UUID.randomUUID().toString() + check(row(connection, "invitecode_players", "player_id", historical) == null) { + "Generated historical ID collided with an existing player; retry after rollback." + } + val player = requireNotNull(row(connection, "invitecode_players", "player_id", old)) + insert(connection, "invitecode_players", player + ("player_id" to historical) + ("last_known_name" to null)) + + // Reward IDs and idempotency keys can be derived from the Minecraft UUID. Copy first, then + // repoint transition FKs and remove the originals within the same storage transaction. + scope.deliveries.forEach { deliveryId -> + val delivery = requireNotNull(row(connection, "invitecode_reward_deliveries", "delivery_id", deliveryId)) + val replacement = UUID.randomUUID().toString() + insert(connection, "invitecode_reward_deliveries", delivery + mapOf( + "delivery_id" to replacement, + "reward_id" to REDACTED, + "idempotency_key" to "anonymized:${UUID.randomUUID()}", + )) + queryIds(connection, "SELECT action_id FROM invitecode_reward_actions WHERE reward_delivery_id = ?", deliveryId) + .forEach { actionId -> + val action = requireNotNull(row(connection, "invitecode_reward_actions", "action_id", actionId)) + val replacementAction = UUID.randomUUID().toString() + insert(connection, "invitecode_reward_actions", action + mapOf( + "action_id" to replacementAction, + "reward_delivery_id" to replacement, + "recipient_id" to if (action["recipient_id"] == old) historical else action["recipient_id"], + "payload" to REDACTED, + "idempotency_key" to "anonymized:${UUID.randomUUID()}", + "last_error" to if (action["last_error"] == null) null else REDACTED, + )) + update(connection, """ + UPDATE invitecode_reward_action_transitions + SET action_id = ?, last_error = CASE WHEN last_error IS NULL THEN NULL ELSE ? END, + actor = CASE WHEN actor IS NULL THEN NULL ELSE ? END, + reason = CASE WHEN reason IS NULL THEN NULL ELSE ? END + WHERE action_id = ? + """, replacementAction, REDACTED, REDACTED, REDACTED, actionId) + update(connection, "DELETE FROM invitecode_reward_actions WHERE action_id = ?", actionId) + } + update(connection, """ + UPDATE invitecode_reward_delivery_transitions + SET delivery_id = ?, actor = CASE WHEN actor IS NULL THEN NULL ELSE ? END, + reason = CASE WHEN reason IS NULL THEN NULL ELSE ? END + WHERE delivery_id = ? + """, replacement, REDACTED, REDACTED, deliveryId) + update(connection, "DELETE FROM invitecode_reward_deliveries WHERE delivery_id = ?", deliveryId) + } + + scope.codes.forEach { code -> + val digest = hashCode(code) + require(Regex("[0-9a-f]{64}").matches(digest)) { "Reserved-code digest is invalid." } + insert(connection, "invitecode_reserved_code_hashes", mapOf("code_hash" to digest, "key_id" to keyId)) + } + update(connection, "DELETE FROM invitecode_codes WHERE inviter_id = ?", old) + + // Redact every structurally related audit row before changing its player reference. + val auditIds = queryIds(connection, """ + SELECT audit_id FROM invitecode_audit_records WHERE player_id = ? + OR previous_inviter_id = ? OR new_inviter_id = ? + OR invitation_id IN (SELECT invitation_id FROM invitecode_invitations WHERE inviter_id = ? OR invitee_id = ?) + """, old, old, old, old, old) + auditIds.forEach { id -> + update(connection, """ + UPDATE invitecode_audit_records SET audit_id = ?, actor = ?, reason = ?, + qualification_policy_id = CASE WHEN qualification_policy_id IS NULL THEN NULL ELSE ? END, + qualification_revision = CASE WHEN qualification_revision IS NULL THEN NULL ELSE ? END + WHERE audit_id = ? + """, UUID.randomUUID().toString(), REDACTED, REDACTED, REDACTED, REDACTED, id) + } + update(connection, "UPDATE invitecode_audit_records SET player_id = ? WHERE player_id = ?", historical, old) + update(connection, "UPDATE invitecode_audit_records SET previous_inviter_id = ? WHERE previous_inviter_id = ?", historical, old) + update(connection, "UPDATE invitecode_audit_records SET new_inviter_id = ? WHERE new_inviter_id = ?", historical, old) + + scope.invitations.forEach { id -> + update(connection, """ + UPDATE invitecode_invitations + SET qualification_policy_id = CASE WHEN qualification_policy_id IS NULL THEN NULL ELSE ? END, + qualification_revision = CASE WHEN qualification_revision IS NULL THEN NULL ELSE ? END + WHERE invitation_id = ? + """, REDACTED, REDACTED, id) + update(connection, """ + UPDATE invitecode_qualification_facts + SET policy_id = ?, qualification_revision = ?, condition_id = ? WHERE invitation_id = ? + """, REDACTED, REDACTED, REDACTED, id) + } + update(connection, "UPDATE invitecode_invitations SET inviter_id = ? WHERE inviter_id = ?", historical, old) + update(connection, "UPDATE invitecode_invitations SET invitee_id = ? WHERE invitee_id = ?", historical, old) + // A reward action for this player can belong to an unrelated delivery; collect() includes it. + update(connection, "UPDATE invitecode_reward_actions SET recipient_id = ? WHERE recipient_id = ?", historical, old) + val oldName = player["last_known_name"] as? String + if (!oldName.isNullOrBlank()) redactSafeFreeText(connection, oldName) + update(connection, "DELETE FROM invitecode_player_login_days WHERE player_id = ?", old) + update(connection, "DELETE FROM invitecode_player_network_hashes WHERE player_id = ?", old) + check(update(connection, "DELETE FROM invitecode_players WHERE player_id = ?", old) == 1) { + "Original player record changed during anonymization." + } + SqliteAuditRecords.save(connection, AuditRecord( + UUID.randomUUID(), InvitationAuditAction.PLAYER_ANONYMIZED, + "offline-maintenance", "privacy request", Instant.now(), playerId = UUID.fromString(historical), + )) + verifyNoOriginalUuid(connection, old) + if (!oldName.isNullOrBlank()) verifyNoOriginalName(connection, oldName) + return AnonymizationResult(UUID.fromString(historical), scope.preview) + } + + private fun redactSafeFreeText(connection: Connection, originalName: String) { + val fields = mapOf( + "invitecode_audit_records" to listOf("actor", "reason"), + "invitecode_reward_action_transitions" to listOf("actor", "reason", "last_error"), + "invitecode_reward_delivery_transitions" to listOf("actor", "reason"), + ) + val needle = originalName.lowercase(Locale.ROOT) + fields.forEach { (table, columns) -> + columns.forEach { column -> + connection.prepareStatement( + "UPDATE $table SET $column = ? WHERE INSTR(LOWER($column), ?) > 0", + ).use { statement -> + statement.setString(1, REDACTED) + statement.setString(2, needle) + statement.executeUpdate() + } + } + } + } + + private fun verifyNoOriginalName(connection: Connection, originalName: String) { + val fields = mapOf( + "invitecode_audit_records" to listOf("actor", "reason", "qualification_policy_id", "qualification_revision"), + "invitecode_reward_actions" to listOf("payload", "last_error", "idempotency_key"), + "invitecode_reward_deliveries" to listOf("reward_id", "idempotency_key"), + "invitecode_reward_action_transitions" to listOf("actor", "reason", "last_error"), + "invitecode_reward_delivery_transitions" to listOf("actor", "reason"), + "invitecode_invitations" to listOf("qualification_policy_id", "qualification_revision"), + "invitecode_qualification_facts" to listOf("policy_id", "qualification_revision", "condition_id"), + ) + fields.forEach { (table, columns) -> + val conditions = columns.joinToString(" OR ") { "INSTR(LOWER($it), ?) > 0" } + connection.prepareStatement("SELECT 1 FROM $table WHERE $conditions LIMIT 1").use { statement -> + columns.indices.forEach { index -> + statement.setString(index + 1, originalName.lowercase(Locale.ROOT)) + } + statement.executeQuery().use { rows -> + check(!rows.next()) { + "Player name remains in $table; anonymization was rolled back. " + + "Inspect unrelated free text and unresolved rewards before retrying." + } + } + } + } + } + + private fun verifyNoOriginalUuid(connection: Connection, original: String) { + val tables = listOf( + "invitecode_players", "invitecode_codes", "invitecode_invitations", "invitecode_qualification_facts", + "invitecode_reward_deliveries", "invitecode_reward_actions", "invitecode_audit_records", + "invitecode_reward_delivery_transitions", "invitecode_reward_action_transitions", + "invitecode_player_login_days", "invitecode_player_network_hashes", "invitecode_reserved_code_hashes", + ) + tables.forEach { table -> + val textColumns = connection.createStatement().use { statement -> + statement.executeQuery("SELECT * FROM $table WHERE 1 = 0").use { rows -> + val metadata = rows.metaData + (1..metadata.columnCount).filter { index -> + metadata.getColumnType(index) in setOf( + Types.CHAR, Types.VARCHAR, Types.LONGVARCHAR, + Types.NCHAR, Types.NVARCHAR, Types.LONGNVARCHAR, + ) + }.map { index -> + metadata.getColumnName(index).also { name -> + require(Regex("[a-z_]+").matches(name)) { "Storage column name is invalid." } + } + } + } + } + if (textColumns.isNotEmpty()) { + val conditions = textColumns.joinToString(" OR ") { "LOWER($it) LIKE ?" } + listOf(original, original.replace("-", "")).forEach { needle -> + connection.prepareStatement("SELECT 1 FROM $table WHERE $conditions LIMIT 1").use { statement -> + textColumns.indices.forEach { index -> statement.setString(index + 1, "%$needle%") } + statement.executeQuery().use { rows -> + check(!rows.next()) { + "Original Minecraft UUID remains in $table; anonymization was rolled back. " + + "Inspect related text without exposing private data." + } + } + } + } + } + } + } + + private data class Scope(val invitations: List, val deliveries: List, val codes: List) { + val preview = AnonymizationPreview(invitations.size, deliveries.size, codes.size) + } + + private fun collect(connection: Connection, playerId: UUID): Scope { + val id = playerId.toString() + check(row(connection, "invitecode_players", "player_id", id) != null) { + "Player $id is absent; it may already be anonymized." + } + val invitations = queryIds(connection, + "SELECT invitation_id FROM invitecode_invitations WHERE inviter_id = ? OR invitee_id = ?", id, id) + val deliveries = queryIds(connection, """ + SELECT DISTINCT d.delivery_id FROM invitecode_reward_deliveries d + LEFT JOIN invitecode_reward_actions a ON a.reward_delivery_id = d.delivery_id + WHERE d.invitation_id IN ( + SELECT invitation_id FROM invitecode_invitations WHERE inviter_id = ? OR invitee_id = ? + ) OR a.recipient_id = ? OR a.invitation_id IN ( + SELECT invitation_id FROM invitecode_invitations WHERE inviter_id = ? OR invitee_id = ? + ) + """, id, id, id, id, id) + deliveries.forEach { deliveryId -> + val delivery = requireNotNull(row(connection, "invitecode_reward_deliveries", "delivery_id", deliveryId)) + check(delivery["status"] !in unsettled) { + "Reward Delivery $deliveryId is unresolved; resolve it before anonymization." + } + queryIds(connection, "SELECT status FROM invitecode_reward_actions WHERE reward_delivery_id = ?", deliveryId) + .forEach { status -> check(status !in unsettled) { + "Reward Delivery $deliveryId contains an unresolved action; resolve it before anonymization." + } } + } + val codes = queryIds(connection, "SELECT code FROM invitecode_codes WHERE inviter_id = ?", id) + return Scope(invitations, deliveries, codes) + } + + private fun queryIds(connection: Connection, sql: String, vararg values: String): List = + connection.prepareStatement(sql).use { statement -> + values.forEachIndexed { index, value -> statement.setString(index + 1, value) } + statement.executeQuery().use { result -> buildList { while (result.next()) add(result.getString(1)) } } + } + + private fun row(connection: Connection, table: String, key: String, id: String): Map? = + connection.prepareStatement("SELECT * FROM $table WHERE $key = ?").use { statement -> + statement.setString(1, id) + statement.executeQuery().use { result -> + if (!result.next()) null else result.toMap().filterKeys { it !in setOf("idempotency_hash", "active_inviter_id") } + } + } + + private fun ResultSet.toMap(): Map = buildMap { + val metadata = metaData + for (index in 1..metadata.columnCount) put(metadata.getColumnName(index), getObject(index)) + } + + private fun insert(connection: Connection, table: String, values: Map) { + val names = values.keys.toList() + val placeholders = names.joinToString(",") { "?" } + connection.prepareStatement("INSERT INTO $table (${names.joinToString(",")}) VALUES ($placeholders)").use { statement -> + names.forEachIndexed { index, name -> statement.setObject(index + 1, values[name]) } + check(statement.executeUpdate() == 1) { "Insert into $table did not affect one row." } + } + } + + private fun update(connection: Connection, sql: String, vararg values: String): Int = + connection.prepareStatement(sql).use { statement -> + values.forEachIndexed { index, value -> statement.setString(index + 1, value) } + statement.executeUpdate() + } +} diff --git a/invitecode-storage-sql/src/main/kotlin/io/github/command1264/invitecode/storage/sql/SqliteIdentityRecords.kt b/invitecode-storage-sql/src/main/kotlin/io/github/command1264/invitecode/storage/sql/SqliteIdentityRecords.kt index da764b4..a3895f3 100644 --- a/invitecode-storage-sql/src/main/kotlin/io/github/command1264/invitecode/storage/sql/SqliteIdentityRecords.kt +++ b/invitecode-storage-sql/src/main/kotlin/io/github/command1264/invitecode/storage/sql/SqliteIdentityRecords.kt @@ -272,11 +272,33 @@ internal object SqliteInviteCodeRecords { } } - fun isReserved(connection: Connection, code: InviteCode): Boolean = - connection.prepareStatement("SELECT 1 FROM invitecode_codes WHERE code = ?").use { statement -> + fun isReserved(connection: Connection, code: InviteCode, reservationKey: CodeReservationKey? = null): Boolean { + val existing = connection.prepareStatement("SELECT 1 FROM invitecode_codes WHERE code = ?").use { statement -> statement.setString(1, code.normalized) statement.executeQuery().use { it.next() } } + if (existing) return true + if (reservationKey == null) { + val tombstonesExist = connection.createStatement().use { statement -> + statement.executeQuery("SELECT 1 FROM invitecode_reserved_code_hashes LIMIT 1").use { it.next() } + } + check(!tombstonesExist) { "Reserved Invite Codes exist, but their secret is unavailable; code allocation is disabled." } + return false + } + val foreignKey = connection.prepareStatement( + "SELECT 1 FROM invitecode_reserved_code_hashes WHERE key_id <> ? LIMIT 1", + ).use { statement -> + statement.setString(1, reservationKey.keyId) + statement.executeQuery().use { it.next() } + } + check(!foreignKey) { "Reserved Invite Codes use another anti-abuse key; restore the original secret." } + return connection.prepareStatement( + "SELECT 1 FROM invitecode_reserved_code_hashes WHERE code_hash = ?", + ).use { statement -> + statement.setString(1, reservationKey.hash(code.normalized)) + statement.executeQuery().use { it.next() } + } + } fun activate(connection: Connection, activeInviteCode: ActiveInviteCode) { connection.prepareStatement( diff --git a/invitecode-storage-sql/src/main/kotlin/io/github/command1264/invitecode/storage/sql/SqliteInviteCodeStorage.kt b/invitecode-storage-sql/src/main/kotlin/io/github/command1264/invitecode/storage/sql/SqliteInviteCodeStorage.kt index 4b80309..0cd0e9c 100644 --- a/invitecode-storage-sql/src/main/kotlin/io/github/command1264/invitecode/storage/sql/SqliteInviteCodeStorage.kt +++ b/invitecode-storage-sql/src/main/kotlin/io/github/command1264/invitecode/storage/sql/SqliteInviteCodeStorage.kt @@ -38,6 +38,7 @@ internal class JdbcInviteCodeStorage private constructor( private val database: Path?, private val mysqlSource: DataSource?, private val blockingOperationGuard: BlockingOperationGuard, + private val reservationKey: CodeReservationKey?, ) : InviteCodeStorage { override fun qualifiedInvitationCount(inviterId: UUID): Int = read { SqliteInvitationRecords.countQualifiedForInviter(it, inviterId) @@ -90,7 +91,7 @@ internal class JdbcInviteCodeStorage private constructor( } override fun isInviteCodeReserved(code: InviteCode): Boolean = read { - SqliteInviteCodeRecords.isReserved(it, code) + SqliteInviteCodeRecords.isReserved(it, code, reservationKey) } override fun saveInvitation(invitation: Invitation) { @@ -354,14 +355,16 @@ internal class JdbcInviteCodeStorage private constructor( SqliteInviteCodeRecords.findActive(connection, inviterId) override fun isReserved(code: InviteCode): Boolean = - SqliteInviteCodeRecords.isReserved(connection, code) + SqliteInviteCodeRecords.isReserved(connection, code, reservationKey) override fun activate(activeInviteCode: ActiveInviteCode) { + check(!isReserved(activeInviteCode.code)) { "Invite Code has already been reserved." } SqliteInviteCodeRecords.activate(connection, activeInviteCode) } override fun replace(previous: RetiredInviteCode, current: ActiveInviteCode) { SqliteInviteCodeRecords.retire(connection, previous) + check(!isReserved(current.code)) { "Invite Code has already been reserved." } SqliteInviteCodeRecords.activate(connection, current) } @@ -414,6 +417,37 @@ internal class JdbcInviteCodeStorage private constructor( override fun close() = Unit + fun previewAnonymization(playerId: UUID): AnonymizationPreview = read { + OfflinePlayerAnonymizer.preview(it, playerId) + } + + fun anonymizePlayer(playerId: UUID): AnonymizationResult { + val key = requireNotNull(reservationKey) { "Anti-abuse secret is required for anonymization." } + val source = mysqlSource ?: return write { OfflinePlayerAnonymizer.anonymize(it, playerId, key.keyId, key::hash) } + // Maintenance tools share this schema-scoped lock across processes, including through commit. + return source.connection.use { lockConnection -> + val lockName = "ic-anon:" + lockConnection.createStatement().use { statement -> + statement.executeQuery("SELECT LEFT(SHA2(DATABASE(), 256), 40)").use { rows -> + check(rows.next()) { "MySQL did not return the selected schema." } + rows.getString(1) + } + } + val acquired = lockConnection.prepareStatement("SELECT GET_LOCK(?, 10)").use { statement -> + statement.setString(1, lockName) + statement.executeQuery().use { rows -> rows.next() && rows.getInt(1) == 1 } + } + check(acquired) { "MySQL anonymization lock timed out; check other maintenance processes." } + try { + write { OfflinePlayerAnonymizer.anonymize(it, playerId, key.keyId, key::hash) } + } finally { + lockConnection.prepareStatement("SELECT RELEASE_LOCK(?)").use { statement -> + statement.setString(1, lockName) + statement.executeQuery().close() + } + } + } + } + private fun read(operation: (Connection) -> T): T { blockingOperationGuard.checkAllowed() try { @@ -512,6 +546,7 @@ internal class JdbcInviteCodeStorage private constructor( fun openSqlite( database: Path, blockingOperationGuard: BlockingOperationGuard, + reservationKey: CodeReservationKey? = null, ): JdbcInviteCodeStorage { blockingOperationGuard.checkAllowed() connect(database).use { connection -> @@ -531,16 +566,35 @@ internal class JdbcInviteCodeStorage private constructor( "${SqliteSchemaMigrator.currentVersion}; run the explicit schema migration.", ) } + if (reservationKey != null) { + val otherKey = connection.prepareStatement( + "SELECT 1 FROM invitecode_reserved_code_hashes WHERE key_id <> ? LIMIT 1", + ).use { statement -> + statement.setString(1, reservationKey.keyId) + statement.executeQuery().use { it.next() } + } + check(!otherKey) { "Reserved Invite Codes use another anti-abuse key; restore the original secret." } + } } - return JdbcInviteCodeStorage(database, null, blockingOperationGuard) + return JdbcInviteCodeStorage(database, null, blockingOperationGuard, reservationKey) } - fun openMysql(dataSource: DataSource, guard: BlockingOperationGuard): JdbcInviteCodeStorage { + fun openMysql(dataSource: DataSource, guard: BlockingOperationGuard, reservationKey: CodeReservationKey? = null): JdbcInviteCodeStorage { guard.checkAllowed() dataSource.connection.use { connection -> MysqlSchemaMigrator.requireCurrent(connection) + if (reservationKey != null) { + val storedKey = connection.createStatement().use { statement -> + statement.executeQuery("SELECT network_key_id FROM invitecode_metadata WHERE singleton = 1").use { rows -> + if (rows.next()) rows.getString(1) else null + } + } + check(storedKey == reservationKey.keyId) { + "MySQL anti-abuse secret does not match the database; restore the shared secret." + } + } } - return JdbcInviteCodeStorage(null, dataSource, guard) + return JdbcInviteCodeStorage(null, dataSource, guard, reservationKey) } private fun configure(connection: Connection) { @@ -556,10 +610,12 @@ class SqliteInviteCodeStorage private constructor( private val delegate: JdbcInviteCodeStorage, ) : InviteCodeStorage by delegate { override fun close() = delegate.close() + fun previewAnonymization(playerId: UUID): AnonymizationPreview = delegate.previewAnonymization(playerId) + fun anonymizePlayer(playerId: UUID): AnonymizationResult = delegate.anonymizePlayer(playerId) companion object { - fun open(database: Path, guard: BlockingOperationGuard): SqliteInviteCodeStorage = - SqliteInviteCodeStorage(JdbcInviteCodeStorage.openSqlite(database, guard)) + fun open(database: Path, guard: BlockingOperationGuard, reservationKey: CodeReservationKey? = null): SqliteInviteCodeStorage = + SqliteInviteCodeStorage(JdbcInviteCodeStorage.openSqlite(database, guard, reservationKey)) } } diff --git a/invitecode-storage-sql/src/main/kotlin/io/github/command1264/invitecode/storage/sql/SqliteSchemaMigrator.kt b/invitecode-storage-sql/src/main/kotlin/io/github/command1264/invitecode/storage/sql/SqliteSchemaMigrator.kt index a802132..4b65fcf 100644 --- a/invitecode-storage-sql/src/main/kotlin/io/github/command1264/invitecode/storage/sql/SqliteSchemaMigrator.kt +++ b/invitecode-storage-sql/src/main/kotlin/io/github/command1264/invitecode/storage/sql/SqliteSchemaMigrator.kt @@ -401,6 +401,18 @@ class SqliteSchemaMigrator( """.trimIndent(), ), ), + SqliteSchemaMigration( + version = 9, + description = "Reserve anonymized Invite Codes without storing their plaintext", + statements = listOf( + """ + CREATE TABLE invitecode_reserved_code_hashes ( + code_hash TEXT PRIMARY KEY, + key_id TEXT NOT NULL + ) + """.trimIndent(), + ), + ), ) val currentVersion: Int diff --git a/invitecode-storage-sql/src/main/resources/mysql/V2__reserved_code_hashes.sql b/invitecode-storage-sql/src/main/resources/mysql/V2__reserved_code_hashes.sql new file mode 100644 index 0000000..22bd113 --- /dev/null +++ b/invitecode-storage-sql/src/main/resources/mysql/V2__reserved_code_hashes.sql @@ -0,0 +1,6 @@ +-- @table invitecode_reserved_code_hashes +CREATE TABLE invitecode_reserved_code_hashes ( + code_hash CHAR(64) CHARACTER SET ascii COLLATE ascii_bin NOT NULL, + key_id CHAR(64) CHARACTER SET ascii COLLATE ascii_bin NOT NULL, + PRIMARY KEY (code_hash) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci; diff --git a/invitecode-storage-sql/src/test/kotlin/io/github/command1264/invitecode/storage/sql/MysqlIntegrationTest.kt b/invitecode-storage-sql/src/test/kotlin/io/github/command1264/invitecode/storage/sql/MysqlIntegrationTest.kt index d5fe401..d71ca77 100644 --- a/invitecode-storage-sql/src/test/kotlin/io/github/command1264/invitecode/storage/sql/MysqlIntegrationTest.kt +++ b/invitecode-storage-sql/src/test/kotlin/io/github/command1264/invitecode/storage/sql/MysqlIntegrationTest.kt @@ -41,6 +41,61 @@ class MysqlStorageContractTest : StorageContractTest() { } class MysqlIntegrationTest { + @Test + fun `MySQL anonymization preserves tombstone and permits a fresh player record`() = withMysqlSchema { _, pool -> + val guard = BlockingOperationGuard { } + MysqlSchemaMigrator(pool, guard).migrate() + val key = CodeReservationKey("a".repeat(64)) { "b".repeat(64) } + pool.connection.use { MysqlSchemaMigrator.bindNetworkKey(it, key.keyId) } + val oldId = UUID.randomUUID() + val inviteeId = UUID.randomUUID() + val invitationId = UUID.randomUUID() + val deliveryId = UUID.randomUUID() + val actionId = UUID.randomUUID() + MysqlInviteCodeStorage.open(pool, guard, key).use { storage -> + storage.savePlayer(StoredPlayer(oldId, Instant.parse("2026-01-01T00:00:00Z"), "Alice")) + storage.savePlayer(StoredPlayer(inviteeId, Instant.parse("2026-01-01T00:00:00Z"), "Bob")) + pool.connection.use { connection -> + fun insert(sql: String, vararg values: String) = connection.prepareStatement(sql).use { statement -> + values.forEachIndexed { index, value -> statement.setString(index + 1, value) } + statement.executeUpdate() + } + insert("INSERT INTO invitecode_codes(code, inviter_id, activated_at) VALUES (?, ?, ?)", + "A1B2C3", oldId.toString(), "2026-01-01T00:00:00Z") + insert(""" + INSERT INTO invitecode_invitations(invitation_id, inviter_id, inviter_eligibility_generation, + invitee_id, invitee_eligibility_generation, status, claimed_at) + VALUES (?, ?, 0, ?, 0, 'CLAIMED', '2026-01-02T00:00:00Z') + """, invitationId.toString(), oldId.toString(), inviteeId.toString()) + insert(""" + INSERT INTO invitecode_reward_deliveries(delivery_id, invitation_id, reward_id, status, + idempotency_key, created_at, updated_at) + VALUES (?, ?, 'Alice reward', 'DELIVERED', ?, '2026-01-03T00:00:00Z', '2026-01-03T00:00:00Z') + """, deliveryId.toString(), invitationId.toString(), "milestone:$oldId") + insert(""" + INSERT INTO invitecode_reward_actions(action_id, reward_delivery_id, invitation_id, recipient_id, + position, action_type, payload, status, idempotency_key, created_at, updated_at) + VALUES (?, ?, ?, ?, 0, 'MESSAGE', 'Hello Alice', 'DELIVERED', ?, + '2026-01-03T00:00:00Z', '2026-01-03T00:00:00Z') + """, actionId.toString(), deliveryId.toString(), invitationId.toString(), oldId.toString(), "action:$oldId") + insert(""" + INSERT INTO invitecode_reward_action_transitions(action_id, previous_status, current_status, + occurred_at, actor, reason) + VALUES (?, 'PENDING', 'DELIVERED', '2026-01-03T00:00:00Z', 'Alice', 'Alice approved') + """, actionId.toString()) + } + val result = storage.anonymizePlayer(oldId) + assertEquals(null, storage.player(oldId)) + assertEquals(null, storage.player(result.historicalId)?.lastKnownName) + assertEquals(result.historicalId, storage.invitation(invitationId)?.inviterId) + assertEquals(null, storage.rewardDelivery(deliveryId)) + assertEquals(null, storage.rewardAction(actionId)) + assertEquals(true, storage.isInviteCodeReserved(InviteCode.fromNormalized("A1B2C3"))) + storage.savePlayer(StoredPlayer(oldId, Instant.now(), "Again")) + assertEquals("Again", storage.player(oldId)?.lastKnownName) + } + } + @Test fun `interrupted DDL resumes only after checking existing tables`() = withMysqlSchema { _, pool -> val guard = BlockingOperationGuard { } @@ -49,7 +104,7 @@ class MysqlIntegrationTest { if (name == "invitecode_players") error("simulated power loss after committed DDL") }.migrate() } - assertEquals(1, MysqlSchemaMigrator(pool, guard).migrate()) + assertEquals(2, MysqlSchemaMigrator(pool, guard).migrate()) pool.connection.use(MysqlSchemaMigrator::requireCurrent) } diff --git a/invitecode-storage-sql/src/test/kotlin/io/github/command1264/invitecode/storage/sql/OfflinePlayerAnonymizerTest.kt b/invitecode-storage-sql/src/test/kotlin/io/github/command1264/invitecode/storage/sql/OfflinePlayerAnonymizerTest.kt new file mode 100644 index 0000000..8293fa6 --- /dev/null +++ b/invitecode-storage-sql/src/test/kotlin/io/github/command1264/invitecode/storage/sql/OfflinePlayerAnonymizerTest.kt @@ -0,0 +1,279 @@ +package io.github.command1264.invitecode.storage.sql + +import io.github.command1264.invitecode.core.InviteCode +import io.github.command1264.invitecode.core.ActiveInviteCode +import java.time.Instant +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertFalse +import org.junit.jupiter.api.Assertions.assertNotNull +import org.junit.jupiter.api.Assertions.assertNull +import org.junit.jupiter.api.Assertions.assertThrows +import org.junit.jupiter.api.Assertions.assertTrue +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.io.TempDir +import java.nio.file.Path +import java.security.MessageDigest +import java.sql.Connection +import java.util.UUID + +class OfflinePlayerAnonymizerTest { + @TempDir lateinit var directory: Path + private val guard = BlockingOperationGuard { } + private val key = CodeReservationKey("a".repeat(64)) { code -> + MessageDigest.getInstance("SHA-256").digest(("test secret:" + code).toByteArray()) + .joinToString("") { "%02x".format(it.toInt() and 0xff) } + } + + @Test + fun `completed history survives without original identity or reusable code`() { + val database = directory.resolve("history.db") + SqliteSchemaMigrator(database, guard).migrate() + val inviter = UUID.randomUUID() + val invitee = UUID.randomUUID() + val invitation = UUID.randomUUID() + val delivery = UUID.nameUUIDFromBytes("milestone:$inviter".toByteArray()) + val action = UUID.nameUUIDFromBytes("action:$inviter".toByteArray()) + seed(database, inviter, invitee, invitation, delivery, action, "DELIVERED") + + SqliteInviteCodeStorage.open(database, guard, key).use { storage -> + assertEquals(1, storage.previewAnonymization(inviter).invitations) + val result = storage.anonymizePlayer(inviter) + assertEquals(1, result.preview.retiredCodes) + assertNull(storage.player(inviter)) + assertNull(storage.activeInviteCode(InviteCode.fromNormalized("A1B2C3"))) + assertTrue(storage.isInviteCodeReserved(InviteCode.fromNormalized("A1B2C3"))) + assertEquals(result.historicalId, storage.invitation(invitation)?.inviterId) + assertNull(storage.player(result.historicalId)?.lastKnownName) + assertNull(storage.rewardDelivery(delivery)) + assertNull(storage.rewardAction(action)) + assertTrue(storage.auditHistoryByPlayer(inviter, 10).isEmpty()) + assertTrue(storage.auditHistoryByPlayer(result.historicalId, 10).isNotEmpty()) + assertTrue(storage.auditHistoryByPlayer(result.historicalId, 10).all { + !it.reason.contains(inviter.toString()) && !it.actor.contains("Alice") + }) + connect(database).use { connection -> + assertEquals(0, count(connection, "SELECT COUNT(*) FROM invitecode_player_network_hashes WHERE player_id = ?", inviter)) + assertEquals(0, count(connection, "SELECT COUNT(*) FROM invitecode_player_login_days WHERE player_id = ?", inviter)) + assertEquals(0, count(connection, "SELECT COUNT(*) FROM invitecode_codes WHERE inviter_id = ?", inviter)) + assertEquals(1, count(connection, "SELECT COUNT(*) FROM invitecode_reward_actions WHERE recipient_id = ?", result.historicalId)) + assertEquals(0, count(connection, "SELECT COUNT(*) FROM invitecode_reward_actions WHERE idempotency_key LIKE ?", inviter)) + } + storage.savePlayer(io.github.command1264.invitecode.core.StoredPlayer(inviter, java.time.Instant.now(), "Returner")) + assertNotNull(storage.player(inviter)) + assertTrue(storage.invitationsByInviter(inviter).isEmpty()) + assertThrows(IllegalStateException::class.java) { + storage.atomically { transaction -> + transaction.activate(ActiveInviteCode(inviter, InviteCode.fromNormalized("A1B2C3"), Instant.now())) + } + } + } + SqliteInviteCodeStorage.open(database, guard).use { withoutKey -> + assertThrows(IllegalStateException::class.java) { + withoutKey.isInviteCodeReserved(InviteCode.fromNormalized("FFFFFF")) + } + } + assertThrows(IllegalStateException::class.java) { + SqliteInviteCodeStorage.open(database, guard, CodeReservationKey("c".repeat(64)) { "d".repeat(64) }) + } + } + + @Test + fun `unresolved reward fails before any identity mutation`() { + val database = directory.resolve("unresolved.db") + SqliteSchemaMigrator(database, guard).migrate() + val inviter = UUID.randomUUID() + val invitee = UUID.randomUUID() + val invitation = UUID.randomUUID() + seed(database, inviter, invitee, invitation, UUID.randomUUID(), UUID.randomUUID(), "PENDING") + SqliteInviteCodeStorage.open(database, guard, key).use { storage -> + assertThrows(IllegalStateException::class.java) { storage.anonymizePlayer(inviter) } + assertNotNull(storage.player(inviter)) + assertFalse(storage.isInviteCodeReserved(InviteCode.fromNormalized("FFFFFF"))) + assertNotNull(storage.activeInviteCode(InviteCode.fromNormalized("A1B2C3"))) + } + } + + @Test + fun `invitee anonymization keeps inviter code and severs old invitee UUID`() { + val database = directory.resolve("invitee.db") + SqliteSchemaMigrator(database, guard).migrate() + val inviter = UUID.randomUUID() + val invitee = UUID.randomUUID() + val invitation = UUID.randomUUID() + seed(database, inviter, invitee, invitation, UUID.randomUUID(), UUID.randomUUID(), "DELIVERED") + SqliteInviteCodeStorage.open(database, guard, key).use { storage -> + val result = storage.anonymizePlayer(invitee) + assertEquals(0, result.preview.retiredCodes) + assertEquals(result.historicalId, storage.invitation(invitation)?.inviteeId) + assertNull(storage.player(invitee)) + assertNotNull(storage.activeInviteCode(InviteCode.fromNormalized("A1B2C3"))) + assertNotNull(storage.player(inviter)) + } + } + + @Test + fun `unrelated free text containing original UUID rolls back the entire operation`() { + val database = directory.resolve("unrelated-text.db") + SqliteSchemaMigrator(database, guard).migrate() + val inviter = UUID.randomUUID() + val invitee = UUID.randomUUID() + seed(database, inviter, invitee, UUID.randomUUID(), UUID.randomUUID(), UUID.randomUUID(), "DELIVERED") + connect(database).use { connection -> + connection.prepareStatement(""" + INSERT INTO invitecode_audit_records(audit_id, action, actor, reason, occurred_at, player_id, details_kind) + VALUES (?, 'ELIGIBILITY_RESET', 'admin', ?, '2026-01-04T00:00:00Z', ?, 'NONE') + """).use { statement -> + statement.setString(1, UUID.randomUUID().toString()) + statement.setString(2, "mentions $inviter") + statement.setString(3, invitee.toString()) + statement.executeUpdate() + } + } + SqliteInviteCodeStorage.open(database, guard, key).use { storage -> + assertThrows(IllegalStateException::class.java) { storage.anonymizePlayer(inviter) } + assertNotNull(storage.player(inviter)) + assertNotNull(storage.activeInviteCode(InviteCode.fromNormalized("A1B2C3"))) + assertFalse(storage.isInviteCodeReserved(InviteCode.fromNormalized("FFFFFF"))) + } + } + + @Test + fun `administrator name in another player's audit is redacted`() { + val database = directory.resolve("admin-name.db") + SqliteSchemaMigrator(database, guard).migrate() + val inviter = UUID.randomUUID() + val invitee = UUID.randomUUID() + seed(database, inviter, invitee, UUID.randomUUID(), UUID.randomUUID(), UUID.randomUUID(), "DELIVERED") + val unrelatedDelivery = UUID.randomUUID() + val unrelatedAction = UUID.randomUUID() + connect(database).use { connection -> + connection.prepareStatement(""" + INSERT INTO invitecode_audit_records(audit_id, action, actor, reason, occurred_at, player_id, details_kind) + VALUES (?, 'ELIGIBILITY_RESET', 'Alice', 'Alice approved Bob', '2026-01-04T00:00:00Z', ?, 'NONE') + """).use { statement -> + statement.setString(1, UUID.randomUUID().toString()) + statement.setString(2, invitee.toString()) + statement.executeUpdate() + } + connection.prepareStatement(""" + INSERT INTO invitecode_reward_deliveries(delivery_id, reward_id, status, idempotency_key, created_at, updated_at) + VALUES (?, 'other', 'DELIVERED', ?, '2026-01-04T00:00:00Z', '2026-01-04T00:00:00Z') + """).use { statement -> + statement.setString(1, unrelatedDelivery.toString()) + statement.setString(2, "other:${unrelatedDelivery}") + statement.executeUpdate() + } + connection.prepareStatement(""" + INSERT INTO invitecode_reward_actions(action_id, reward_delivery_id, recipient_id, position, + action_type, payload, status, idempotency_key, created_at, updated_at) + VALUES (?, ?, ?, 0, 'MESSAGE', 'Hello Bob', 'DELIVERED', ?, '2026-01-04T00:00:00Z', '2026-01-04T00:00:00Z') + """).use { statement -> + statement.setString(1, unrelatedAction.toString()) + statement.setString(2, unrelatedDelivery.toString()) + statement.setString(3, invitee.toString()) + statement.setString(4, "other-action:${unrelatedAction}") + statement.executeUpdate() + } + connection.prepareStatement(""" + INSERT INTO invitecode_reward_action_transitions(action_id, previous_status, current_status, + occurred_at, actor, reason) + VALUES (?, 'PENDING', 'DELIVERED', '2026-01-04T00:00:00Z', 'Alice', 'Alice approved') + """).use { statement -> + statement.setString(1, unrelatedAction.toString()) + statement.executeUpdate() + } + } + SqliteInviteCodeStorage.open(database, guard, key).use { storage -> + storage.anonymizePlayer(inviter) + assertTrue(storage.auditHistoryByPlayer(invitee, 10).all { + !it.actor.contains("Alice") && !it.reason.contains("Alice") + }) + assertTrue(storage.rewardActionTransitions(unrelatedAction).all { + it.actor?.contains("Alice") != true && it.reason?.contains("Alice") != true + }) + } + } + + @Test + fun `another player's pending reward mentioning the name blocks anonymization`() { + val database = directory.resolve("other-reward.db") + SqliteSchemaMigrator(database, guard).migrate() + val inviter = UUID.randomUUID() + val invitee = UUID.randomUUID() + seed(database, inviter, invitee, UUID.randomUUID(), UUID.randomUUID(), UUID.randomUUID(), "DELIVERED") + val delivery = UUID.randomUUID() + connect(database).use { connection -> + connection.prepareStatement(""" + INSERT INTO invitecode_reward_deliveries(delivery_id, reward_id, status, idempotency_key, created_at, updated_at) + VALUES (?, 'other', 'PENDING', ?, '2026-01-04T00:00:00Z', '2026-01-04T00:00:00Z') + """).use { statement -> + statement.setString(1, delivery.toString()) + statement.setString(2, "other:$delivery") + statement.executeUpdate() + } + connection.prepareStatement(""" + INSERT INTO invitecode_reward_actions(action_id, reward_delivery_id, recipient_id, position, + action_type, payload, status, idempotency_key, created_at, updated_at) + VALUES (?, ?, ?, 0, 'MESSAGE', 'Hello Alice', 'PENDING', ?, '2026-01-04T00:00:00Z', '2026-01-04T00:00:00Z') + """).use { statement -> + statement.setString(1, UUID.randomUUID().toString()) + statement.setString(2, delivery.toString()) + statement.setString(3, invitee.toString()) + statement.setString(4, "other-action:$delivery") + statement.executeUpdate() + } + } + SqliteInviteCodeStorage.open(database, guard, key).use { storage -> + assertThrows(IllegalStateException::class.java) { storage.anonymizePlayer(inviter) } + assertNotNull(storage.player(inviter)) + assertNotNull(storage.activeInviteCode(InviteCode.fromNormalized("A1B2C3"))) + } + } + + private fun seed(db: Path, inviter: UUID, invitee: UUID, invitation: UUID, delivery: UUID, action: UUID, status: String) { + connect(db).use { connection -> + connection.createStatement().use { it.execute("PRAGMA foreign_keys = ON") } + fun insert(sql: String, vararg values: Any?) = connection.prepareStatement(sql).use { statement -> + values.forEachIndexed { index, value -> statement.setObject(index + 1, value) } + statement.executeUpdate() + } + listOf(inviter to "Alice", invitee to "Bob").forEach { (id, name) -> + insert("INSERT INTO invitecode_players(player_id, first_seen_at, last_known_name) VALUES (?, ?, ?)", + id.toString(), "2026-01-01T00:00:00Z", name) + } + insert("INSERT INTO invitecode_codes(code, inviter_id, activated_at) VALUES (?, ?, ?)", + "A1B2C3", inviter.toString(), "2026-01-01T00:00:00Z") + insert(""" + INSERT INTO invitecode_invitations(invitation_id, inviter_id, inviter_eligibility_generation, + invitee_id, invitee_eligibility_generation, status, claimed_at) + VALUES (?, ?, 0, ?, 0, 'CLAIMED', ?) + """, invitation.toString(), inviter.toString(), invitee.toString(), "2026-01-02T00:00:00Z") + insert(""" + INSERT INTO invitecode_reward_deliveries(delivery_id, invitation_id, reward_id, status, + idempotency_key, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?) + """, delivery.toString(), invitation.toString(), "reward-Alice", status, + "milestone:$inviter", "2026-01-03T00:00:00Z", "2026-01-03T00:00:00Z") + insert(""" + INSERT INTO invitecode_reward_actions(action_id, reward_delivery_id, invitation_id, recipient_id, + position, action_type, payload, status, idempotency_key, created_at, updated_at) + VALUES (?, ?, ?, ?, 0, 'MESSAGE', ?, ?, ?, ?, ?) + """, action.toString(), delivery.toString(), invitation.toString(), inviter.toString(), + "Hello Alice", status, "action:$inviter", "2026-01-03T00:00:00Z", "2026-01-03T00:00:00Z") + insert(""" + INSERT INTO invitecode_audit_records(audit_id, action, actor, reason, occurred_at, player_id, details_kind) + VALUES (?, 'ELIGIBILITY_RESET', ?, ?, ?, ?, 'NONE') + """, UUID.randomUUID().toString(), "Alice", "Request by $inviter", "2026-01-03T00:00:00Z", inviter.toString()) + insert("INSERT INTO invitecode_player_login_days(player_id, login_date) VALUES (?, ?)", inviter.toString(), "2026-01-01") + insert(""" + INSERT INTO invitecode_player_network_hashes(player_id, key_id, network_hash, observed_at, expires_at) + VALUES (?, ?, ?, ?, ?) + """, inviter.toString(), "a".repeat(64), "b".repeat(64), "2026-01-01T00:00:00Z", "2027-01-01T00:00:00Z") + } + } + + private fun count(connection: Connection, sql: String, id: UUID): Int = + connection.prepareStatement(sql).use { statement -> + statement.setString(1, id.toString()) + statement.executeQuery().use { rows -> rows.next(); rows.getInt(1) } + } +}