From 0bf2bfb2e26563429925ec3c1fc6fa5510b09bfb Mon Sep 17 00:00:00 2001 From: Command1264 Date: Wed, 23 Sep 2026 03:48:43 +0800 Subject: [PATCH 1/2] feat: add MySQL 8.4 storage backend --- .github/workflows/ci.yml | 28 ++ README.md | 85 +---- docs/README.zh-TW.md | 99 +++++ docs/adr/0003-explicit-storage-migration.md | 4 +- docs/operations/bukkit-workflow.md | 11 +- docs/operations/mysql-storage.md | 47 +++ .../invitecode/core/StorageConfiguration.kt | 33 +- .../core/StorageConfigurationTest.kt | 28 +- .../bukkit/InviteCodeTabCompletion.kt | 2 +- .../platform/bukkit/NetworkAddressHasher.kt | 14 + .../bukkit/NetworkAddressHasherTest.kt | 15 + .../RuntimeConfigurationAssemblerTest.kt | 8 +- invitecode-plugin/build.gradle.kts | 11 + .../invitecode/plugin/InviteCodePlugin.kt | 125 ++++--- .../plugin/MysqlRuntimeBootstrap.kt | 77 ++++ .../main/resources/config/messages/en_US.yml | 8 +- .../main/resources/config/messages/zh_TW.yml | 8 +- .../src/main/resources/config/storage.yml | 2 + .../plugin/MysqlRuntimeBootstrapTest.kt | 85 +++++ invitecode-storage-sql/build.gradle.kts | 3 + .../storage/sql/MysqlInviteCodeStorage.kt | 42 +++ .../storage/sql/MysqlSchemaMigrator.kt | 337 ++++++++++++++++++ .../storage/sql/MysqlStorageException.kt | 3 + .../invitecode/storage/sql/SqlDialect.kt | 14 + .../storage/sql/SqlStorageBackends.kt | 2 +- .../storage/sql/SqliteIdentityRecords.kt | 40 ++- .../storage/sql/SqliteInvitationRecords.kt | 10 +- .../storage/sql/SqliteInviteCodeStorage.kt | 102 +++++- .../storage/sql/SqliteRewardRecords.kt | 30 +- .../storage/sql/SqliteSchemaMigrator.kt | 2 +- .../resources/mysql/V1__initial_schema.sql | 185 ++++++++++ .../storage/sql/MysqlIntegrationTest.kt | 248 +++++++++++++ .../sql/SqliteInviteCodeStorageTest.kt | 2 +- .../storage/sql/StorageContractTest.kt | 66 ++++ 34 files changed, 1582 insertions(+), 194 deletions(-) create mode 100644 docs/README.zh-TW.md create mode 100644 docs/operations/mysql-storage.md create mode 100644 invitecode-plugin/src/main/kotlin/io/github/command1264/invitecode/plugin/MysqlRuntimeBootstrap.kt create mode 100644 invitecode-plugin/src/test/kotlin/io/github/command1264/invitecode/plugin/MysqlRuntimeBootstrapTest.kt create mode 100644 invitecode-storage-sql/src/main/kotlin/io/github/command1264/invitecode/storage/sql/MysqlInviteCodeStorage.kt create mode 100644 invitecode-storage-sql/src/main/kotlin/io/github/command1264/invitecode/storage/sql/MysqlSchemaMigrator.kt create mode 100644 invitecode-storage-sql/src/main/kotlin/io/github/command1264/invitecode/storage/sql/MysqlStorageException.kt create mode 100644 invitecode-storage-sql/src/main/kotlin/io/github/command1264/invitecode/storage/sql/SqlDialect.kt create mode 100644 invitecode-storage-sql/src/main/resources/mysql/V1__initial_schema.sql create mode 100644 invitecode-storage-sql/src/test/kotlin/io/github/command1264/invitecode/storage/sql/MysqlIntegrationTest.kt create mode 100644 invitecode-storage-sql/src/test/kotlin/io/github/command1264/invitecode/storage/sql/StorageContractTest.kt diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index fcf9d84..4fc10d9 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -34,3 +34,31 @@ jobs: - name: 在 Windows 驗證與封裝 if: runner.os == 'Windows' run: mise exec -- .\gradlew.bat --no-daemon check shadowJar + + mysql-integration: + runs-on: ubuntu-latest + services: + mysql: + image: mysql:8.4 + env: + MYSQL_ROOT_PASSWORD: ${{ github.run_id }} + MYSQL_ROOT_HOST: "%" + ports: + - 3306:3306 + options: >- + --health-cmd "mysqladmin ping -h 127.0.0.1 -u root" + --health-interval 10s + --health-timeout 5s + --health-retries 10 + env: + MISE_JAVA_VERSION: temurin-8.0.504+1 + INVITECODE_TEST_MYSQL_HOST: 127.0.0.1 + INVITECODE_TEST_MYSQL_PORT: "3306" + INVITECODE_TEST_MYSQL_USER: root + INVITECODE_TEST_MYSQL_PASSWORD: ${{ github.run_id }} + steps: + - uses: actions/checkout@v6 + - uses: jdx/mise-action@v4 + - uses: gradle/actions/setup-gradle@v4 + - name: 驗證 Java 8 與 MySQL 儲存契約 + run: mise exec -- ./gradlew --no-daemon :invitecode-storage-sql:test :invitecode-plugin:test diff --git a/README.md b/README.md index c560d1a..1d021d7 100644 --- a/README.md +++ b/README.md @@ -1,93 +1,30 @@ # InviteCode -InviteCode 是從零重寫的 Kotlin Minecraft 邀請與推薦獎勵插件;`InviteCodeKt` 是 repository 名稱,`Kt` 只表示實作使用 Kotlin。目標是以單一可安裝 JAR 支援 Spigot 與 Paper 1.8.8 到最新已測試版本,並透過隔離的 adapter 載入新版能力。 +InviteCode is a Kotlin invitation and referral rewards plugin for Spigot and Paper. `InviteCodeKt` is the repository name; the plugin and its data directory are named `InviteCode`. -> [!IMPORTANT] -> 這個 repository 目前是 `0.1.0-SNAPSHOT`。舊版相容的 Bukkit 指令、聊天輸入、SQLite lifecycle、Qualification、可復原 Reward Delivery 與新版原生 Dialog adapter 已完成串接;跨版本自動化 smoke 已建立,玩家實際操作與畫面呈現仍留待發行前真人驗收。 +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 implemented storage backends. The final player experience and cross-version server matrix 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), and [MySQL setup](docs/operations/mysql-storage.md). These documents are maintained in Traditional Chinese. -- 透過 Invite Code 建立一筆永久的 Inviter 與 Invitee 關係。 -- 將建立 Invitation 與達成獎勵資格分成不同階段。 -- 支援可設定的 Qualification Policy 與可復原的 Reward Delivery。 -- 支援 SQLite 與 MySQL;JSON 僅用於小型安裝環境與資料交換。 -- 在不使用 NMS 的前提下維持 Java 8 執行環境相容性。 -- 在有能力的新版伺服器使用原生 Dialog 輸入,其餘版本安全退回聊天或指令輸入。 +## Build -標準領域詞彙記錄於 [`CONTEXT.md`](./CONTEXT.md),已確認的產品與工程範圍記錄於 [`docs/spec/invitecode-1.0.md`](./docs/spec/invitecode-1.0.md)。 - -## 建置 - -需求: - -- 已安裝 [mise](https://mise.jdx.dev/) -- 第一次解析 dependency 時需要網路連線 - -本機開發透過 `mise.toml` 使用已登錄的 `java@local-11`。先確認 mise 可解析工具與實際 JDK: +Install [mise](https://mise.jdx.dev/) and use the repository's Gradle Wrapper. The project selects the locally registered `java@local-11` by default. Dependencies require network access on first resolution. ```powershell -mise where java +mise ls --current java +mise ls java mise exec -- java -version mise exec -- .\gradlew.bat check shadowJar ``` -驗證 Java 8 執行環境時,使用已登錄的 `java@local-8` 覆寫預設 JDK: +To verify the Java 8 runtime, use the already registered local JDK: ```powershell mise exec java@local-8 -- .\gradlew.bat clean check shadowJar ``` -`local-8` 與 `local-11` 由開發機的 mise 設定連結至既有 JDK。GitHub Actions 沒有這些本機 alias,因此 CI 透過 `MISE_JAVA_VERSION` 改用對應的 Temurin Java 8 與 Java 11。 - -可安裝的骨架 JAR 會輸出至: - -```text -invitecode-plugin/build/libs/InviteCode-0.1.0-SNAPSHOT.jar -``` - -所有本機 Java、Gradle 建置與測試指令都必須透過 `mise exec` 執行。Gradle Wrapper 仍由 repository 管理。建置流程會驗證目前 production class 使用 Java 8 bytecode。未來的新版 adapter 只有在 class 維持隔離,並驗證舊版 JVM 不會載入時,才可使用新版 bytecode。 - -## SQLite schema 與 thread 規則 - -`invitecode-storage-sql` 使用 `org.xerial:sqlite-jdbc:3.53.4.0`,driver 與主要平台的原生程式庫會封裝進單一插件 JAR。SQLite adapter 提供下列保證: - -- schema 只會由 `SqliteSchemaMigrator` 依版本順序明確遷移;開啟 storage 不會暗中修改 schema。 -- migration 在 transaction 內執行;失敗時回復原 schema version,並保留既有資料庫供檢查與重試;rollback 本身失敗時會回報狀態不確定,且不再切回 auto-commit。 -- Claim 使用 SQLite write transaction,且資料庫以 unique constraint 保證一名 Invitee 在每次 Claim Eligibility 世代最多只有一筆 Invitation;可稽核的 Eligibility Reset 會開始新世代並保留歷史資料。 -- Reward Delivery 與其完整 Reward Action 集合只能從 `PENDING` 開始,並以單一 transaction 建立或更新;狀態不一致或任一 Action 寫入失敗時整批回復。Delivery 與 Action 的狀態轉換會在同一 transaction 追加不可覆寫的歷史,Pending Action 可依收件玩家於重新登入或重啟後找回。 -- Reward Action 使用明確狀態轉換;重啟時會將中斷於 `PROCESSING` 的 Action 原子轉為 `UNCERTAIN`,之後只有記錄 actor 與 reason 的管理操作可決定重試或視為已交付。 -- 初始 Invitation 只能以 `CLAIMED` 保存;一般 qualification 必須將 Qualified Invitation 與相符的 Qualification Facts 原子保存,管理員變更則使用可稽核轉換。Qualified Invitation 會同時保存穩定的 Qualification Policy ID 與 revision;Qualification Fact 為不可變稽核事實,只接受內容完全相同的冪等重送。 -- 所有 SQLite 入口都要求 `BlockingOperationGuard`;Minecraft adapter 必須用它拒絕 server main thread,並在專用 executor 呼叫同步 storage interface。 -- storage 錯誤會拒絕當次操作,不會自動切換成 memory、JSON 或其他 backend。 - -SQLite persistence 具備暫存資料庫 contract tests,插件只在專用 executor 執行 blocking I/O。全新安裝會自動建立 SQLite schema 與所需密鑰;既有資料庫的 schema 更新仍須使用明確的 `admin storage migrate`。完整操作方式請參閱 [`docs/operations/bukkit-workflow.md`](./docs/operations/bukkit-workflow.md)。 - -Claim 防濫用只保存由 `anti-abuse.key` 產生、具期限的 HMAC-SHA-256 網路雜湊,不保存原始 IP;預設保留 30 天,並可設定相符時 `ALLOW`、`WARN` 或 `DENY`。密鑰由全新 SQLite 首次初始化建立,需隨 SQLite 備份且不得提交版本控制。 - -## Qualification Policy - -`QualificationPolicy` 使用 OR group 包含 AND condition;每次解析都會依正規化內容產生不可變的 SHA-256 revision。`QualificationEvaluator` 對 condition 依序短路求值,provider 缺失或執行失敗時安全地產生 `UNKNOWN`/設定的 `UNSATISFIED`,不會因此讓 Invitation qualified。 - -內建 provider 涵蓋遊玩時間、Claim 後經過時間、不同登入日數、管理員核准、permission 與 Placeholder 比較。Permission 與 Placeholder 值由平台 adapter 注入,核心不直接依賴 Bukkit 或 PlaceholderAPI。Qualification 通過時,Qualified Invitation 與造成通過的 facts 透過 storage transaction 原子保存;一般 reevaluation 不會反轉既有 qualification。 - -設定格式、condition 參數與外部 provider 契約請參閱 [`docs/configuration/qualifications.md`](./docs/configuration/qualifications.md)。Bukkit workflow 會收集遊玩時間、不同登入日、Permission 與 PlaceholderAPI 值,並定期重新評估;外部插件可由 Bukkit ServicesManager 取得 `InviteCodeApi`。 - -## Reward Delivery - -Qualification Reward 與 Inviter Milestone Reward 會先以穩定冪等鍵保存完整 Delivery/Action,再執行訊息、Console 指令、玩家指令或 Vault 經濟獎勵。玩家離線或 Vault integration 暫時不可用時維持 `PENDING`;外部結果無法判定時轉為 `UNCERTAIN`,只允許具稽核資訊的管理操作決定重試或視為已交付。 - -設定格式、placeholder、離線補發及失敗復原流程請參閱 [`docs/configuration/rewards.md`](./docs/configuration/rewards.md)。Bukkit workflow 已串接玩家登入補發、啟動復原、Vault Economy 與具 actor/reason 的人工處理指令。 - -## 分支 - -- `main`:穩定發行基線與 GitHub 預設分支 -- `develop`:日常整合分支 -- task branch:使用獨立 Worktree,目標分支為 `develop` - -## 真實伺服器測試 - -專案的真實 Spigot/Paper/Folia 測試矩陣位於 [`test-servers/matrix.json`](./test-servers/matrix.json),並使用專案外的共用 TestLab 建立隔離實例。操作方式與 EULA 邊界請參閱 [`docs/testing/test-servers.md`](./docs/testing/test-servers.md)。 +The installable artifact is `invitecode-plugin/build/libs/InviteCode-0.1.0-SNAPSHOT.jar`. The build checks Java 8 class files and bundled driver entries. CI also runs MySQL 8.4 integration tests with an isolated service. -## 目前狀態 +## Development branches -實作工作記錄於本 repository 的 GitHub Issues。不規劃相容或匯入舊版 InviteCode 的資料與設定。 +`develop` is the daily integration branch and the local main checkout. Feature work uses separate worktrees and targets `develop`. `main` remains the stable release baseline and GitHub default branch. diff --git a/docs/README.zh-TW.md b/docs/README.zh-TW.md new file mode 100644 index 0000000..4bba184 --- /dev/null +++ b/docs/README.zh-TW.md @@ -0,0 +1,99 @@ +# InviteCode + +本文件為 InviteCode 的主要繁體中文維護者說明;精簡英文介紹請見 [`README.md`](../README.md)。 + +InviteCode 是從零重寫的 Kotlin Minecraft 邀請與推薦獎勵插件;`InviteCodeKt` 是 repository 名稱,`Kt` 只表示實作使用 Kotlin。目標是以單一可安裝 JAR 支援 Spigot 與 Paper 1.8.8 到最新已測試版本,並透過隔離的 adapter 載入新版能力。 + +> [!IMPORTANT] +> 這個 repository 目前是 `0.1.0-SNAPSHOT`。舊版相容的 Bukkit 指令、聊天輸入、SQLite lifecycle、Qualification、可復原 Reward Delivery 與新版原生 Dialog adapter 已完成串接;跨版本自動化 smoke 已建立,玩家實際操作與畫面呈現仍留待發行前真人驗收。 + +## 專案目標 + +- 透過 Invite Code 建立一筆永久的 Inviter 與 Invitee 關係。 +- 將建立 Invitation 與達成獎勵資格分成不同階段。 +- 支援可設定的 Qualification Policy 與可復原的 Reward Delivery。 +- 已實作 SQLite 與 MySQL 8.4;JSON 仍是後續規劃。 +- 在不使用 NMS 的前提下維持 Java 8 執行環境相容性。 +- 在有能力的新版伺服器使用原生 Dialog 輸入,其餘版本安全退回聊天或指令輸入。 + +標準領域詞彙記錄於 [`CONTEXT.md`](../CONTEXT.md),已確認的產品與工程範圍記錄於 [`invitecode-1.0.md`](./spec/invitecode-1.0.md)。 + +## 建置 + +需求: + +- 已安裝 [mise](https://mise.jdx.dev/) +- 第一次解析 dependency 時需要網路連線 + +本機開發透過 `mise.toml` 使用已登錄的 `java@local-11`。先確認 mise 可解析工具與實際 JDK: + +```powershell +mise where java +mise ls --current java +mise ls java +mise exec -- java -version +mise exec -- .\gradlew.bat check shadowJar +``` + +驗證 Java 8 執行環境時,使用已登錄的 `java@local-8` 覆寫預設 JDK: + +```powershell +mise exec java@local-8 -- .\gradlew.bat clean check shadowJar +``` + +`local-8` 與 `local-11` 由開發機的 mise 設定連結至既有 JDK。GitHub Actions 沒有這些本機 alias,因此 CI 透過 `MISE_JAVA_VERSION` 改用對應的 Temurin Java 8 與 Java 11。 + +可安裝的骨架 JAR 會輸出至: + +```text +invitecode-plugin/build/libs/InviteCode-0.1.0-SNAPSHOT.jar +``` + +所有本機 Java、Gradle 建置與測試指令都必須透過 `mise exec` 執行。Gradle Wrapper 仍由 repository 管理。建置流程會驗證目前 production class 使用 Java 8 bytecode。未來的新版 adapter 只有在 class 維持隔離,並驗證舊版 JVM 不會載入時,才可使用新版 bytecode。 + +## SQLite schema 與 thread 規則 + +`invitecode-storage-sql` 使用 `org.xerial:sqlite-jdbc:3.53.4.0`,driver 與主要平台的原生程式庫會封裝進單一插件 JAR。SQLite adapter 提供下列保證: + +- schema 只會由 `SqliteSchemaMigrator` 依版本順序明確遷移;開啟 storage 不會暗中修改 schema。 +- migration 在 transaction 內執行;失敗時回復原 schema version,並保留既有資料庫供檢查與重試;rollback 本身失敗時會回報狀態不確定,且不再切回 auto-commit。 +- Claim 使用 SQLite write transaction,且資料庫以 unique constraint 保證一名 Invitee 在每次 Claim Eligibility 世代最多只有一筆 Invitation;可稽核的 Eligibility Reset 會開始新世代並保留歷史資料。 +- Reward Delivery 與其完整 Reward Action 集合只能從 `PENDING` 開始,並以單一 transaction 建立或更新;狀態不一致或任一 Action 寫入失敗時整批回復。Delivery 與 Action 的狀態轉換會在同一 transaction 追加不可覆寫的歷史,Pending Action 可依收件玩家於重新登入或重啟後找回。 +- Reward Action 使用明確狀態轉換;重啟時會將中斷於 `PROCESSING` 的 Action 原子轉為 `UNCERTAIN`,之後只有記錄 actor 與 reason 的管理操作可決定重試或視為已交付。 +- 初始 Invitation 只能以 `CLAIMED` 保存;一般 qualification 必須將 Qualified Invitation 與相符的 Qualification Facts 原子保存,管理員變更則使用可稽核轉換。Qualified Invitation 會同時保存穩定的 Qualification Policy ID 與 revision;Qualification Fact 為不可變稽核事實,只接受內容完全相同的冪等重送。 +- 所有 SQLite 入口都要求 `BlockingOperationGuard`;Minecraft adapter 必須用它拒絕 server main thread,並在專用 executor 呼叫同步 storage interface。 +- storage 錯誤會拒絕當次操作,不會自動切換成 memory、JSON 或其他 backend。 + +SQLite persistence 具備暫存資料庫 contract tests,插件只在專用 executor 執行 blocking I/O。全新安裝會自動建立 SQLite schema 與所需密鑰;既有資料庫的 schema 更新仍須使用明確的 `admin storage migrate`。完整操作方式請參閱 [`bukkit-workflow.md`](./operations/bukkit-workflow.md)。 + +MySQL 8.4 使用共用外部 HMAC 密鑰、連線池及具 checksum 與中斷復原檢查的 migration ledger。資料庫須先存在,全新的空白 database 會在插件啟動時自動建表;多個插件實例必須使用同一個密鑰。設定與復原方式請見 [`mysql-storage.md`](./operations/mysql-storage.md)。 + +Claim 防濫用只保存具期限的 HMAC-SHA-256 網路雜湊,不保存原始 IP;預設保留 30 天,並可設定相符時 `ALLOW`、`WARN` 或 `DENY`。SQLite 的 `anti-abuse.key` 由首次初始化建立,需隨 SQLite 備份且不得提交版本控制;MySQL 則使用所有實例共用的外部密鑰。 + +## Qualification Policy + +`QualificationPolicy` 使用 OR group 包含 AND condition;每次解析都會依正規化內容產生不可變的 SHA-256 revision。`QualificationEvaluator` 對 condition 依序短路求值,provider 缺失或執行失敗時安全地產生 `UNKNOWN`/設定的 `UNSATISFIED`,不會因此讓 Invitation qualified。 + +內建 provider 涵蓋遊玩時間、Claim 後經過時間、不同登入日數、管理員核准、permission 與 Placeholder 比較。Permission 與 Placeholder 值由平台 adapter 注入,核心不直接依賴 Bukkit 或 PlaceholderAPI。Qualification 通過時,Qualified Invitation 與造成通過的 facts 透過 storage transaction 原子保存;一般 reevaluation 不會反轉既有 qualification。 + +設定格式、condition 參數與外部 provider 契約請參閱 [`qualifications.md`](./configuration/qualifications.md)。Bukkit workflow 會收集遊玩時間、不同登入日、Permission 與 PlaceholderAPI 值,並定期重新評估;外部插件可由 Bukkit ServicesManager 取得 `InviteCodeApi`。 + +## Reward Delivery + +Qualification Reward 與 Inviter Milestone Reward 會先以穩定冪等鍵保存完整 Delivery/Action,再執行訊息、Console 指令、玩家指令或 Vault 經濟獎勵。玩家離線或 Vault integration 暫時不可用時維持 `PENDING`;外部結果無法判定時轉為 `UNCERTAIN`,只允許具稽核資訊的管理操作決定重試或視為已交付。 + +設定格式、placeholder、離線補發及失敗復原流程請參閱 [`rewards.md`](./configuration/rewards.md)。Bukkit workflow 已串接玩家登入補發、啟動復原、Vault Economy 與具 actor/reason 的人工處理指令。 + +## 分支 + +- `main`:穩定發行基線與 GitHub 預設分支 +- `develop`:日常整合分支 +- task branch:使用獨立 Worktree,目標分支為 `develop` + +## 真實伺服器測試 + +專案的真實 Spigot/Paper/Folia 測試矩陣位於 [`test-servers/matrix.json`](../test-servers/matrix.json),並使用專案外的共用 TestLab 建立隔離實例。操作方式與 EULA 邊界請參閱 [`test-servers.md`](./testing/test-servers.md)。 + +## 目前狀態 + +實作工作記錄於本 repository 的 GitHub Issues。不規劃相容或匯入舊版 InviteCode 的資料與設定。 diff --git a/docs/adr/0003-explicit-storage-migration.md b/docs/adr/0003-explicit-storage-migration.md index c4afdb3..ac971d8 100644 --- a/docs/adr/0003-explicit-storage-migration.md +++ b/docs/adr/0003-explicit-storage-migration.md @@ -1,5 +1,7 @@ # 全新 Storage 自動初始化,既有資料只透過明確遷移流程變更 -SQLite 與 MySQL 是 production backend;JSON 僅用於小型安裝環境與資料交換。選定 backend 尚未存在任何資料時,插件會在首次啟動自動建立該 backend 所需的 schema、metadata 與本機 secret,讓全新安裝可直接使用。自動初始化失敗時只清理由該次嘗試建立、尚未承載使用者資料的檔案,並進入可診斷的安全失敗狀態。 +SQLite 與 MySQL 是 production backend;JSON 僅用於小型安裝環境與資料交換。選定 backend 尚未存在任何資料時,插件會在首次啟動自動建立該 backend 所需的 schema 與 metadata,讓全新安裝可直接使用。SQLite 同時建立本機 secret。MySQL 的 database 須預先建立,防濫用 secret 須由管理員透過環境變數提供並由所有實例共用;插件只在 MySQL 保存其識別碼,不自行產生或儲存密鑰。自動初始化失敗時只清理由該次嘗試建立、尚未承載使用者資料的檔案,並進入可診斷的安全失敗狀態。 既有 backend 的 schema 升級、backend 切換與資料搬移不得在一般啟動或 reload 過程自動執行。這些操作必須使用明確的 preflight、migration、verification 與 cutover 流程;失敗時保留來源資料,避免在未察覺的情況下改寫資料或產生兩份各自寫入的資料。檔案或連線存在即視為既有 backend,不因內容異常而退回全新初始化。 + +MySQL 的建表 DDL 會獨立提交,不能倚賴 transaction 回滾。首次初始化中斷後,只有 migration ledger 仍為 `APPLYING`、checksum 相符且既有表結構通過檢查時,才可在下次啟動續建;否則保留資料並進入維護模式。已標為 `APPLIED` 的 schema 不會在一般啟動時套用新版本 migration。 diff --git a/docs/operations/bukkit-workflow.md b/docs/operations/bukkit-workflow.md index 181a901..7c6f5bd 100644 --- a/docs/operations/bukkit-workflow.md +++ b/docs/operations/bukkit-workflow.md @@ -1,6 +1,6 @@ # Bukkit 操作與維護 -本文件說明 InviteCode 在 Spigot/Paper 上的玩家流程、管理指令、SQLite 初始化、維護模式與人工驗收方式。Issue #10 使用 SQLite;選擇 `MYSQL` 或 `JSON` 會明確拒絕啟動,不會自動退回其他儲存方式。 +本文件說明 InviteCode 在 Spigot/Paper 上的玩家流程、管理指令、儲存初始化、維護模式與人工驗收方式。可選擇 `SQLITE` 或 `MYSQL`;`JSON` 尚未實作。MySQL 的設定與復原細節見 [`mysql-storage.md`](./mysql-storage.md)。 ## 首次啟動 @@ -10,6 +10,8 @@ `/invitecode admin storage migrate SQLITE ` 保留給既有 SQLite schema 升級與人工復原。`doctor` 不會建立資料庫或執行 migration。 +選擇 MySQL 時,管理員須先建立空白 database 並設定連線與共用防濫用密鑰的環境變數。插件首次啟動會建立 MySQL schema;既有 schema 不會自動升級。中斷於首次建表的 migration 只有在既有表結構通過檢查後才會續跑。明確遷移指令為 `/invitecode admin storage migrate MYSQL `。 + 維護模式只允許 `help`、`admin doctor` 與 `admin storage migrate`。設定錯誤須修正檔案並重新啟動;正常模式可用 `/invitecode reload` 驗證所有 YAML 後原子替換設定快照。`/invitecode admin reload` 保留為相容路徑。 ## 玩家指令 @@ -31,7 +33,7 @@ Tab 建議會依發送者身分、權限與當前參數位置篩選。已完成 聊天輸入會先取消公開聊天,再送入背景流程;原始訊息不會寫入 log。Dialog 提交後沿用同一組格式、資格與限時確認流程;取消按鈕、`/invitecode cancel`、登出或逾時只會清除短期 Session,不會建立或修改 Invitation。輸入、確認、逾時、成功、取消、登出或停用插件後,短期 Session 都會失效。玩家一旦建立 Invite Code、已有 Invitation,或超過 Claim Window,就不能使用他人的 Invite Code。 -玩家登入時,插件會以 `anti-abuse.key` 對正規化網路位址執行 HMAC-SHA-256,SQLite 只保存雜湊、密鑰識別碼與觀察/到期時間,絕不保存原始 IP。`anti-abuse.ip-hash-retention` 預設為 30 天;到期資料會在玩家登入時清除。邀請人與受邀人有尚未到期的相同雜湊時,`matching-ip-action` 的行為如下: +玩家登入時,插件會以 SQLite 的 `anti-abuse.key` 或 MySQL 多實例共用的外部密鑰,對正規化網路位址執行 HMAC-SHA-256。資料庫只保存雜湊、密鑰識別碼與觀察/到期時間,絕不保存原始 IP。`anti-abuse.ip-hash-retention` 預設為 30 天;到期資料會在玩家登入時清除。邀請人與受邀人有尚未到期的相同雜湊時,`matching-ip-action` 的行為如下: | 值 | 行為 | | --- | --- | @@ -59,13 +61,14 @@ Tab 建議會依發送者身分、權限與當前參數位置篩選。已完成 /invitecode admin reward mark-delivered /invitecode admin code rotate <玩家> /invitecode admin storage migrate SQLITE +/invitecode admin storage migrate MYSQL /invitecode reload /invitecode admin doctor ``` `/invitecode admin reload` 仍可使用,但說明與 Tab 建議以較直接的 `/invitecode reload` 為主。 -Invitation、Eligibility、Code Rotation 與 Storage Migration 會留下 actor、reason 與 Audit Record;Reward 的人工決定會留下 Reward transition。`retry` 與 `mark-delivered` 只接受 `UNCERTAIN` Action。Force Qualification 會在同一 SQLite transaction 保存 Qualification、Audit Record 與完整 Reward plans。 +Invitation、Eligibility、Code Rotation 與 Storage Migration 會留下 actor、reason 與 Audit Record;Reward 的人工決定會留下 Reward transition。`retry` 與 `mark-delivered` 只接受 `UNCERTAIN` Action。Force Qualification 會在同一儲存 transaction 保存 Qualification、Audit Record 與完整 Reward plans。 ## Qualification 與 Reward 復原 @@ -73,7 +76,7 @@ Invitation、Eligibility、Code Rotation 與 Storage Migration 會留下 actor 玩家登入會補發自己的 `PENDING` Reward。玩家離線或 Vault Economy 不可用時維持 `PENDING`。插件啟動會先把上次中斷於 `PROCESSING` 的 Action 轉成 `UNCERTAIN`;這類外部結果不得自動重試,必須由管理員檢查後決定。 -背景 executor 執行 SQLite 與 Qualification/Reward orchestration;Bukkit、聊天、指令、訊息與 Vault 操作只在 server main thread 執行。停用時會停止接受新工作並有界等待,不會讓背景執行緒同步等待主執行緒。 +背景 executor 執行 SQLite/MySQL 與 Qualification/Reward orchestration;Bukkit、聊天、指令、訊息與 Vault 操作只在 server main thread 執行。停用時會停止接受新工作並有界等待,不會讓背景執行緒同步等待主執行緒。 ## 人工驗收 diff --git a/docs/operations/mysql-storage.md b/docs/operations/mysql-storage.md new file mode 100644 index 0000000..36eec73 --- /dev/null +++ b/docs/operations/mysql-storage.md @@ -0,0 +1,47 @@ +# MySQL 8.4 儲存設定與復原 + +InviteCode 的 MySQL backend 目前以 MySQL 8.4 LTS 為正式驗證目標。MariaDB 尚未列入相容性承諾。插件會在已存在、完全空白的 database 首次啟動時自行建立 schema;database 本身與專用帳號須先由管理員建立。本功能不搬移 SQLite 資料,也不會在 reload 時切換 backend。 + +## 準備 database 與設定 + +先在 MySQL 8.4 建立專用的空白 database 與帳號,並授予這個 database 所需的建表與讀寫權限。不要讓插件連到已有其他用途資料的 database。`plugins/InviteCode/storage.yml` 的預設檔案位於 JAR 的 `config/storage.yml`;將 `backend` 改為 `MYSQL` 並設定下列值: + +```yaml +config-version: 1 +backend: MYSQL + +sqlite: + file: invitecode.db + +mysql: + host: db.example.net + port: 3306 + database: invitecode + username: invitecode + password: "${INVITECODE_DB_PASSWORD}" + network-secret: "${INVITECODE_NETWORK_SECRET}" + connection-timeout: 5s + tls-mode: VERIFY_IDENTITY +``` + +`password` 與 `network-secret` 只接受 `${ENV_VAR}` 格式。啟動 Minecraft 伺服器前,必須在其程序環境中設定兩個變數;找不到變數會在連線前拒絕啟動。`INVITECODE_NETWORK_SECRET` 是 32 bytes 隨機資料的 Base64 字串,同一個 MySQL database 的所有插件實例必須使用完全相同的值。PowerShell 7 可在伺服器啟動腳本中產生一次,再由安全的設定管理方式保存並分發: + +```powershell +$env:INVITECODE_NETWORK_SECRET = [Convert]::ToBase64String( + [Security.Cryptography.RandomNumberGenerator]::GetBytes(32) +) +``` + +上例每執行一次都會產生不同密鑰。正式使用時只產生一次,將其與 MySQL 備份一起安全保存;不得每次開機重新產生、寫入 Git、貼到 Issue 或輸出到 log。MySQL 只保存密鑰的 SHA-256 識別碼,不保存密鑰本體;新實例的密鑰不一致時會拒絕啟動。MySQL 模式不使用本機 `anti-abuse.key`。 + +`tls-mode: VERIFY_IDENTITY` 是預設值,要求 TLS 並驗證伺服器憑證與 host 名稱。憑證必須由 JVM 信任,必要時在 Minecraft 伺服器的 Java 啟動參數設定 trust store。`VERIFY_CA` 驗證憑證鏈但不驗證 host 名稱;`REQUIRED` 僅加密連線、不驗證伺服器身分,適用於受控的本機測試。設定變更後須重新啟動,不會熱切換連線池。`connection-timeout` 可設 250ms 至 60s;連線池耗盡或 MySQL 不可用時,當次操作會在有限時間內失敗。 + +## 初始化與復原 + +新 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 同時收集正式玩家資料後直接改回設定。 + +## 驗證 + +獨立測試使用隨機命名的 `invitecode_test_*` database,測試結束後只清理該次建立的 database;不會連線到未指定的服務。CI 的 MySQL 8.4 service 執行共用 storage contract、中斷續跑、資料結構遭修改的拒絕、兩個連線池競爭 Claim、密鑰不一致、連線池耗盡及連線失敗測試。本機要執行同一批測試時,先在隔離 MySQL 8.4 設定 `INVITECODE_TEST_MYSQL_HOST`、`INVITECODE_TEST_MYSQL_PORT`、`INVITECODE_TEST_MYSQL_USER` 與 `INVITECODE_TEST_MYSQL_PASSWORD`,再依 [`README.md`](../../README.md) 使用 mise 與 Gradle Wrapper 執行 `check`。 diff --git a/invitecode-core/src/main/kotlin/io/github/command1264/invitecode/core/StorageConfiguration.kt b/invitecode-core/src/main/kotlin/io/github/command1264/invitecode/core/StorageConfiguration.kt index f7ae601..397cb1f 100644 --- a/invitecode-core/src/main/kotlin/io/github/command1264/invitecode/core/StorageConfiguration.kt +++ b/invitecode-core/src/main/kotlin/io/github/command1264/invitecode/core/StorageConfiguration.kt @@ -9,6 +9,12 @@ enum class StorageBackendType { JSON, } +enum class MysqlTlsMode { + VERIFY_IDENTITY, + VERIFY_CA, + REQUIRED, +} + data class SqliteConfiguration(val file: String) { init { require(file.isNotBlank()) { "SQLite file must not be blank." } @@ -32,18 +38,29 @@ data class MysqlConfiguration( val database: String, val username: String, val passwordReference: String, + val networkSecretReference: String, val connectionTimeout: Duration, + val tlsMode: MysqlTlsMode = MysqlTlsMode.VERIFY_IDENTITY, ) { init { - require(host.isNotBlank()) { "MySQL host must not be blank." } + require(HOST.matches(host)) { "MySQL host must be a hostname or IPv4 address without URL parameters." } require(port in 1..65535) { "MySQL port must be between 1 and 65535." } - require(database.isNotBlank()) { "MySQL database must not be blank." } + require(DATABASE.matches(database)) { "MySQL database must contain only letters, digits and underscores." } require(username.isNotBlank()) { "MySQL username must not be blank." } - require(passwordReference.isNotBlank()) { "MySQL password reference must not be blank." } - require(!connectionTimeout.isZero && !connectionTimeout.isNegative) { - "MySQL connection timeout must be greater than zero." + require(ENV_REFERENCE.matches(passwordReference)) { "MySQL password must be an environment variable reference." } + require(ENV_REFERENCE.matches(networkSecretReference)) { + "MySQL network secret must be an environment variable reference." + } + require(connectionTimeout.toMillis() in 250..60_000) { + "MySQL connection timeout must be between 250ms and 60s." } } + + companion object { + private val ENV_REFERENCE = Regex("\\$\\{[A-Za-z_][A-Za-z0-9_]*}") + private val HOST = Regex("[A-Za-z0-9][A-Za-z0-9.-]*") + private val DATABASE = Regex("[A-Za-z0-9_]+") + } } data class StorageConfiguration( @@ -53,7 +70,7 @@ data class StorageConfiguration( val mysql: MysqlConfiguration, ) { fun requireSupportedBackend(): StorageConfiguration { - if (backend != StorageBackendType.SQLITE) { + if (backend == StorageBackendType.JSON) { throw UnsupportedStorageBackendException(backend) } return this @@ -91,10 +108,12 @@ object StorageConfigurationParser { database = mysql.requiredString("database", "mysql"), username = mysql.requiredString("username", "mysql"), passwordReference = mysql.requiredString("password", "mysql"), + networkSecretReference = mysql.requiredString("network-secret", "mysql"), connectionTimeout = parsePositiveDuration( mysql.requiredString("connection-timeout", "mysql"), "mysql.connection-timeout", ), + tlsMode = mysql.requiredEnum("tls-mode", "mysql"), ), ) } @@ -158,7 +177,9 @@ object StorageConfigurationParser { "database", "username", "password", + "network-secret", "connection-timeout", + "tls-mode", ) private val SHORT_DURATION = Regex("^(\\d+)(ms|s|m|h|d)$") } diff --git a/invitecode-core/src/test/kotlin/io/github/command1264/invitecode/core/StorageConfigurationTest.kt b/invitecode-core/src/test/kotlin/io/github/command1264/invitecode/core/StorageConfigurationTest.kt index 8230784..b5e68d7 100644 --- a/invitecode-core/src/test/kotlin/io/github/command1264/invitecode/core/StorageConfigurationTest.kt +++ b/invitecode-core/src/test/kotlin/io/github/command1264/invitecode/core/StorageConfigurationTest.kt @@ -15,6 +15,7 @@ class StorageConfigurationTest { assertEquals(3306, configuration.mysql.port) assertEquals(Duration.ofSeconds(5), configuration.mysql.connectionTimeout) assertEquals("${'$'}{INVITECODE_DB_PASSWORD}", configuration.mysql.passwordReference) + assertEquals(MysqlTlsMode.VERIFY_IDENTITY, configuration.mysql.tlsMode) } @Test @@ -26,13 +27,34 @@ class StorageConfigurationTest { } @Test - fun `marks unfinished backends unsupported`() { - assertThrows { + fun `supports MySQL and rejects unfinished JSON`() { + assertEquals( + StorageBackendType.MYSQL, StorageConfigurationParser.parse(validConfiguration().toMutableMap().apply { put("backend", "MYSQL") }) + .requireSupportedBackend().backend, + ) + assertThrows { + StorageConfigurationParser.parse(validConfiguration().toMutableMap().apply { put("backend", "JSON") }) .requireSupportedBackend() } } + @Test + fun `MySQL config rejects literal credentials and URL injection`() { + fun withMysql(changed: Map): Map = validConfiguration().toMutableMap().apply { + put("mysql", (get("mysql") as Map) + changed) + } + assertThrows { + StorageConfigurationParser.parse(withMysql(mapOf("password" to "plaintext"))) + } + assertThrows { + StorageConfigurationParser.parse(withMysql(mapOf("host" to "localhost/?allowPublicKeyRetrieval=true"))) + } + assertThrows { + StorageConfigurationParser.parse(withMysql(mapOf("tls-mode" to "DISABLED"))) + } + } + private fun validConfiguration(): Map = mapOf( "config-version" to 1, "backend" to "SQLITE", @@ -43,7 +65,9 @@ class StorageConfigurationTest { "database" to "invitecode", "username" to "invitecode", "password" to "${'$'}{INVITECODE_DB_PASSWORD}", + "network-secret" to "${'$'}{INVITECODE_NETWORK_SECRET}", "connection-timeout" to "5s", + "tls-mode" to "VERIFY_IDENTITY", ), ) } diff --git a/invitecode-platform-bukkit/src/main/kotlin/io/github/command1264/invitecode/platform/bukkit/InviteCodeTabCompletion.kt b/invitecode-platform-bukkit/src/main/kotlin/io/github/command1264/invitecode/platform/bukkit/InviteCodeTabCompletion.kt index b48bbb2..f7d2e43 100644 --- a/invitecode-platform-bukkit/src/main/kotlin/io/github/command1264/invitecode/platform/bukkit/InviteCodeTabCompletion.kt +++ b/invitecode-platform-bukkit/src/main/kotlin/io/github/command1264/invitecode/platform/bukkit/InviteCodeTabCompletion.kt @@ -55,7 +55,7 @@ object InviteCodeTabCompletion { listOf("admin", "code", "rotate") -> permitted(hasPermission, "invitecode.admin.code", onlinePlayerNames) listOf("admin", "storage", "migrate") -> - permitted(hasPermission, "invitecode.admin.storage", listOf("SQLITE")) + permitted(hasPermission, "invitecode.admin.storage", listOf("SQLITE", "MYSQL")) else -> emptyList() } return candidates 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 520961e..1300f0b 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.util.Base64 import java.util.concurrent.atomic.AtomicBoolean import javax.crypto.Mac import javax.crypto.spec.SecretKeySpec @@ -49,6 +50,19 @@ class NetworkAddressHasher private constructor( private const val IPV4_SIZE = 4 private const val IPV6_SIZE = 16 + fun fromBase64(encoded: String): NetworkAddressHasher { + val bytes = try { + Base64.getDecoder().decode(encoded) + } catch (error: IllegalArgumentException) { + throw IllegalArgumentException("Network secret must be Base64 encoded.", error) + } + return try { + NetworkAddressHasher(bytes) + } finally { + bytes.fill(0) + } + } + fun loadExisting(path: Path): NetworkAddressHasher { require(Files.isRegularFile(path)) { "Network hash secret ${path.toAbsolutePath()} is missing; run the explicit storage migration." 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 2a655f0..72af7a6 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 @@ -3,9 +3,11 @@ package io.github.command1264.invitecode.platform.bukkit import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertNotEquals import org.junit.jupiter.api.Test +import org.junit.jupiter.api.assertThrows import org.junit.jupiter.api.io.TempDir import java.nio.file.Files import java.nio.file.Path +import java.util.Base64 class NetworkAddressHasherTest { @TempDir @@ -35,4 +37,17 @@ class NetworkAddressHasherTest { assertEquals(it.hash(ipv4), it.hash(mapped)) } } + + @Test + fun `shared Base64 secret yields the same digest and rejects invalid length`() { + val secret = Base64.getEncoder().encodeToString(ByteArray(32) { it.toByte() }) + val address = byteArrayOf(192.toByte(), 0, 2, 10) + val first = NetworkAddressHasher.fromBase64(secret).use { it.keyId to it.hash(address) } + val second = NetworkAddressHasher.fromBase64(secret).use { it.keyId to it.hash(address) } + assertEquals(first, second) + assertThrows { NetworkAddressHasher.fromBase64("not-base64") } + assertThrows { + NetworkAddressHasher.fromBase64(Base64.getEncoder().encodeToString(ByteArray(16))) + } + } } diff --git a/invitecode-platform-bukkit/src/test/kotlin/io/github/command1264/invitecode/platform/bukkit/RuntimeConfigurationAssemblerTest.kt b/invitecode-platform-bukkit/src/test/kotlin/io/github/command1264/invitecode/platform/bukkit/RuntimeConfigurationAssemblerTest.kt index dac6ff5..5e3be7e 100644 --- a/invitecode-platform-bukkit/src/test/kotlin/io/github/command1264/invitecode/platform/bukkit/RuntimeConfigurationAssemblerTest.kt +++ b/invitecode-platform-bukkit/src/test/kotlin/io/github/command1264/invitecode/platform/bukkit/RuntimeConfigurationAssemblerTest.kt @@ -46,11 +46,11 @@ class RuntimeConfigurationAssemblerTest { @Test fun `unsupported configured backend fails before snapshot installation`() { - val mysql = storage().toMutableMap().apply { this["backend"] = "MYSQL" } + val json = storage().toMutableMap().apply { this["backend"] = "JSON" } assertThrows(IllegalStateException::class.java) { RuntimeConfigurationAssembler.parse( - general(), mysql, qualifications(), rewards(), mapOf("zh_TW" to catalog("訊息")), + general(), json, qualifications(), rewards(), mapOf("zh_TW" to catalog("訊息")), ) } } @@ -98,8 +98,10 @@ class RuntimeConfigurationAssemblerTest { "port" to 3306, "database" to "invitecode", "username" to "invitecode", - "password" to "env:INVITECODE_DB_PASSWORD", + "password" to "${'$'}{INVITECODE_DB_PASSWORD}", + "network-secret" to "${'$'}{INVITECODE_NETWORK_SECRET}", "connection-timeout" to "5s", + "tls-mode" to "VERIFY_IDENTITY", ), ) diff --git a/invitecode-plugin/build.gradle.kts b/invitecode-plugin/build.gradle.kts index 28d64ca..5e8378b 100644 --- a/invitecode-plugin/build.gradle.kts +++ b/invitecode-plugin/build.gradle.kts @@ -54,6 +54,12 @@ abstract class VerifyPluginJar : DefaultTask() { "plugin.yml must declare the oldest supported modern API version" } + val drivers = zip.getInputStream(requireNotNull(zip.getEntry("META-INF/services/java.sql.Driver"))) + .bufferedReader(Charsets.UTF_8).use { it.readLines().map(String::trim).toSet() } + check(drivers.containsAll(setOf("org.sqlite.JDBC", "com.mysql.cj.jdbc.Driver"))) { + "Plugin JAR must register both SQLite and MySQL JDBC drivers" + } + val entries = zip.entries() while (entries.hasMoreElements()) { val entry = entries.nextElement() @@ -91,6 +97,7 @@ dependencies { implementation(project(":invitecode-core")) implementation(project(":invitecode-storage-json")) implementation(project(":invitecode-storage-sql")) + implementation("com.zaxxer:HikariCP:4.0.3") implementation(project(":invitecode-platform-bukkit")) implementation(project(":invitecode-platform-modern")) compileOnly("org.spigotmc:spigot-api:1.8.8-R0.1-SNAPSHOT") @@ -141,6 +148,10 @@ val verifyPluginJar by tasks.registering(VerifyPluginJar::class) { "config/messages/en_US.yml", "io/github/command1264/invitecode/plugin/InviteCodePlugin.class", "org/sqlite/JDBC.class", + "com/mysql/cj/jdbc/Driver.class", + "com/zaxxer/hikari/HikariDataSource.class", + "org/slf4j/impl/JDK14LoggerFactory.class", + "mysql/V1__initial_schema.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 5b2448f..c83d49c 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 @@ -1,6 +1,7 @@ package io.github.command1264.invitecode.plugin import io.github.command1264.invitecode.core.InviteCodeStorage +import io.github.command1264.invitecode.core.StorageBackendType import io.github.command1264.invitecode.core.AuditRecord import io.github.command1264.invitecode.core.InvitationAuditAction import io.github.command1264.invitecode.core.RewardDeliveryCoordinator @@ -23,6 +24,7 @@ import io.github.command1264.invitecode.platform.modern.ModernPlatformIntegratio 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 io.github.command1264.invitecode.storage.sql.MysqlSchemaMigrator import org.bukkit.Bukkit import org.bukkit.command.Command import org.bukkit.command.CommandExecutor @@ -146,7 +148,7 @@ class InviteCodePlugin : JavaPlugin() { ) } if (result.storageInitialized) { - logger.info("已自動完成首次 SQLite schema 與防濫用密鑰初始化。") + logger.info("已自動完成首次 ${result.configuration?.storage?.backend} schema 與防濫用密鑰初始化。") } server.onlinePlayers.forEach { playerWorkflows?.registerPlayer(it) } logger.info("InviteCode ${description.version} 已啟用。") @@ -175,22 +177,33 @@ class InviteCodePlugin : JavaPlugin() { var opened: InviteCodeStorage? = null var hasher: NetworkAddressHasher? = null return try { - val dataDirectory = dataFolder.toPath().normalize() - val database = dataDirectory.resolve(candidate.storage.sqlite.file).normalize() - require(database.startsWith(dataDirectory)) { "SQLite database path escapes the plugin data directory." } - val bootstrap = SqliteRuntimeBootstrap( - database, - dataDirectory.resolve(NETWORK_SECRET_FILE), - BlockingOperationGuard.rejectingServerMainThread(Bukkit::isPrimaryThread), - ).initializeOrOpen() - opened = bootstrap.storage - hasher = bootstrap.networkHasher + val guard = BlockingOperationGuard.rejectingServerMainThread(Bukkit::isPrimaryThread) + val initialized = when (candidate.storage.backend) { + StorageBackendType.SQLITE -> { + val dataDirectory = dataFolder.toPath().normalize() + val database = dataDirectory.resolve(candidate.storage.sqlite.file).normalize() + require(database.startsWith(dataDirectory)) { "SQLite database path escapes the plugin data directory." } + val bootstrap = SqliteRuntimeBootstrap( + database, dataDirectory.resolve(NETWORK_SECRET_FILE), guard, + ).initializeOrOpen() + opened = bootstrap.storage + hasher = bootstrap.networkHasher + bootstrap.initialized + } + StorageBackendType.MYSQL -> { + val bootstrap = MysqlRuntimeBootstrap(candidate.storage.mysql, guard).initializeOrOpen() + opened = bootstrap.storage + hasher = bootstrap.networkHasher + bootstrap.initialized + } + StorageBackendType.JSON -> error("JSON storage is not implemented.") + } val recovered = RewardDeliveryCoordinator(opened).recoverInterrupted(Instant.now()) StartupResult( configuration = candidate, storage = opened, networkHasher = hasher, - storageInitialized = bootstrap.initialized, + storageInitialized = initialized, recoveredRewardActions = recovered, ) } catch (error: Exception) { @@ -230,15 +243,16 @@ class InviteCodePlugin : JavaPlugin() { } private fun migrateStorage(sender: CommandSender, request: ParsedInviteCodeCommand) { - if (!request.operands.single().equals("SQLITE", ignoreCase = true)) { - sendLocalized(sender, "admin.storage-unsupported") - return - } val candidate = configuration.currentOrNull()?.value if (candidate == null) { sendLocalized(sender, "admin.storage-config-unavailable") return } + val target = request.operands.single().uppercase(java.util.Locale.ROOT) + if (target != candidate.storage.backend.name || target == "JSON") { + sendLocalized(sender, "admin.storage-unsupported") + return + } val executor = operations if (executor == null) { sendLocalized(sender, "admin.storage-stopping") @@ -248,38 +262,47 @@ class InviteCodePlugin : JavaPlugin() { val reason = requireNotNull(request.reason) val accepted = executor.submit( operation = { - val dataDirectory = dataFolder.toPath().normalize() - val database = dataDirectory.resolve(candidate.storage.sqlite.file).normalize() - require(database.startsWith(dataDirectory)) { - "SQLite database path escapes the plugin data directory." - } val guard = BlockingOperationGuard.rejectingServerMainThread(Bukkit::isPrimaryThread) - val version = SqliteSchemaMigrator(database, guard).migrate() - val opened = SqliteInviteCodeStorage.open(database, guard) - var newHasher: NetworkAddressHasher? = null - try { - val loadedHasher = networkHasher.get() - newHasher = if (loadedHasher == null) { - NetworkAddressHasher.loadOrCreate(dataDirectory.resolve(NETWORK_SECRET_FILE)) - } else { - null + when (candidate.storage.backend) { + StorageBackendType.SQLITE -> { + val dataDirectory = dataFolder.toPath().normalize() + val database = dataDirectory.resolve(candidate.storage.sqlite.file).normalize() + require(database.startsWith(dataDirectory)) { + "SQLite database path escapes the plugin data directory." + } + val version = SqliteSchemaMigrator(database, guard).migrate() + val opened = SqliteInviteCodeStorage.open(database, guard) + var newHasher: NetworkAddressHasher? = 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) + opened.saveAuditRecord(AuditRecord(UUID.randomUUID(), InvitationAuditAction.STORAGE_MIGRATED, actor, reason, Instant.now())) + StorageMigrationResult(version, opened, newHasher) + } catch (error: Exception) { + newHasher?.close() + opened.close() + throw error + } + } + StorageBackendType.MYSQL -> { + val bootstrap = MysqlRuntimeBootstrap( + candidate.storage.mysql, guard, explicitMigration = true, + ).initializeOrOpen() + try { + bootstrap.storage.saveAuditRecord( + AuditRecord(UUID.randomUUID(), InvitationAuditAction.STORAGE_MIGRATED, actor, reason, Instant.now()), + ) + StorageMigrationResult(MysqlSchemaMigrator.CURRENT_VERSION, bootstrap.storage, bootstrap.networkHasher) + } catch (error: Exception) { + bootstrap.storage.close() + bootstrap.networkHasher.close() + throw error + } } - val effectiveHasher = loadedHasher ?: requireNotNull(newHasher) - opened.purgeNetworkHashesWithDifferentKey(effectiveHasher.keyId) - opened.saveAuditRecord( - AuditRecord( - UUID.randomUUID(), - InvitationAuditAction.STORAGE_MIGRATED, - actor, - reason, - Instant.now(), - ), - ) - StorageMigrationResult(version, opened, newHasher) - } catch (error: Exception) { - newHasher?.close() - opened.close() - throw error + StorageBackendType.JSON -> error("JSON storage is not implemented.") } }, onSuccess = { result -> @@ -289,12 +312,12 @@ class InviteCodePlugin : JavaPlugin() { } if (runtime.phase == RuntimePhase.MAINTENANCE) runtime.activate() server.onlinePlayers.forEach { playerWorkflows?.registerPlayer(it) } - logger.info("$actor 以理由「$reason」完成 SQLite schema migration 至版本 ${result.version}。") + logger.info("$actor 以理由「$reason」完成 $target schema migration 至版本 ${result.version}。") sendLocalized(sender, "admin.storage-success", mapOf("version" to result.version.toString())) }, onFailure = { error -> sendLocalized(sender, "admin.storage-failed") - logger.log(Level.SEVERE, "$actor 執行 SQLite schema migration 失敗;理由:$reason", error) + logger.log(Level.SEVERE, "$actor 執行 $target schema migration 失敗;理由:$reason", error) }, ) if (!accepted) sendLocalized(sender, "admin.storage-stopping") @@ -340,7 +363,11 @@ class InviteCodePlugin : JavaPlugin() { sender, "admin.doctor-storage", mapOf( - "schema" to SqliteSchemaMigrator.currentVersion.toString(), + "schema" to when (configuration.current().value.storage.backend) { + StorageBackendType.SQLITE -> SqliteSchemaMigrator.currentVersion.toString() + StorageBackendType.MYSQL -> MysqlSchemaMigrator.CURRENT_VERSION.toString() + StorageBackendType.JSON -> "N/A" + }, "pending" to backlog.pending.toString(), "processing" to backlog.processing.toString(), "uncertain" to backlog.uncertain.toString(), 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 new file mode 100644 index 0000000..049e2b8 --- /dev/null +++ b/invitecode-plugin/src/main/kotlin/io/github/command1264/invitecode/plugin/MysqlRuntimeBootstrap.kt @@ -0,0 +1,77 @@ +package io.github.command1264.invitecode.plugin + +import io.github.command1264.invitecode.core.AuditRecord +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.MysqlInviteCodeStorage +import io.github.command1264.invitecode.storage.sql.MysqlSchemaMigrator +import io.github.command1264.invitecode.storage.sql.MysqlStorageException +import java.time.Instant +import java.sql.SQLException +import java.util.UUID + +internal data class MysqlBootstrapResult( + val storage: MysqlInviteCodeStorage, + val networkHasher: NetworkAddressHasher, + val initialized: Boolean, +) + +internal class MysqlRuntimeBootstrap( + private val config: MysqlConfiguration, + private val guard: BlockingOperationGuard, + private val environment: (String) -> String? = System::getenv, + private val now: () -> Instant = Instant::now, + private val explicitMigration: Boolean = false, +) { + fun initializeOrOpen(): MysqlBootstrapResult { + guard.checkAllowed() + val password = resolve(config.passwordReference, "mysql.password") + val secret = resolve(config.networkSecretReference, "mysql.network-secret") + val hasher = NetworkAddressHasher.fromBase64(secret) + var storage: MysqlInviteCodeStorage? = null + val pool = try { + MysqlInviteCodeStorage.createPool(config, password) + } catch (error: Exception) { + hasher.close() + throw error + } + try { + val initializedBefore = pool.connection.use(MysqlSchemaMigrator::isInitialized) + if (initializedBefore && !explicitMigration) { + pool.connection.use(MysqlSchemaMigrator::requireCurrent) + } else { + MysqlSchemaMigrator(pool, guard).migrate() + } + pool.connection.use { connection -> MysqlSchemaMigrator.bindNetworkKey(connection, hasher.keyId) } + storage = MysqlInviteCodeStorage.open(pool, guard) + if (!initializedBefore) { + storage.saveAuditRecord( + AuditRecord( + UUID.randomUUID(), InvitationAuditAction.STORAGE_MIGRATED, + "system", "automatic first MySQL initialization", now(), + ), + ) + } + return MysqlBootstrapResult(storage, hasher, !initializedBefore) + } catch (error: Exception) { + storage?.close() ?: pool.close() + hasher.close() + if (error is MysqlStorageException) throw error + val diagnostic = if (error is SQLException) { + "SQLState ${error.sqlState ?: "unknown"}, code ${error.errorCode}" + } else error.javaClass.simpleName + throw MysqlStorageException( + "MySQL initialization failed at ${config.host}:${config.port}/${config.database}; " + + "check connectivity, schema and shared network secret ($diagnostic).", + ) + } + } + + private fun resolve(reference: String, field: String): String { + val name = reference.substring(2, reference.length - 1) + return environment(name)?.takeIf(String::isNotEmpty) + ?: throw IllegalArgumentException("$field environment variable $name is missing or empty.") + } +} diff --git a/invitecode-plugin/src/main/resources/config/messages/en_US.yml b/invitecode-plugin/src/main/resources/config/messages/en_US.yml index 80894de..82cfdf7 100644 --- a/invitecode-plugin/src/main/resources/config/messages/en_US.yml +++ b/invitecode-plugin/src/main/resources/config/messages/en_US.yml @@ -60,11 +60,11 @@ admin: reload-success: "InviteCode validated and applied the complete configuration snapshot." reload-storage-restart: "storage.yml changes were not applied. Complete an explicit cutover and restart." reload-failed: "Configuration validation failed. The previous snapshot remains active; check the server log." - storage-unsupported: "This version can migrate only SQLITE storage." - storage-config-unavailable: "Configuration is not loaded, so the SQLite path is unavailable." + storage-unsupported: "The migration target must match the configured SQLITE or MYSQL backend." + storage-config-unavailable: "Configuration is not loaded, so the storage location is unavailable." storage-stopping: "InviteCode is stopping and cannot run the migration." - storage-success: "SQLite schema migration completed at version {version}." - storage-failed: "SQLite schema migration failed. Check the server log." + storage-success: "Storage schema migration completed at version {version}." + storage-failed: "Storage schema migration failed. Check the server log." doctor-runtime: "Runtime={phase}, configuration generation={generation}, executor={executor}." doctor-integrations: "Integrations: PlaceholderAPI={placeholder}, Vault Economy={vault}, Dialog={dialog}, RGB={rgb}." doctor-maintenance: "Maintenance reason: {reason}" diff --git a/invitecode-plugin/src/main/resources/config/messages/zh_TW.yml b/invitecode-plugin/src/main/resources/config/messages/zh_TW.yml index 4b95a85..5f7668e 100644 --- a/invitecode-plugin/src/main/resources/config/messages/zh_TW.yml +++ b/invitecode-plugin/src/main/resources/config/messages/zh_TW.yml @@ -60,11 +60,11 @@ admin: reload-success: "InviteCode 設定已完整驗證並套用。" reload-storage-restart: "storage.yml 的變更尚未套用;請完成明確 cutover 並重新啟動。" reload-failed: "設定驗證失敗,仍保留上一份有效設定;請查看伺服器紀錄。" - storage-unsupported: "目前版本只支援遷移 SQLITE 儲存。" - storage-config-unavailable: "設定尚未成功載入,無法判定 SQLite 位置。" + storage-unsupported: "遷移目標必須與目前設定的 SQLITE 或 MYSQL backend 相同。" + storage-config-unavailable: "設定尚未成功載入,無法判定儲存位置。" storage-stopping: "InviteCode 正在停止,無法執行 migration。" - storage-success: "SQLite schema migration 已完成,目前版本為 {version}。" - storage-failed: "SQLite schema migration 失敗,請查看伺服器紀錄。" + storage-success: "Storage schema migration 已完成,目前版本為 {version}。" + storage-failed: "Storage schema migration 失敗,請查看伺服器紀錄。" doctor-runtime: "Runtime={phase},設定世代={generation},executor={executor}。" doctor-integrations: "Integration:PlaceholderAPI={placeholder},Vault Economy={vault},Dialog={dialog},RGB={rgb}。" doctor-maintenance: "維護原因:{reason}" diff --git a/invitecode-plugin/src/main/resources/config/storage.yml b/invitecode-plugin/src/main/resources/config/storage.yml index cdaf3b6..c48e847 100644 --- a/invitecode-plugin/src/main/resources/config/storage.yml +++ b/invitecode-plugin/src/main/resources/config/storage.yml @@ -10,4 +10,6 @@ mysql: database: invitecode username: invitecode password: "${INVITECODE_DB_PASSWORD}" + network-secret: "${INVITECODE_NETWORK_SECRET}" connection-timeout: 5s + tls-mode: VERIFY_IDENTITY diff --git a/invitecode-plugin/src/test/kotlin/io/github/command1264/invitecode/plugin/MysqlRuntimeBootstrapTest.kt b/invitecode-plugin/src/test/kotlin/io/github/command1264/invitecode/plugin/MysqlRuntimeBootstrapTest.kt new file mode 100644 index 0000000..bd16b88 --- /dev/null +++ b/invitecode-plugin/src/test/kotlin/io/github/command1264/invitecode/plugin/MysqlRuntimeBootstrapTest.kt @@ -0,0 +1,85 @@ +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.storage.sql.BlockingOperationGuard +import io.github.command1264.invitecode.storage.sql.MysqlStorageException +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertThrows +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.Assumptions.assumeTrue +import java.sql.DriverManager +import java.time.Duration +import java.util.Base64 +import java.util.UUID + +class MysqlRuntimeBootstrapTest { + @Test + fun `first startup initializes and later startup uses the same database and shared key`() { + val host = System.getenv("INVITECODE_TEST_MYSQL_HOST") + val password = System.getenv("INVITECODE_TEST_MYSQL_PASSWORD") + assumeTrue(!host.isNullOrBlank() && !password.isNullOrBlank()) + val port = System.getenv("INVITECODE_TEST_MYSQL_PORT")?.toIntOrNull() ?: 3306 + val user = System.getenv("INVITECODE_TEST_MYSQL_USER") ?: "root" + val schema = "invitecode_test_${UUID.randomUUID().toString().replace("-", "")}" + check(Regex("invitecode_test_[0-9a-f]{32}").matches(schema)) + val url = "jdbc:mysql://$host:$port/?sslMode=REQUIRED&connectionTimeZone=UTC" + DriverManager.getConnection(url, user, password).use { connection -> + connection.createStatement().use { it.execute("CREATE DATABASE $schema") } + } + try { + val config = MysqlConfiguration( + host, port, schema, user, "${'$'}{DB_PASSWORD}", "${'$'}{NETWORK_SECRET}", Duration.ofSeconds(5), + MysqlTlsMode.REQUIRED, + ) + val secret = Base64.getEncoder().encodeToString(ByteArray(32) { (it + 1).toByte() }) + val environment: (String) -> String? = { name -> + when (name) { + "DB_PASSWORD" -> password + "NETWORK_SECRET" -> secret + else -> null + } + } + val guard = BlockingOperationGuard { } + val first = MysqlRuntimeBootstrap(config, guard, environment).initializeOrOpen() + try { + assertEquals(true, first.initialized) + val reopened = MysqlRuntimeBootstrap(config, guard, environment).initializeOrOpen() + try { + assertEquals(false, reopened.initialized) + assertEquals(first.networkHasher.keyId, reopened.networkHasher.keyId) + } finally { + reopened.storage.close() + reopened.networkHasher.close() + } + assertThrows(MysqlStorageException::class.java) { + MysqlRuntimeBootstrap(config, guard, environment = { name -> + if (name == "DB_PASSWORD") password else Base64.getEncoder() + .encodeToString(ByteArray(32) { 7 }) + }).initializeOrOpen() + } + } finally { + first.storage.close() + first.networkHasher.close() + } + } finally { + DriverManager.getConnection(url, user, password).use { connection -> + connection.createStatement().use { it.execute("DROP DATABASE $schema") } + } + } + } + + @Test + fun `missing secret fails before connecting to MySQL`() { + val config = MysqlConfiguration( + "localhost", 3306, "invitecode_test", "test", + "${'$'}{DB_PASSWORD}", "${'$'}{NETWORK_SECRET}", Duration.ofSeconds(1), + ) + val error = assertThrows(IllegalArgumentException::class.java) { + MysqlRuntimeBootstrap(config, BlockingOperationGuard { }, environment = { name -> + if (name == "DB_PASSWORD") "dummy" else null + }).initializeOrOpen() + } + assertEquals(true, error.message.orEmpty().contains("NETWORK_SECRET")) + } +} diff --git a/invitecode-storage-sql/build.gradle.kts b/invitecode-storage-sql/build.gradle.kts index 16542c0..93a8777 100644 --- a/invitecode-storage-sql/build.gradle.kts +++ b/invitecode-storage-sql/build.gradle.kts @@ -3,4 +3,7 @@ description = "Shared SQLite and MySQL storage contracts and migrations." dependencies { implementation(project(":invitecode-core")) implementation("org.xerial:sqlite-jdbc:3.53.4.0") + implementation("com.mysql:mysql-connector-j:26.7.0") + implementation("com.zaxxer:HikariCP:4.0.3") + implementation("org.slf4j:slf4j-jdk14:1.7.36") } 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 new file mode 100644 index 0000000..d4e36a1 --- /dev/null +++ b/invitecode-storage-sql/src/main/kotlin/io/github/command1264/invitecode/storage/sql/MysqlInviteCodeStorage.kt @@ -0,0 +1,42 @@ +package io.github.command1264.invitecode.storage.sql + +import com.zaxxer.hikari.HikariConfig +import com.zaxxer.hikari.HikariDataSource +import io.github.command1264.invitecode.core.InviteCodeStorage +import io.github.command1264.invitecode.core.MysqlConfiguration + +class MysqlInviteCodeStorage private constructor( + private val pool: HikariDataSource, + private val delegate: JdbcInviteCodeStorage, +) : InviteCodeStorage by delegate { + override fun close() = pool.close() + + companion object { + fun open(pool: HikariDataSource, guard: BlockingOperationGuard): MysqlInviteCodeStorage = + MysqlInviteCodeStorage(pool, JdbcInviteCodeStorage.openMysql(pool, guard)) + + fun createPool(config: MysqlConfiguration, password: String): HikariDataSource { + val hikari = HikariConfig().apply { + jdbcUrl = "jdbc:mysql://${config.host}:${config.port}/${config.database}" + + "?sslMode=${config.tlsMode.name}&connectionTimeZone=UTC" + username = config.username + this.password = password + driverClassName = "com.mysql.cj.jdbc.Driver" + poolName = "InviteCode-MySQL" + maximumPoolSize = 8 + minimumIdle = 0 + connectionTimeout = config.connectionTimeout.toMillis() + validationTimeout = minOf(config.connectionTimeout.toMillis(), 5_000L) + initializationFailTimeout = config.connectionTimeout.toMillis() + } + try { + return HikariDataSource(hikari) + } catch (error: Exception) { + throw MysqlStorageException( + "MySQL connection pool could not start at ${config.host}:${config.port}/${config.database}; " + + "check server availability, TLS and credentials.", + ) + } + } + } +} 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 new file mode 100644 index 0000000..58b87de --- /dev/null +++ b/invitecode-storage-sql/src/main/kotlin/io/github/command1264/invitecode/storage/sql/MysqlSchemaMigrator.kt @@ -0,0 +1,337 @@ +package io.github.command1264.invitecode.storage.sql + +import java.nio.charset.StandardCharsets +import java.security.MessageDigest +import java.sql.Connection +import java.sql.SQLException +import java.util.Locale +import javax.sql.DataSource + +/** MySQL DDL commits independently. The ledger stays APPLYING until every table is verified. */ +class MysqlSchemaMigrator( + private val dataSource: DataSource, + private val guard: BlockingOperationGuard, + private val afterTable: (String) -> Unit = {}, +) { + fun migrate(): Int { + guard.checkAllowed() + try { + dataSource.connection.use { connection -> + val schema = schemaName(connection) + val lockName = "invitecode:" + sha256(schema).take(40) + val acquired = connection.prepareStatement("SELECT GET_LOCK(?, 10)").use { statement -> + statement.setString(1, lockName) + statement.executeQuery().use { result -> result.next() && result.getInt(1) == 1 } + } + if (!acquired) throw MysqlStorageException("MySQL schema lock timed out; retry when other plugin instances finish migration.") + try { + migrateLocked(connection, schema) + } finally { + connection.prepareStatement("SELECT RELEASE_LOCK(?)").use { statement -> + statement.setString(1, lockName) + statement.executeQuery().close() + } + } + } + return CURRENT_VERSION + } catch (error: SQLException) { + throw MysqlStorageException( + "MySQL schema migration failed (SQLState ${error.sqlState ?: "unknown"}, code ${error.errorCode}); " + + "inspect the database before retrying. No secret was logged.", + ) + } + } + + private fun migrateLocked(connection: Connection, schema: String) { + val ledgerExists = tableExists(connection, schema, LEDGER) + if (!ledgerExists) { + val existing = connection.metaData.getTables(schema, null, "%", arrayOf("TABLE", "VIEW")).use { rows -> + rows.next() + } + if (existing) throw MysqlStorageException( + "MySQL database is not empty and has no migration ledger; preserve the database and inspect it manually.", + ) + 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 -> + rows.next() + rows.getInt(1) + } + } + if (otherVersions != 0) throw MysqlStorageException( + "MySQL schema contains another version; a separate explicit migration is required.", + ) + val state = connection.prepareStatement( + "SELECT checksum, state FROM $LEDGER WHERE version = ?", + ).use { statement -> + statement.setInt(1, CURRENT_VERSION) + statement.executeQuery().use { rows -> + if (rows.next()) rows.getString(1) to rows.getString(2) else null + } + } + if (state == null) { + 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.setString(2, CHECKSUM) + statement.executeUpdate() + } + } else { + if (state.first != CHECKSUM) throw MysqlStorageException( + "MySQL schema checksum differs from the bundled migration; preserve the database and inspect manually.", + ) + if (state.second !in setOf("APPLYING", "APPLIED")) throw MysqlStorageException( + "MySQL schema ledger has unknown state ${state.second}; preserve the database.", + ) + } + TABLES.forEach { table -> + if (!tableExists(connection, schema, table.name)) { + if (state?.second == "APPLIED") throw MysqlStorageException("MySQL table ${table.name} is missing; preserve the database.") + connection.createStatement().use { statement -> statement.execute(table.ddl) } + afterTable(table.name) + } + verifyTable(connection, schema, table) + } + if (state?.second != "APPLIED") { + connection.prepareStatement("UPDATE $LEDGER SET state = 'APPLIED' WHERE version = ? AND state = 'APPLYING'").use { + it.setInt(1, CURRENT_VERSION) + check(it.executeUpdate() == 1) { "MySQL schema ledger changed during migration." } + } + } + } + + companion object { + const val CURRENT_VERSION = 1 + private const val LEDGER = "invitecode_schema_migrations" + private const val LEDGER_DDL = """ + CREATE TABLE invitecode_schema_migrations ( + version INT NOT NULL PRIMARY KEY, + checksum CHAR(64) CHARACTER SET ascii COLLATE ascii_bin NOT NULL, + state VARCHAR(16) CHARACTER SET ascii NOT NULL + ) ENGINE=InnoDB + """ + private val RESOURCE = requireNotNull(MysqlSchemaMigrator::class.java.getResource("/mysql/V1__initial_schema.sql")) { + "Bundled MySQL schema resource is missing." + }.readText(StandardCharsets.UTF_8) + private val TABLES = Regex("(?m)^-- @table ([a-z_]+)\\s*$") + .findAll(RESOURCE).toList().mapIndexed { index, match -> + val next = Regex("(?m)^-- @table ([a-z_]+)\\s*$").find(RESOURCE, match.range.last + 1) + val ddl = RESOURCE.substring(match.range.last + 1, next?.range?.first ?: RESOURCE.length).trim() + .removeSuffix(";") + check(index == 0 || ddl.isNotBlank()) { "Empty MySQL schema statement." } + TableDefinition(match.groupValues[1], ddl) + } + private val CHECKSUM = sha256(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.executeQuery().use { rows -> rows.next() && rows.getString(1) == "APPLIED" } + } + } + + fun requireCurrent(connection: Connection) { + val schema = schemaName(connection) + if (!tableExists(connection, schema, LEDGER)) throw MysqlStorageException( + "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 -> + rows.next() + rows.getInt(1) + } + } + if (otherVersions != 0) throw MysqlStorageException( + "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.executeQuery().use { rows -> + if (rows.next()) rows.getString(1) to rows.getString(2) else null + } + } + if (row != (CHECKSUM to "APPLIED")) throw MysqlStorageException( + "MySQL schema version/checksum is not current; run explicit storage migration after inspecting the database.", + ) + TABLES.forEach { verifyTable(connection, schema, it) } + } + + fun bindNetworkKey(connection: Connection, keyId: String) { + require(Regex("[0-9a-f]{64}").matches(keyId)) { "Network key ID is invalid." } + connection.prepareStatement( + "INSERT IGNORE INTO invitecode_metadata(singleton, network_key_id) VALUES (1, ?)", + ).use { statement -> + statement.setString(1, keyId) + statement.executeUpdate() + } + val stored = connection.createStatement().use { statement -> + statement.executeQuery("SELECT network_key_id FROM invitecode_metadata WHERE singleton = 1").use { rows -> + check(rows.next()) { "MySQL network key metadata is missing." } + rows.getString(1) + } + } + if (stored != keyId) throw MysqlStorageException( + "MySQL network secret differs from the key used by another plugin instance; use the shared secret.", + ) + } + + private fun schemaName(connection: Connection): String = connection.createStatement().use { statement -> + statement.executeQuery("SELECT DATABASE()").use { rows -> + check(rows.next()) { "MySQL did not return a database name." } + requireNotNull(rows.getString(1)) { "MySQL connection must select an existing database." } + } + } + + private fun tableExists(connection: Connection, schema: String, name: String): Boolean = + connection.metaData.getTables(schema, null, name, arrayOf("TABLE")).use { it.next() } + + private fun verifyTable(connection: Connection, schema: String, table: TableDefinition) { + val expected = Regex( + "(?m)^ ([a-z_]+) (CHAR|VARCHAR|TEXT|INT|BIGINT)(?:\\((\\d+)\\))? (.*)$", + RegexOption.IGNORE_CASE, + ).findAll(table.ddl).associate { match -> + match.groupValues[1] to ColumnShape( + match.groupValues[2].uppercase(Locale.ROOT), + match.groupValues[3].toIntOrNull(), + "NOT NULL" !in match.groupValues[4].uppercase(Locale.ROOT), + when { + "COLLATE ascii_bin" in match.groupValues[4] -> "ascii_bin" + "COLLATE utf8mb4_bin" in match.groupValues[4] -> "utf8mb4_bin" + else -> null + }, + ) + } + val actual = connection.metaData.getColumns(schema, null, table.name, null).use { rows -> + buildMap { + while (rows.next()) put( + rows.getString("COLUMN_NAME"), + ColumnShape( + rows.getString("TYPE_NAME").uppercase(Locale.ROOT), + rows.getInt("COLUMN_SIZE"), + rows.getInt("NULLABLE") != 0, + null, + ), + ) + } + } + if (actual.keys != expected.keys || expected.any { (name, shape) -> + val found = actual[name] + found == null || found.type != shape.type || found.nullable != shape.nullable || + (shape.length != null && found.length != shape.length) + }) { + throw MysqlStorageException("MySQL table ${table.name} has unexpected columns; preserve the database and inspect manually.") + } + val collations = connection.prepareStatement( + "SELECT COLUMN_NAME, COLLATION_NAME FROM information_schema.COLUMNS " + + "WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ?", + ).use { statement -> + statement.setString(1, schema) + statement.setString(2, table.name) + statement.executeQuery().use { rows -> + buildMap { while (rows.next()) put(rows.getString(1), rows.getString(2)) } + } + } + if (expected.any { (name, shape) -> shape.collation != null && collations[name] != shape.collation }) { + throw MysqlStorageException("MySQL table ${table.name} has an unsafe collation; preserve the database.") + } + val generated = Regex("(?m)^ ([a-z_]+) [^\\r\\n]*(?:\\r?\\n [^\\r\\n]*)?GENERATED ALWAYS AS") + .findAll(table.ddl).map { it.groupValues[1] }.toSet() + if (generated.isNotEmpty()) { + val actualGenerated = connection.prepareStatement( + "SELECT COLUMN_NAME, EXTRA, GENERATION_EXPRESSION FROM information_schema.COLUMNS " + + "WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ? AND EXTRA LIKE '%STORED GENERATED%'", + ).use { statement -> + statement.setString(1, schema) + statement.setString(2, table.name) + statement.executeQuery().use { rows -> + buildMap { while (rows.next()) put(rows.getString(1), rows.getString(3)) } + } + } + if (actualGenerated.keys != generated || actualGenerated.values.any(String::isNullOrBlank)) { + throw MysqlStorageException("MySQL table ${table.name} has unexpected generated columns; preserve the database.") + } + } + val indexes = connection.metaData.getIndexInfo(schema, null, table.name, false, false).use { rows -> + val columns = mutableMapOf>>() + val unique = mutableMapOf() + while (rows.next()) { + val name = rows.getString("INDEX_NAME") ?: continue + val column = rows.getString("COLUMN_NAME") ?: continue + columns.getOrPut(name) { mutableListOf() }.add(rows.getInt("ORDINAL_POSITION") to column) + unique[name] = !rows.getBoolean("NON_UNIQUE") + } + columns.mapValues { (name, values) -> + IndexShape(values.sortedBy { it.first }.map { it.second }, unique.getValue(name)) + } + } + val requiredIndexes = Regex("(?m)^ (UNIQUE )?KEY ([a-z_]+) \\(([^)]+)\\)") + .findAll(table.ddl).associate { match -> + match.groupValues[2] to IndexShape( + match.groupValues[3].split(',').map(String::trim), + match.groupValues[1].isNotEmpty(), + ) + } + val primary = Regex("(?m)^ PRIMARY KEY \\(([^)]+)\\)").find(table.ddl)?.groupValues?.get(1) + ?.split(',')?.map(String::trim) + if (primary == null || indexes["PRIMARY"] != IndexShape(primary, true) || + requiredIndexes.any { (name, shape) -> indexes[name] != shape }) { + throw MysqlStorageException("MySQL table ${table.name} has unexpected indexes; preserve the database and inspect manually.") + } + val expectedForeignKeys = Regex( + "(?m)^ CONSTRAINT ([a-z_]+) FOREIGN KEY \\(([^)]+)\\) REFERENCES ([a-z_]+)\\(([^)]+)\\)", + ).findAll(table.ddl).associate { match -> + match.groupValues[1] to Triple(match.groupValues[2], match.groupValues[3], match.groupValues[4]) + } + val actualForeignKeys = connection.metaData.getImportedKeys(schema, null, table.name).use { rows -> + buildMap { + while (rows.next()) put( + rows.getString("FK_NAME"), + Triple(rows.getString("FKCOLUMN_NAME"), rows.getString("PKTABLE_NAME"), rows.getString("PKCOLUMN_NAME")), + ) + } + } + if (expectedForeignKeys != actualForeignKeys) throw MysqlStorageException( + "MySQL table ${table.name} has unexpected foreign keys; preserve the database and inspect manually.", + ) + val checkCount = connection.prepareStatement( + "SELECT COUNT(*) FROM information_schema.TABLE_CONSTRAINTS " + + "WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ? AND CONSTRAINT_TYPE = 'CHECK'", + ).use { statement -> + statement.setString(1, schema) + statement.setString(2, table.name) + statement.executeQuery().use { rows -> rows.next(); rows.getInt(1) } + } + val expectedCheckCount = Regex("(?m)^ CONSTRAINT [a-z_]+ CHECK ").findAll(table.ddl).count() + if (checkCount != expectedCheckCount) throw MysqlStorageException( + "MySQL table ${table.name} has unexpected check constraints; preserve the database.", + ) + val properties = connection.prepareStatement( + "SELECT ENGINE, TABLE_COLLATION FROM information_schema.TABLES WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ?", + ).use { statement -> + statement.setString(1, schema) + statement.setString(2, table.name) + statement.executeQuery().use { rows -> + if (rows.next()) rows.getString(1) to rows.getString(2) else null + } + } + if (!"InnoDB".equals(properties?.first, ignoreCase = true) || properties?.second != "utf8mb4_0900_ai_ci") throw MysqlStorageException( + "MySQL table ${table.name} must use InnoDB and utf8mb4_0900_ai_ci; preserve the database.", + ) + } + + private fun sha256(value: String): String = MessageDigest.getInstance("SHA-256") + .digest(value.toByteArray(StandardCharsets.UTF_8)) + .joinToString("") { "%02x".format(it.toInt() and 0xff) } + } +} + +private data class TableDefinition(val name: String, val ddl: String) +private data class ColumnShape(val type: String, val length: Int?, val nullable: Boolean, val collation: String?) +private data class IndexShape(val columns: List, val unique: Boolean) diff --git a/invitecode-storage-sql/src/main/kotlin/io/github/command1264/invitecode/storage/sql/MysqlStorageException.kt b/invitecode-storage-sql/src/main/kotlin/io/github/command1264/invitecode/storage/sql/MysqlStorageException.kt new file mode 100644 index 0000000..b31dbe8 --- /dev/null +++ b/invitecode-storage-sql/src/main/kotlin/io/github/command1264/invitecode/storage/sql/MysqlStorageException.kt @@ -0,0 +1,3 @@ +package io.github.command1264.invitecode.storage.sql + +class MysqlStorageException(message: String) : IllegalStateException(message) diff --git a/invitecode-storage-sql/src/main/kotlin/io/github/command1264/invitecode/storage/sql/SqlDialect.kt b/invitecode-storage-sql/src/main/kotlin/io/github/command1264/invitecode/storage/sql/SqlDialect.kt new file mode 100644 index 0000000..0caa6fa --- /dev/null +++ b/invitecode-storage-sql/src/main/kotlin/io/github/command1264/invitecode/storage/sql/SqlDialect.kt @@ -0,0 +1,14 @@ +package io.github.command1264.invitecode.storage.sql + +import java.sql.Connection +import java.time.Instant +import java.time.format.DateTimeFormatter +import java.time.format.DateTimeFormatterBuilder + +internal fun Connection.isMysql(): Boolean = metaData.databaseProductName.equals("MySQL", ignoreCase = true) + +private val MYSQL_INSTANT_FORMAT: DateTimeFormatter = DateTimeFormatterBuilder().appendInstant(9).toFormatter() + +/** Fixed-width UTC text keeps lexical index ordering equal to chronological ordering in MySQL. */ +internal fun Instant.toSqlText(connection: Connection): String = + if (connection.isMysql()) MYSQL_INSTANT_FORMAT.format(this) else toString() diff --git a/invitecode-storage-sql/src/main/kotlin/io/github/command1264/invitecode/storage/sql/SqlStorageBackends.kt b/invitecode-storage-sql/src/main/kotlin/io/github/command1264/invitecode/storage/sql/SqlStorageBackends.kt index eea7773..8d48536 100644 --- a/invitecode-storage-sql/src/main/kotlin/io/github/command1264/invitecode/storage/sql/SqlStorageBackends.kt +++ b/invitecode-storage-sql/src/main/kotlin/io/github/command1264/invitecode/storage/sql/SqlStorageBackends.kt @@ -9,5 +9,5 @@ object SqliteStorageBackend : StorageBackendDescriptor { object MysqlStorageBackend : StorageBackendDescriptor { override val id: String = "mysql" - override val productionReady: Boolean = false + override val productionReady: Boolean = true } 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 53035ba..da764b4 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 @@ -15,7 +15,12 @@ import java.util.UUID internal object SqlitePlayerRecords { fun save(connection: Connection, player: StoredPlayer) { connection.prepareStatement( - """ + if (connection.isMysql()) """ + INSERT INTO invitecode_players(player_id, first_seen_at, last_known_name) + VALUES (?, ?, ?) + ON DUPLICATE KEY UPDATE + last_known_name = COALESCE(VALUES(last_known_name), last_known_name) + """.trimIndent() else """ INSERT INTO invitecode_players(player_id, first_seen_at, last_known_name) VALUES (?, ?, ?) ON CONFLICT(player_id) DO UPDATE SET @@ -23,7 +28,7 @@ internal object SqlitePlayerRecords { """.trimIndent(), ).use { statement -> statement.setString(1, player.id.toString()) - statement.setString(2, player.firstSeenAt.toString()) + statement.setString(2, player.firstSeenAt.toSqlText(connection)) statement.setString(3, player.lastKnownName) statement.executeUpdate() } @@ -34,7 +39,7 @@ internal object SqlitePlayerRecords { """ SELECT player_id, first_seen_at, last_known_name FROM invitecode_players - WHERE last_known_name = ? COLLATE NOCASE + WHERE last_known_name = ? ${if (connection.isMysql()) "" else "COLLATE NOCASE"} ORDER BY player_id LIMIT 2 """.trimIndent(), @@ -57,7 +62,10 @@ internal object SqlitePlayerRecords { fun recordLoginDay(connection: Connection, playerId: UUID, loginDate: LocalDate) { connection.prepareStatement( - "INSERT OR IGNORE INTO invitecode_player_login_days(player_id, login_date) VALUES (?, ?)", + if (connection.isMysql()) + "INSERT INTO invitecode_player_login_days(player_id, login_date) VALUES (?, ?) " + + "ON DUPLICATE KEY UPDATE login_date = VALUES(login_date)" + else "INSERT OR IGNORE INTO invitecode_player_login_days(player_id, login_date) VALUES (?, ?)", ).use { statement -> statement.setString(1, playerId.toString()) statement.setString(2, loginDate.toString()) @@ -148,7 +156,7 @@ internal object SqlitePlayerRecords { WHERE player_id = ? """.trimIndent(), ).use { statement -> - statement.setString(1, transition.state.firstSeenAt.toString()) + statement.setString(1, transition.state.firstSeenAt.toSqlText(connection)) statement.setString(2, transition.state.playerId.toString()) statement.executeUpdate() } @@ -161,7 +169,13 @@ internal object SqlitePlayerRecords { internal object SqliteNetworkHashRecords { fun save(connection: Connection, record: PlayerNetworkHash) { connection.prepareStatement( - """ + if (connection.isMysql()) """ + INSERT INTO invitecode_player_network_hashes(player_id, key_id, network_hash, observed_at, expires_at) + VALUES (?, ?, ?, ?, ?) + ON DUPLICATE KEY UPDATE + observed_at = VALUES(observed_at), + expires_at = VALUES(expires_at) + """.trimIndent() else """ INSERT INTO invitecode_player_network_hashes(player_id, key_id, network_hash, observed_at, expires_at) VALUES (?, ?, ?, ?, ?) ON CONFLICT(player_id, key_id, network_hash) DO UPDATE SET @@ -172,8 +186,8 @@ internal object SqliteNetworkHashRecords { statement.setString(1, record.playerId.toString()) statement.setString(2, record.keyId) statement.setString(3, record.hash) - statement.setString(4, record.observedAt.toString()) - statement.setString(5, record.expiresAt.toString()) + statement.setString(4, record.observedAt.toSqlText(connection)) + statement.setString(5, record.expiresAt.toSqlText(connection)) statement.executeUpdate() } } @@ -181,7 +195,7 @@ internal object SqliteNetworkHashRecords { fun purgeExpired(connection: Connection, expiredAt: Instant): Int = connection.prepareStatement( "DELETE FROM invitecode_player_network_hashes WHERE expires_at <= ?", ).use { statement -> - statement.setString(1, expiredAt.toString()) + statement.setString(1, expiredAt.toSqlText(connection)) statement.executeUpdate() } @@ -213,8 +227,8 @@ internal object SqliteNetworkHashRecords { ).use { statement -> statement.setString(1, firstPlayerId.toString()) statement.setString(2, secondPlayerId.toString()) - statement.setString(3, evaluatedAt.toString()) - statement.setString(4, evaluatedAt.toString()) + statement.setString(3, evaluatedAt.toSqlText(connection)) + statement.setString(4, evaluatedAt.toSqlText(connection)) statement.executeQuery().use { it.next() } } } @@ -273,7 +287,7 @@ internal object SqliteInviteCodeRecords { ).use { statement -> statement.setString(1, activeInviteCode.code.normalized) statement.setString(2, activeInviteCode.inviterId.toString()) - statement.setString(3, activeInviteCode.activatedAt.toString()) + statement.setString(3, activeInviteCode.activatedAt.toSqlText(connection)) statement.executeUpdate() } } @@ -286,7 +300,7 @@ internal object SqliteInviteCodeRecords { WHERE code = ? AND inviter_id = ? AND retired_at IS NULL """.trimIndent(), ).use { statement -> - statement.setString(1, retiredInviteCode.retiredAt.toString()) + statement.setString(1, retiredInviteCode.retiredAt.toSqlText(connection)) statement.setString(2, retiredInviteCode.code.normalized) statement.setString(3, retiredInviteCode.inviterId.toString()) statement.executeUpdate() diff --git a/invitecode-storage-sql/src/main/kotlin/io/github/command1264/invitecode/storage/sql/SqliteInvitationRecords.kt b/invitecode-storage-sql/src/main/kotlin/io/github/command1264/invitecode/storage/sql/SqliteInvitationRecords.kt index a398b34..62417c8 100644 --- a/invitecode-storage-sql/src/main/kotlin/io/github/command1264/invitecode/storage/sql/SqliteInvitationRecords.kt +++ b/invitecode-storage-sql/src/main/kotlin/io/github/command1264/invitecode/storage/sql/SqliteInvitationRecords.kt @@ -45,8 +45,8 @@ internal object SqliteInvitationRecords { statement.setString(4, invitation.inviteeId.toString()) statement.setInt(5, inviteeGeneration) statement.setString(6, invitation.status.name) - statement.setString(7, invitation.claimedAt.toString()) - statement.setString(8, invitation.qualifiedAt?.toString()) + statement.setString(7, invitation.claimedAt.toSqlText(connection)) + statement.setString(8, invitation.qualifiedAt?.toSqlText(connection)) statement.setString(9, invitation.qualificationPolicyId) statement.setString(10, invitation.qualificationRevision) statement.executeUpdate() @@ -97,7 +97,7 @@ internal object SqliteInvitationRecords { statement.setString(1, invitation.inviterId.toString()) statement.setInt(2, inviterGeneration) statement.setString(3, invitation.status.name) - statement.setString(4, invitation.qualifiedAt?.toString()) + statement.setString(4, invitation.qualifiedAt?.toSqlText(connection)) statement.setString(5, invitation.qualificationPolicyId) statement.setString(6, invitation.qualificationRevision) statement.setString(7, invitation.id.toString()) @@ -209,7 +209,7 @@ internal object SqliteQualificationRecords { statement.setString(4, fact.qualificationRevision) statement.setString(5, fact.conditionId) statement.setString(6, fact.outcome.name) - statement.setString(7, fact.recordedAt.toString()) + statement.setString(7, fact.recordedAt.toSqlText(connection)) statement.executeUpdate() } } @@ -284,7 +284,7 @@ internal object SqliteAuditRecords { statement.setString(2, record.action.name) statement.setString(3, record.actor) statement.setString(4, record.reason) - statement.setString(5, record.occurredAt.toString()) + statement.setString(5, record.occurredAt.toSqlText(connection)) statement.setString(6, record.invitationId?.toString()) statement.setString(7, record.playerId?.toString()) statement.setString(8, details.kind) 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 b62b66b..4b80309 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 @@ -31,9 +31,12 @@ import java.nio.file.Path import java.sql.Connection import java.sql.SQLException import java.util.UUID +import javax.sql.DataSource -class SqliteInviteCodeStorage private constructor( - private val database: Path, +/** Shared JDBC operations; backend-specific connection and transaction rules stay at this boundary. */ +internal class JdbcInviteCodeStorage private constructor( + private val database: Path?, + private val mysqlSource: DataSource?, private val blockingOperationGuard: BlockingOperationGuard, ) : InviteCodeStorage { override fun qualifiedInvitationCount(inviterId: UUID): Int = read { @@ -373,6 +376,18 @@ class SqliteInviteCodeStorage private constructor( operation: (InvitationTransaction) -> T, ): T = write { connection -> require(playerIds.isNotEmpty()) { "An Invitation transaction requires at least one player." } + if (mysqlSource != null) { + playerIds.sortedBy(UUID::toString).forEach { playerId -> + connection.prepareStatement( + "SELECT player_id FROM invitecode_players WHERE player_id = ? FOR UPDATE", + ).use { statement -> + statement.setString(1, playerId.toString()) + statement.executeQuery().use { result -> + check(result.next()) { "Player $playerId must exist before Claim." } + } + } + } + } operation(object : InvitationTransaction { override fun activeInviter(inviteCode: InviteCode): UUID? = SqliteInviteCodeRecords.findActive(connection, inviteCode)?.inviterId @@ -402,8 +417,8 @@ class SqliteInviteCodeStorage private constructor( private fun read(operation: (Connection) -> T): T { blockingOperationGuard.checkAllowed() try { - return connect(database).use { connection -> - configure(connection) + return connection().use { connection -> + if (mysqlSource == null) configure(connection) operation(connection) } } catch (error: SQLException) { @@ -413,13 +428,43 @@ class SqliteInviteCodeStorage private constructor( private fun write(operation: (Connection) -> T): T { blockingOperationGuard.checkAllowed() + var retries = 0 + while (true) { + try { + return connection().use { connection -> + if (mysqlSource == null) { + configure(connection) + executeImmediateWrite(connection, requireNotNull(database), operation) + } else executeMysqlWrite(connection, operation) + } + } catch (error: SQLException) { + if (mysqlSource != null && retries < 2 && (error.errorCode == 1213 || error.sqlState == "40001")) { + retries++ + continue + } + throw storageFailure("write", error) + } + } + } + + private fun connection(): Connection = mysqlSource?.connection ?: connect(requireNotNull(database)) + + private fun executeMysqlWrite(connection: Connection, operation: (Connection) -> T): T { + connection.transactionIsolation = Connection.TRANSACTION_READ_COMMITTED + connection.autoCommit = false try { - return connect(database).use { connection -> - configure(connection) - executeImmediateWrite(connection, database, operation) + val result = operation(connection) + connection.commit() + return result + } catch (error: Throwable) { + try { + connection.rollback() + } catch (rollbackError: Throwable) { + throw MysqlStorageException( + "MySQL write and rollback both failed; state is uncertain. Stop writes and inspect the database.", + ) } - } catch (error: SQLException) { - throw storageFailure("write", error) + throw error } } @@ -443,11 +488,15 @@ class SqliteInviteCodeStorage private constructor( } } - private fun storageFailure(operation: String, cause: SQLException) = SqliteStorageException( - "SQLite $operation failed for ${database.toAbsolutePath()}; " + - "the storage operation was rejected and no fallback backend was used.", - cause, - ) + private fun storageFailure(operation: String, cause: SQLException): IllegalStateException = + if (mysqlSource != null) MysqlStorageException( + "MySQL $operation failed (SQLState ${cause.sqlState ?: "unknown"}, code ${cause.errorCode}); " + + "check database availability, schema and pool capacity. The operation was rejected.", + ) else SqliteStorageException( + "SQLite $operation failed for ${requireNotNull(database).toAbsolutePath()}; " + + "the storage operation was rejected and no fallback backend was used.", + cause, + ) companion object { private fun aggregateStatus(actions: List): RewardDeliveryStatus = when { @@ -460,10 +509,10 @@ class SqliteInviteCodeStorage private constructor( else -> RewardDeliveryStatus.PENDING } - fun open( + fun openSqlite( database: Path, blockingOperationGuard: BlockingOperationGuard, - ): SqliteInviteCodeStorage { + ): JdbcInviteCodeStorage { blockingOperationGuard.checkAllowed() connect(database).use { connection -> configure(connection) @@ -483,7 +532,15 @@ class SqliteInviteCodeStorage private constructor( ) } } - return SqliteInviteCodeStorage(database, blockingOperationGuard) + return JdbcInviteCodeStorage(database, null, blockingOperationGuard) + } + + fun openMysql(dataSource: DataSource, guard: BlockingOperationGuard): JdbcInviteCodeStorage { + guard.checkAllowed() + dataSource.connection.use { connection -> + MysqlSchemaMigrator.requireCurrent(connection) + } + return JdbcInviteCodeStorage(null, dataSource, guard) } private fun configure(connection: Connection) { @@ -495,6 +552,17 @@ class SqliteInviteCodeStorage private constructor( } } +class SqliteInviteCodeStorage private constructor( + private val delegate: JdbcInviteCodeStorage, +) : InviteCodeStorage by delegate { + override fun close() = delegate.close() + + companion object { + fun open(database: Path, guard: BlockingOperationGuard): SqliteInviteCodeStorage = + SqliteInviteCodeStorage(JdbcInviteCodeStorage.openSqlite(database, guard)) + } +} + internal fun executeImmediateWrite( connection: Connection, database: Path, diff --git a/invitecode-storage-sql/src/main/kotlin/io/github/command1264/invitecode/storage/sql/SqliteRewardRecords.kt b/invitecode-storage-sql/src/main/kotlin/io/github/command1264/invitecode/storage/sql/SqliteRewardRecords.kt index 199ef79..b241c94 100644 --- a/invitecode-storage-sql/src/main/kotlin/io/github/command1264/invitecode/storage/sql/SqliteRewardRecords.kt +++ b/invitecode-storage-sql/src/main/kotlin/io/github/command1264/invitecode/storage/sql/SqliteRewardRecords.kt @@ -43,7 +43,14 @@ internal object SqliteRewardRecords { } val previousStatus = current?.status connection.prepareStatement( - """ + if (connection.isMysql()) """ + INSERT INTO invitecode_reward_deliveries( + delivery_id, invitation_id, reward_id, status, + idempotency_key, created_at, updated_at + ) VALUES (?, ?, ?, ?, ?, ?, ?) + ON DUPLICATE KEY UPDATE + status = VALUES(status), updated_at = VALUES(updated_at) + """.trimIndent() else """ INSERT INTO invitecode_reward_deliveries( delivery_id, invitation_id, reward_id, status, idempotency_key, created_at, updated_at @@ -58,8 +65,8 @@ internal object SqliteRewardRecords { statement.setString(3, delivery.rewardId) statement.setString(4, delivery.status.name) statement.setString(5, delivery.idempotencyKey) - statement.setString(6, delivery.createdAt.toString()) - statement.setString(7, delivery.updatedAt.toString()) + statement.setString(6, delivery.createdAt.toSqlText(connection)) + statement.setString(7, delivery.updatedAt.toSqlText(connection)) statement.executeUpdate() } if (previousStatus != delivery.status) { @@ -73,7 +80,7 @@ internal object SqliteRewardRecords { statement.setString(1, delivery.id.toString()) statement.setString(2, previousStatus?.name) statement.setString(3, delivery.status.name) - statement.setString(4, delivery.updatedAt.toString()) + statement.setString(4, delivery.updatedAt.toSqlText(connection)) statement.setString(5, administration?.actor) statement.setString(6, administration?.reason) statement.executeUpdate() @@ -160,7 +167,14 @@ internal object SqliteRewardRecords { } val previousStatus = current?.status connection.prepareStatement( - """ + if (connection.isMysql()) """ + 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, last_error + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) + ON DUPLICATE KEY UPDATE + status = VALUES(status), updated_at = VALUES(updated_at), last_error = VALUES(last_error) + """.trimIndent() else """ 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, last_error @@ -180,8 +194,8 @@ internal object SqliteRewardRecords { statement.setString(7, action.payload) statement.setString(8, action.status.name) statement.setString(9, action.idempotencyKey) - statement.setString(10, action.createdAt.toString()) - statement.setString(11, action.updatedAt.toString()) + statement.setString(10, action.createdAt.toSqlText(connection)) + statement.setString(11, action.updatedAt.toSqlText(connection)) statement.setString(12, action.lastError) statement.executeUpdate() } @@ -196,7 +210,7 @@ internal object SqliteRewardRecords { statement.setString(1, action.id.toString()) statement.setString(2, previousStatus?.name) statement.setString(3, action.status.name) - statement.setString(4, action.updatedAt.toString()) + statement.setString(4, action.updatedAt.toSqlText(connection)) statement.setString(5, action.lastError) statement.setString(6, administration?.actor) statement.setString(7, administration?.reason) 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 0bce13a..a802132 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 @@ -17,7 +17,7 @@ fun interface BlockingOperationGuard { fun rejectingServerMainThread(isServerMainThread: () -> Boolean): BlockingOperationGuard = BlockingOperationGuard { check(!isServerMainThread()) { - "SQLite storage cannot run on the server main thread; " + + "SQL storage cannot run on the server main thread; " + "schedule the operation on a dedicated storage executor." } } diff --git a/invitecode-storage-sql/src/main/resources/mysql/V1__initial_schema.sql b/invitecode-storage-sql/src/main/resources/mysql/V1__initial_schema.sql new file mode 100644 index 0000000..8a5ab64 --- /dev/null +++ b/invitecode-storage-sql/src/main/resources/mysql/V1__initial_schema.sql @@ -0,0 +1,185 @@ +-- @table invitecode_players +CREATE TABLE invitecode_players ( + player_id CHAR(36) CHARACTER SET ascii COLLATE ascii_bin NOT NULL, + first_seen_at VARCHAR(64) CHARACTER SET ascii NOT NULL, + last_known_name VARCHAR(64) NULL, + eligibility_generation INT NOT NULL DEFAULT 0, + PRIMARY KEY (player_id), + KEY invitecode_query_players_by_name (last_known_name, player_id), + CONSTRAINT invitecode_players_generation CHECK (eligibility_generation >= 0) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci; + +-- @table invitecode_metadata +CREATE TABLE invitecode_metadata ( + singleton INT NOT NULL, + network_key_id CHAR(64) CHARACTER SET ascii COLLATE ascii_bin NOT NULL, + PRIMARY KEY (singleton), + CONSTRAINT invitecode_metadata_singleton CHECK (singleton = 1) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci; + +-- @table invitecode_codes +CREATE TABLE invitecode_codes ( + code VARCHAR(512) COLLATE utf8mb4_bin NOT NULL, + inviter_id CHAR(36) CHARACTER SET ascii COLLATE ascii_bin NOT NULL, + activated_at VARCHAR(64) CHARACTER SET ascii NOT NULL, + retired_at VARCHAR(64) CHARACTER SET ascii NULL, + active_inviter_id CHAR(36) CHARACTER SET ascii COLLATE ascii_bin + GENERATED ALWAYS AS (IF(retired_at IS NULL, inviter_id, NULL)) STORED, + PRIMARY KEY (code), + UNIQUE KEY invitecode_one_active_code_per_inviter (active_inviter_id), + KEY invitecode_codes_by_inviter (inviter_id), + CONSTRAINT invitecode_codes_inviter_fk FOREIGN KEY (inviter_id) REFERENCES invitecode_players(player_id) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci; + +-- @table invitecode_invitations +CREATE TABLE invitecode_invitations ( + invitation_id CHAR(36) CHARACTER SET ascii COLLATE ascii_bin NOT NULL, + inviter_id CHAR(36) CHARACTER SET ascii COLLATE ascii_bin NOT NULL, + inviter_eligibility_generation INT NOT NULL, + invitee_id CHAR(36) CHARACTER SET ascii COLLATE ascii_bin NOT NULL, + invitee_eligibility_generation INT NOT NULL, + status VARCHAR(32) CHARACTER SET ascii NOT NULL, + claimed_at VARCHAR(64) CHARACTER SET ascii NOT NULL, + qualified_at VARCHAR(64) CHARACTER SET ascii NULL, + qualification_policy_id VARCHAR(191) NULL, + qualification_revision VARCHAR(191) CHARACTER SET ascii NULL, + PRIMARY KEY (invitation_id), + UNIQUE KEY invitecode_one_invitation_per_generation (invitee_id, invitee_eligibility_generation), + KEY invitecode_query_invitations_by_inviter (inviter_id, claimed_at, invitation_id, status), + CONSTRAINT invitecode_invitations_inviter_fk FOREIGN KEY (inviter_id) REFERENCES invitecode_players(player_id), + CONSTRAINT invitecode_invitations_invitee_fk FOREIGN KEY (invitee_id) REFERENCES invitecode_players(player_id), + CONSTRAINT invitecode_invitations_qualification CHECK ( + (qualified_at IS NULL AND qualification_policy_id IS NULL AND qualification_revision IS NULL) OR + (qualified_at IS NOT NULL AND qualification_policy_id IS NOT NULL AND qualification_revision IS NOT NULL) + ) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci; + +-- @table invitecode_qualification_facts +CREATE TABLE invitecode_qualification_facts ( + fact_id CHAR(36) CHARACTER SET ascii COLLATE ascii_bin NOT NULL, + invitation_id CHAR(36) CHARACTER SET ascii COLLATE ascii_bin NOT NULL, + policy_id VARCHAR(191) NOT NULL, + qualification_revision VARCHAR(191) CHARACTER SET ascii NOT NULL, + condition_id VARCHAR(191) NOT NULL, + outcome VARCHAR(32) CHARACTER SET ascii NOT NULL, + recorded_at VARCHAR(64) CHARACTER SET ascii NOT NULL, + PRIMARY KEY (fact_id), + KEY invitecode_query_qualification_facts (invitation_id, recorded_at, fact_id), + CONSTRAINT invitecode_facts_invitation_fk FOREIGN KEY (invitation_id) REFERENCES invitecode_invitations(invitation_id) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci; + +-- @table invitecode_reward_deliveries +CREATE TABLE invitecode_reward_deliveries ( + delivery_id CHAR(36) CHARACTER SET ascii COLLATE ascii_bin NOT NULL, + invitation_id CHAR(36) CHARACTER SET ascii COLLATE ascii_bin NULL, + reward_id VARCHAR(191) NOT NULL, + status VARCHAR(32) CHARACTER SET ascii NOT NULL, + idempotency_key TEXT NOT NULL, + idempotency_hash CHAR(64) CHARACTER SET ascii COLLATE ascii_bin + GENERATED ALWAYS AS (SHA2(idempotency_key, 256)) STORED, + created_at VARCHAR(64) CHARACTER SET ascii NOT NULL, + updated_at VARCHAR(64) CHARACTER SET ascii NOT NULL, + PRIMARY KEY (delivery_id), + UNIQUE KEY invitecode_delivery_idempotency (idempotency_hash), + KEY invitecode_query_reward_deliveries_by_invitation (invitation_id, created_at, delivery_id), + CONSTRAINT invitecode_delivery_invitation_fk FOREIGN KEY (invitation_id) REFERENCES invitecode_invitations(invitation_id) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci; + +-- @table invitecode_reward_actions +CREATE TABLE invitecode_reward_actions ( + action_id CHAR(36) CHARACTER SET ascii COLLATE ascii_bin NOT NULL, + reward_delivery_id CHAR(36) CHARACTER SET ascii COLLATE ascii_bin NOT NULL, + invitation_id CHAR(36) CHARACTER SET ascii COLLATE ascii_bin NULL, + recipient_id CHAR(36) CHARACTER SET ascii COLLATE ascii_bin NOT NULL, + position INT NOT NULL, + action_type VARCHAR(64) CHARACTER SET ascii NOT NULL, + payload TEXT NOT NULL, + status VARCHAR(32) CHARACTER SET ascii NOT NULL, + idempotency_key TEXT NOT NULL, + idempotency_hash CHAR(64) CHARACTER SET ascii COLLATE ascii_bin + GENERATED ALWAYS AS (SHA2(idempotency_key, 256)) STORED, + created_at VARCHAR(64) CHARACTER SET ascii NOT NULL, + updated_at VARCHAR(64) CHARACTER SET ascii NOT NULL, + last_error TEXT NULL, + PRIMARY KEY (action_id), + UNIQUE KEY invitecode_action_idempotency (idempotency_hash), + UNIQUE KEY invitecode_action_position (reward_delivery_id, position), + KEY invitecode_pending_reward_actions_by_recipient (recipient_id, status, created_at), + KEY invitecode_query_reward_actions_by_status (status), + KEY invitecode_action_invitation (invitation_id), + CONSTRAINT invitecode_action_delivery_fk FOREIGN KEY (reward_delivery_id) REFERENCES invitecode_reward_deliveries(delivery_id), + CONSTRAINT invitecode_action_invitation_fk FOREIGN KEY (invitation_id) REFERENCES invitecode_invitations(invitation_id), + CONSTRAINT invitecode_action_recipient_fk FOREIGN KEY (recipient_id) REFERENCES invitecode_players(player_id), + CONSTRAINT invitecode_action_position_nonnegative CHECK (position >= 0) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci; + +-- @table invitecode_audit_records +CREATE TABLE invitecode_audit_records ( + audit_id CHAR(36) CHARACTER SET ascii COLLATE ascii_bin NOT NULL, + action VARCHAR(64) CHARACTER SET ascii NOT NULL, + actor VARCHAR(191) NOT NULL, + reason TEXT NOT NULL, + occurred_at VARCHAR(64) CHARACTER SET ascii NOT NULL, + invitation_id CHAR(36) CHARACTER SET ascii COLLATE ascii_bin NULL, + player_id CHAR(36) CHARACTER SET ascii COLLATE ascii_bin NULL, + details_kind VARCHAR(32) CHARACTER SET ascii NOT NULL, + previous_inviter_id CHAR(36) CHARACTER SET ascii COLLATE ascii_bin NULL, + new_inviter_id CHAR(36) CHARACTER SET ascii COLLATE ascii_bin NULL, + qualification_policy_id VARCHAR(191) NULL, + qualification_revision VARCHAR(191) CHARACTER SET ascii NULL, + PRIMARY KEY (audit_id), + KEY invitecode_query_audit_by_invitation (invitation_id, occurred_at, audit_id), + KEY invitecode_query_audit_by_player (player_id, occurred_at, audit_id), + CONSTRAINT invitecode_audit_invitation_fk FOREIGN KEY (invitation_id) REFERENCES invitecode_invitations(invitation_id), + CONSTRAINT invitecode_audit_player_fk FOREIGN KEY (player_id) REFERENCES invitecode_players(player_id) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci; + +-- @table invitecode_reward_delivery_transitions +CREATE TABLE invitecode_reward_delivery_transitions ( + transition_id BIGINT NOT NULL AUTO_INCREMENT, + delivery_id CHAR(36) CHARACTER SET ascii COLLATE ascii_bin NOT NULL, + previous_status VARCHAR(32) CHARACTER SET ascii NULL, + current_status VARCHAR(32) CHARACTER SET ascii NOT NULL, + occurred_at VARCHAR(64) CHARACTER SET ascii NOT NULL, + actor VARCHAR(191) NULL, + reason TEXT NULL, + PRIMARY KEY (transition_id), + KEY invitecode_reward_delivery_transition_history (delivery_id, transition_id), + CONSTRAINT invitecode_transition_delivery_fk FOREIGN KEY (delivery_id) REFERENCES invitecode_reward_deliveries(delivery_id) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci; + +-- @table invitecode_reward_action_transitions +CREATE TABLE invitecode_reward_action_transitions ( + transition_id BIGINT NOT NULL AUTO_INCREMENT, + action_id CHAR(36) CHARACTER SET ascii COLLATE ascii_bin NOT NULL, + previous_status VARCHAR(32) CHARACTER SET ascii NULL, + current_status VARCHAR(32) CHARACTER SET ascii NOT NULL, + occurred_at VARCHAR(64) CHARACTER SET ascii NOT NULL, + last_error TEXT NULL, + actor VARCHAR(191) NULL, + reason TEXT NULL, + PRIMARY KEY (transition_id), + KEY invitecode_reward_action_transition_history (action_id, transition_id), + CONSTRAINT invitecode_transition_action_fk FOREIGN KEY (action_id) REFERENCES invitecode_reward_actions(action_id) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci; + +-- @table invitecode_player_login_days +CREATE TABLE invitecode_player_login_days ( + player_id CHAR(36) CHARACTER SET ascii COLLATE ascii_bin NOT NULL, + login_date CHAR(10) CHARACTER SET ascii NOT NULL, + PRIMARY KEY (player_id, login_date), + CONSTRAINT invitecode_login_player_fk FOREIGN KEY (player_id) REFERENCES invitecode_players(player_id) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci; + +-- @table invitecode_player_network_hashes +CREATE TABLE invitecode_player_network_hashes ( + player_id CHAR(36) CHARACTER SET ascii COLLATE ascii_bin NOT NULL, + key_id CHAR(64) CHARACTER SET ascii COLLATE ascii_bin NOT NULL, + network_hash CHAR(64) CHARACTER SET ascii COLLATE ascii_bin NOT NULL, + observed_at VARCHAR(64) CHARACTER SET ascii NOT NULL, + expires_at VARCHAR(64) CHARACTER SET ascii NOT NULL, + PRIMARY KEY (player_id, key_id, network_hash), + KEY invitecode_network_hash_expiry (expires_at), + KEY invitecode_network_hash_match (key_id, network_hash, player_id, expires_at), + CONSTRAINT invitecode_network_player_fk FOREIGN KEY (player_id) REFERENCES invitecode_players(player_id) +) 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 new file mode 100644 index 0000000..f5522e3 --- /dev/null +++ b/invitecode-storage-sql/src/test/kotlin/io/github/command1264/invitecode/storage/sql/MysqlIntegrationTest.kt @@ -0,0 +1,248 @@ +package io.github.command1264.invitecode.storage.sql + +import com.zaxxer.hikari.HikariDataSource +import io.github.command1264.invitecode.core.ClaimConfirmation +import io.github.command1264.invitecode.core.ClaimEligibilityPolicy +import io.github.command1264.invitecode.core.InvitationClaimResult +import io.github.command1264.invitecode.core.InvitationClaimService +import io.github.command1264.invitecode.core.InviteCode +import io.github.command1264.invitecode.core.InviteCodeFormats +import io.github.command1264.invitecode.core.InviteCodeGenerator +import io.github.command1264.invitecode.core.InviteCodeLifecycleService +import io.github.command1264.invitecode.core.InviteCodeStorage +import io.github.command1264.invitecode.core.MysqlConfiguration +import io.github.command1264.invitecode.core.MysqlTlsMode +import io.github.command1264.invitecode.core.PlayerNetworkHash +import io.github.command1264.invitecode.core.RewardDeliveryStatus +import io.github.command1264.invitecode.core.RewardActionStatus +import io.github.command1264.invitecode.core.StoredRewardAction +import io.github.command1264.invitecode.core.StoredRewardDelivery +import io.github.command1264.invitecode.core.StoredPlayer +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertThrows +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.Assumptions.assumeTrue +import java.sql.DriverManager +import java.time.Duration +import java.time.Instant +import java.util.UUID +import java.util.concurrent.CountDownLatch +import java.util.concurrent.Executors +import java.util.concurrent.TimeUnit + +class MysqlStorageContractTest : StorageContractTest() { + override fun withStorage(test: (InviteCodeStorage) -> Unit) = withMysqlSchema { _, pool -> + val guard = BlockingOperationGuard { } + MysqlSchemaMigrator(pool, guard).migrate() + MysqlInviteCodeStorage.open(pool, guard).use(test) + } +} + +class MysqlIntegrationTest { + @Test + fun `interrupted DDL resumes only after checking existing tables`() = withMysqlSchema { _, pool -> + val guard = BlockingOperationGuard { } + assertThrows(IllegalStateException::class.java) { + MysqlSchemaMigrator(pool, guard) { name -> + if (name == "invitecode_players") error("simulated power loss after committed DDL") + }.migrate() + } + assertEquals(1, MysqlSchemaMigrator(pool, guard).migrate()) + pool.connection.use(MysqlSchemaMigrator::requireCurrent) + } + + @Test + fun `changed table blocks interrupted migration`() = withMysqlSchema { _, pool -> + val guard = BlockingOperationGuard { } + assertThrows(IllegalStateException::class.java) { + MysqlSchemaMigrator(pool, guard) { name -> + if (name == "invitecode_players") error("simulated interruption") + }.migrate() + } + pool.connection.use { connection -> + connection.createStatement().use { it.execute("ALTER TABLE invitecode_players MODIFY last_known_name VARCHAR(32) NULL") } + } + assertThrows(MysqlStorageException::class.java) { MysqlSchemaMigrator(pool, guard).migrate() } + } + + @Test + fun `nonempty database without ledger is never treated as fresh`() = withMysqlSchema { _, pool -> + pool.connection.use { connection -> + connection.createStatement().use { it.execute("CREATE TABLE unrelated_data (id INT PRIMARY KEY) ENGINE=InnoDB") } + } + assertThrows(MysqlStorageException::class.java) { + MysqlSchemaMigrator(pool, BlockingOperationGuard { }).migrate() + } + } + + @Test + fun `table collation drift blocks reopening`() = withMysqlSchema { _, pool -> + MysqlSchemaMigrator(pool, BlockingOperationGuard { }).migrate() + pool.connection.use { connection -> + connection.createStatement().use { + it.execute("ALTER TABLE invitecode_metadata COLLATE utf8mb4_bin") + } + } + assertThrows(MysqlStorageException::class.java) { + pool.connection.use(MysqlSchemaMigrator::requireCurrent) + } + } + + @Test + fun `fractional timestamps preserve network hash expiry ordering`() = withMysqlSchema { _, pool -> + val guard = BlockingOperationGuard { } + MysqlSchemaMigrator(pool, guard).migrate() + MysqlInviteCodeStorage.open(pool, guard).use { storage -> + val player = UUID.randomUUID() + val observed = Instant.parse("2026-09-22T00:00:00Z") + storage.savePlayer(StoredPlayer(player, observed)) + storage.recordNetworkHash( + PlayerNetworkHash(player, "a".repeat(64), "b".repeat(64), observed, observed.plusNanos(500_000_000)), + ) + assertEquals(0, storage.purgeExpiredNetworkHashes(observed.plusNanos(100_000_000))) + assertEquals(1, storage.purgeExpiredNetworkHashes(observed.plusSeconds(1))) + } + } + + @Test + fun `duplicate reward idempotency key cannot mutate another delivery`() = withMysqlSchema { _, pool -> + val guard = BlockingOperationGuard { } + MysqlSchemaMigrator(pool, guard).migrate() + MysqlInviteCodeStorage.open(pool, guard).use { storage -> + val now = Instant.parse("2026-09-22T00:00:00Z") + val original = StoredRewardDelivery( + UUID.randomUUID(), null, "reward", RewardDeliveryStatus.PENDING, + "same-idempotency-key", now, now, + ) + val recipient = UUID.randomUUID() + storage.savePlayer(StoredPlayer(recipient, now)) + val action = StoredRewardAction( + UUID.randomUUID(), original.id, null, recipient, 0, "MESSAGE", "hello", + RewardActionStatus.PENDING, "original-action", now, now, + ) + storage.saveRewardDelivery(original, listOf(action)) + val conflicting = original.copy(id = UUID.randomUUID(), status = RewardDeliveryStatus.PROCESSING) + val conflictingAction = action.copy( + id = UUID.randomUUID(), rewardDeliveryId = conflicting.id, idempotencyKey = "conflicting-action", + ) + assertThrows(Exception::class.java) { storage.saveRewardDelivery(conflicting, listOf(conflictingAction)) } + assertEquals(original, storage.rewardDelivery(original.id)) + assertEquals(null, storage.rewardDelivery(conflicting.id)) + } + } + + @Test + fun `two independent instances serialize competing claims`() = withMysqlSchema { config, pool -> + val guard = BlockingOperationGuard { } + MysqlSchemaMigrator(pool, guard).migrate() + val first = MysqlInviteCodeStorage.open(pool, guard) + val secondPool = MysqlInviteCodeStorage.createPool( + config, System.getenv("INVITECODE_TEST_MYSQL_PASSWORD") ?: "", + ) + val second = MysqlInviteCodeStorage.open(secondPool, guard) + val inviters = listOf(UUID.randomUUID(), UUID.randomUUID()) + val invitee = UUID.randomUUID() + val now = Instant.parse("2026-09-22T00:00:00Z") + (inviters + invitee).forEach { first.savePlayer(StoredPlayer(it, now)) } + val codes = listOf("A25981", "0B35E7").map { InviteCode.parse(it, InviteCodeFormats.colorHex) } + inviters.zip(codes).forEach { (id, code) -> + InviteCodeLifecycleService(first, InviteCodeGenerator { code }, 1).assign(id, now) + } + val executor = Executors.newFixedThreadPool(2) + try { + val start = CountDownLatch(1) + val attempts = inviters.indices.map { index -> + executor.submit { + start.await() + InvitationClaimService( + if (index == 0) first else second, + ClaimEligibilityPolicy(Duration.ofHours(24)), + UUID::randomUUID, + ).claim( + ClaimConfirmation.present( + invitee, inviters[index], "Inviter", codes[index], + now.plusSeconds(30), Duration.ofSeconds(30), + ).confirm(invitee, now.plusSeconds(60)), + ) + } + } + start.countDown() + val results = attempts.map { it.get(15, TimeUnit.SECONDS) } + assertEquals(1, results.count { it is InvitationClaimResult.Claimed }) + assertEquals(1, results.count { it is InvitationClaimResult.Rejected }) + } finally { + executor.shutdownNow() + second.close() + first.close() + } + } + + @Test + fun `another network key cannot join the same database`() = withMysqlSchema { _, pool -> + MysqlSchemaMigrator(pool, BlockingOperationGuard { }).migrate() + pool.connection.use { MysqlSchemaMigrator.bindNetworkKey(it, "a".repeat(64)) } + assertThrows(MysqlStorageException::class.java) { + pool.connection.use { MysqlSchemaMigrator.bindNetworkKey(it, "b".repeat(64)) } + } + } + + @Test + fun `pool exhaustion has a bounded redacted error`() = withMysqlSchema { config, _ -> + val constrained = MysqlInviteCodeStorage.createPool( + config.copy(connectionTimeout = Duration.ofMillis(500)), + System.getenv("INVITECODE_TEST_MYSQL_PASSWORD") ?: "", + ) + try { + MysqlSchemaMigrator(constrained, BlockingOperationGuard { }).migrate() + val storage = MysqlInviteCodeStorage.open(constrained, BlockingOperationGuard { }) + val held = List(8) { constrained.connection } + try { + val started = System.nanoTime() + val error = assertThrows(MysqlStorageException::class.java) { storage.player(UUID.randomUUID()) } + val elapsed = Duration.ofNanos(System.nanoTime() - started) + assertEquals(true, elapsed < Duration.ofSeconds(3)) + assertEquals(true, error.message.orEmpty().contains("pool capacity")) + } finally { + held.forEach { it.close() } + } + } finally { + constrained.close() + } + } + + @Test + fun `unavailable database error excludes password`() = withMysqlSchema { config, _ -> + val error = assertThrows(MysqlStorageException::class.java) { + MysqlInviteCodeStorage.createPool( + config.copy(port = 1, connectionTimeout = Duration.ofMillis(500)), "sensitive-password", + ) + } + assertEquals(false, error.message.orEmpty().contains("sensitive-password")) + } +} + +private fun withMysqlSchema(test: (MysqlConfiguration, HikariDataSource) -> Unit) { + val host = System.getenv("INVITECODE_TEST_MYSQL_HOST") + assumeTrue(!host.isNullOrBlank(), "MySQL integration requires explicit test server environment variables.") + val port = System.getenv("INVITECODE_TEST_MYSQL_PORT")?.toIntOrNull() ?: 3306 + val username = System.getenv("INVITECODE_TEST_MYSQL_USER") ?: "root" + val password = System.getenv("INVITECODE_TEST_MYSQL_PASSWORD") ?: "" + val schema = "invitecode_test_${UUID.randomUUID().toString().replace("-", "")}" + check(Regex("invitecode_test_[0-9a-f]{32}").matches(schema)) + val serverUrl = "jdbc:mysql://$host:$port/?sslMode=REQUIRED&connectionTimeZone=UTC" + DriverManager.getConnection(serverUrl, username, password).use { admin -> + admin.createStatement().use { it.execute("CREATE DATABASE $schema") } + } + try { + val config = MysqlConfiguration( + host, port, schema, username, "${'$'}{INVITECODE_TEST_MYSQL_PASSWORD}", + "${'$'}{INVITECODE_TEST_NETWORK_SECRET}", Duration.ofSeconds(5), + MysqlTlsMode.REQUIRED, + ) + MysqlInviteCodeStorage.createPool(config, password).use { pool -> test(config, pool) } + } finally { + DriverManager.getConnection(serverUrl, username, password).use { admin -> + admin.createStatement().use { it.execute("DROP DATABASE $schema") } + } + } +} diff --git a/invitecode-storage-sql/src/test/kotlin/io/github/command1264/invitecode/storage/sql/SqliteInviteCodeStorageTest.kt b/invitecode-storage-sql/src/test/kotlin/io/github/command1264/invitecode/storage/sql/SqliteInviteCodeStorageTest.kt index df791bc..bd7835a 100644 --- a/invitecode-storage-sql/src/test/kotlin/io/github/command1264/invitecode/storage/sql/SqliteInviteCodeStorageTest.kt +++ b/invitecode-storage-sql/src/test/kotlin/io/github/command1264/invitecode/storage/sql/SqliteInviteCodeStorageTest.kt @@ -201,7 +201,7 @@ class SqliteInviteCodeStorageTest { } assertEquals( - "SQLite storage cannot run on the server main thread; " + + "SQL storage cannot run on the server main thread; " + "schedule the operation on a dedicated storage executor.", error.message, ) diff --git a/invitecode-storage-sql/src/test/kotlin/io/github/command1264/invitecode/storage/sql/StorageContractTest.kt b/invitecode-storage-sql/src/test/kotlin/io/github/command1264/invitecode/storage/sql/StorageContractTest.kt new file mode 100644 index 0000000..b54b78c --- /dev/null +++ b/invitecode-storage-sql/src/test/kotlin/io/github/command1264/invitecode/storage/sql/StorageContractTest.kt @@ -0,0 +1,66 @@ +package io.github.command1264.invitecode.storage.sql + +import io.github.command1264.invitecode.core.InviteCodeStorage +import io.github.command1264.invitecode.core.StoredPlayer +import io.github.command1264.invitecode.core.StoredRewardAction +import io.github.command1264.invitecode.core.StoredRewardDelivery +import io.github.command1264.invitecode.core.RewardActionStatus +import io.github.command1264.invitecode.core.RewardDeliveryStatus +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.io.TempDir +import java.nio.file.Path +import java.time.Instant +import java.time.LocalDate +import java.util.UUID + +abstract class StorageContractTest { + protected abstract fun withStorage(test: (InviteCodeStorage) -> Unit) + + @Test + fun `player identity and unique login days survive storage operations`() = withStorage { storage -> + val id = UUID.randomUUID() + val firstSeen = Instant.parse("2026-09-22T00:00:00Z") + storage.savePlayer(StoredPlayer(id, firstSeen, "Original")) + storage.savePlayer(StoredPlayer(id, firstSeen.plusSeconds(5), "Latest")) + storage.recordLoginDay(id, LocalDate.parse("2026-09-22")) + storage.recordLoginDay(id, LocalDate.parse("2026-09-22")) + assertEquals(StoredPlayer(id, firstSeen, "Latest"), storage.player(id)) + assertEquals(1, storage.loginDays(id)) + } + + @Test + fun `reward state and transition history are durable`() = withStorage { storage -> + val recipient = UUID.randomUUID() + val now = Instant.parse("2026-09-22T00:00:00Z") + val deliveryId = UUID.randomUUID() + val actionId = UUID.randomUUID() + storage.savePlayer(StoredPlayer(recipient, now)) + val delivery = StoredRewardDelivery( + deliveryId, null, "first-milestone", RewardDeliveryStatus.PENDING, + "milestone:$recipient:1:first-milestone", now, now, + ) + val action = StoredRewardAction( + actionId, deliveryId, null, recipient, 0, "MESSAGE", "hello", + RewardActionStatus.PENDING, "${delivery.idempotencyKey}:0", now, now, + ) + storage.saveRewardDelivery(delivery, listOf(action)) + assertEquals(delivery, storage.rewardDelivery(deliveryId)) + assertEquals(listOf(action), storage.rewardActions(deliveryId)) + storage.saveRewardAction(action.copy(status = RewardActionStatus.PROCESSING, updatedAt = now.plusSeconds(1))) + assertEquals(1, storage.recoverInterruptedRewardActions(now.plusSeconds(2))) + assertEquals(RewardActionStatus.UNCERTAIN, storage.rewardAction(actionId)?.status) + assertEquals(3, storage.rewardActionTransitions(actionId).size) + } +} + +class SqliteStorageContractTest : StorageContractTest() { + @TempDir lateinit var temporaryDirectory: Path + + override fun withStorage(test: (InviteCodeStorage) -> Unit) { + val database = temporaryDirectory.resolve("contract.db") + val guard = BlockingOperationGuard { } + SqliteSchemaMigrator(database, guard).migrate() + SqliteInviteCodeStorage.open(database, guard).use(test) + } +} From 9a9a36197c9a360695ba25cec69f204d4f16bc0e Mon Sep 17 00:00:00 2001 From: Command1264 Date: Wed, 23 Sep 2026 16:36:33 +0800 Subject: [PATCH 2/2] fix: accept literal or environment MySQL passwords --- docs/operations/mysql-storage.md | 4 ++- .../invitecode/core/StorageConfiguration.kt | 14 ++++++-- .../core/StorageConfigurationTest.kt | 20 +++++++++-- .../plugin/BukkitConfigurationLoader.kt | 14 +++++++- .../plugin/MysqlRuntimeBootstrap.kt | 4 ++- .../plugin/BukkitConfigurationLoaderTest.kt | 35 +++++++++++++++++++ .../plugin/MysqlRuntimeBootstrapTest.kt | 11 ++++++ 7 files changed, 93 insertions(+), 9 deletions(-) diff --git a/docs/operations/mysql-storage.md b/docs/operations/mysql-storage.md index 36eec73..8335a5d 100644 --- a/docs/operations/mysql-storage.md +++ b/docs/operations/mysql-storage.md @@ -24,7 +24,9 @@ mysql: tls-mode: VERIFY_IDENTITY ``` -`password` 與 `network-secret` 只接受 `${ENV_VAR}` 格式。啟動 Minecraft 伺服器前,必須在其程序環境中設定兩個變數;找不到變數會在連線前拒絕啟動。`INVITECODE_NETWORK_SECRET` 是 32 bytes 隨機資料的 Base64 字串,同一個 MySQL database 的所有插件實例必須使用完全相同的值。PowerShell 7 可在伺服器啟動腳本中產生一次,再由安全的設定管理方式保存並分發: +`password` 可以像上例使用 `${ENV_VAR}`,也可以直接在 `storage.yml` 寫入密碼,例如 `password: "在此填入自己的資料庫密碼"`。環境變數不存在時會在連線前拒絕啟動;若密碼以 `${` 開頭,必須是完整的環境變數參照,以免拼錯後被當成明文密碼。直接寫入時請限制 `storage.yml` 的讀取權限,檢查備份與檔案分享範圍,且不要把真實密碼提交到 Git。預設的 JAR 設定仍採環境變數參照,不內附密碼。 + +`network-secret` 仍只接受 `${ENV_VAR}`。啟動 Minecraft 伺服器前,必須在其程序環境中設定該變數。`INVITECODE_NETWORK_SECRET` 是 32 bytes 隨機資料的 Base64 字串,同一個 MySQL database 的所有插件實例必須使用完全相同的值。PowerShell 7 可在伺服器啟動腳本中產生一次,再由安全的設定管理方式保存並分發: ```powershell $env:INVITECODE_NETWORK_SECRET = [Convert]::ToBase64String( diff --git a/invitecode-core/src/main/kotlin/io/github/command1264/invitecode/core/StorageConfiguration.kt b/invitecode-core/src/main/kotlin/io/github/command1264/invitecode/core/StorageConfiguration.kt index 397cb1f..51ed9c4 100644 --- a/invitecode-core/src/main/kotlin/io/github/command1264/invitecode/core/StorageConfiguration.kt +++ b/invitecode-core/src/main/kotlin/io/github/command1264/invitecode/core/StorageConfiguration.kt @@ -37,7 +37,7 @@ data class MysqlConfiguration( val port: Int, val database: String, val username: String, - val passwordReference: String, + val passwordSetting: String, val networkSecretReference: String, val connectionTimeout: Duration, val tlsMode: MysqlTlsMode = MysqlTlsMode.VERIFY_IDENTITY, @@ -47,7 +47,10 @@ data class MysqlConfiguration( require(port in 1..65535) { "MySQL port must be between 1 and 65535." } require(DATABASE.matches(database)) { "MySQL database must contain only letters, digits and underscores." } require(username.isNotBlank()) { "MySQL username must not be blank." } - require(ENV_REFERENCE.matches(passwordReference)) { "MySQL password must be an environment variable reference." } + require(passwordSetting.isNotBlank()) { "MySQL password must not be blank." } + require(!passwordSetting.startsWith("${'$'}{") || ENV_REFERENCE.matches(passwordSetting)) { + "MySQL password has an invalid environment variable reference." + } require(ENV_REFERENCE.matches(networkSecretReference)) { "MySQL network secret must be an environment variable reference." } @@ -56,6 +59,11 @@ data class MysqlConfiguration( } } + override fun toString(): String = + "MysqlConfiguration(host=$host, port=$port, database=$database, username=$username, " + + "password=, networkSecretReference=$networkSecretReference, " + + "connectionTimeout=$connectionTimeout, tlsMode=$tlsMode)" + companion object { private val ENV_REFERENCE = Regex("\\$\\{[A-Za-z_][A-Za-z0-9_]*}") private val HOST = Regex("[A-Za-z0-9][A-Za-z0-9.-]*") @@ -107,7 +115,7 @@ object StorageConfigurationParser { port = mysql.requiredInteger("port", "mysql"), database = mysql.requiredString("database", "mysql"), username = mysql.requiredString("username", "mysql"), - passwordReference = mysql.requiredString("password", "mysql"), + passwordSetting = mysql.requiredString("password", "mysql"), networkSecretReference = mysql.requiredString("network-secret", "mysql"), connectionTimeout = parsePositiveDuration( mysql.requiredString("connection-timeout", "mysql"), diff --git a/invitecode-core/src/test/kotlin/io/github/command1264/invitecode/core/StorageConfigurationTest.kt b/invitecode-core/src/test/kotlin/io/github/command1264/invitecode/core/StorageConfigurationTest.kt index b5e68d7..c89a4d6 100644 --- a/invitecode-core/src/test/kotlin/io/github/command1264/invitecode/core/StorageConfigurationTest.kt +++ b/invitecode-core/src/test/kotlin/io/github/command1264/invitecode/core/StorageConfigurationTest.kt @@ -14,7 +14,7 @@ class StorageConfigurationTest { assertEquals("invitecode.db", configuration.sqlite.file) assertEquals(3306, configuration.mysql.port) assertEquals(Duration.ofSeconds(5), configuration.mysql.connectionTimeout) - assertEquals("${'$'}{INVITECODE_DB_PASSWORD}", configuration.mysql.passwordReference) + assertEquals("${'$'}{INVITECODE_DB_PASSWORD}", configuration.mysql.passwordSetting) assertEquals(MysqlTlsMode.VERIFY_IDENTITY, configuration.mysql.tlsMode) } @@ -40,12 +40,26 @@ class StorageConfigurationTest { } @Test - fun `MySQL config rejects literal credentials and URL injection`() { + fun `MySQL config accepts literal password without exposing it in configuration text`() { + val literal = "sample-only:p@ss#word" + val value = validConfiguration().toMutableMap().apply { + put("mysql", (get("mysql") as Map) + ("password" to literal)) + } + val configuration = StorageConfigurationParser.parse(value) + assertEquals(literal, configuration.mysql.passwordSetting) + assertEquals(false, configuration.toString().contains(literal)) + } + + @Test + fun `MySQL config rejects blank or malformed password and URL injection`() { fun withMysql(changed: Map): Map = validConfiguration().toMutableMap().apply { put("mysql", (get("mysql") as Map) + changed) } assertThrows { - StorageConfigurationParser.parse(withMysql(mapOf("password" to "plaintext"))) + StorageConfigurationParser.parse(withMysql(mapOf("password" to " "))) + } + assertThrows { + StorageConfigurationParser.parse(withMysql(mapOf("password" to "${'$'}{BROKEN"))) } assertThrows { StorageConfigurationParser.parse(withMysql(mapOf("host" to "localhost/?allowPublicKeyRetrieval=true"))) diff --git a/invitecode-plugin/src/main/kotlin/io/github/command1264/invitecode/plugin/BukkitConfigurationLoader.kt b/invitecode-plugin/src/main/kotlin/io/github/command1264/invitecode/plugin/BukkitConfigurationLoader.kt index 1d8dc29..c729f45 100644 --- a/invitecode-plugin/src/main/kotlin/io/github/command1264/invitecode/plugin/BukkitConfigurationLoader.kt +++ b/invitecode-plugin/src/main/kotlin/io/github/command1264/invitecode/plugin/BukkitConfigurationLoader.kt @@ -3,6 +3,7 @@ package io.github.command1264.invitecode.plugin import io.github.command1264.invitecode.platform.bukkit.InviteCodeRuntimeConfiguration import io.github.command1264.invitecode.platform.bukkit.RuntimeConfigurationAssembler import org.bukkit.configuration.ConfigurationSection +import org.bukkit.configuration.InvalidConfigurationException import org.bukkit.configuration.file.YamlConfiguration import java.nio.charset.StandardCharsets import java.nio.file.Files @@ -51,7 +52,18 @@ class BukkitConfigurationLoader( private fun loadDocument(path: Path): Map { require(Files.isRegularFile(path)) { "Configuration file does not exist: ${path.toAbsolutePath()}." } val yaml = YamlConfiguration() - Files.newBufferedReader(path, StandardCharsets.UTF_8).use { reader -> yaml.load(reader) } + Files.newBufferedReader(path, StandardCharsets.UTF_8).use { reader -> + try { + yaml.load(reader) + } catch (error: InvalidConfigurationException) { + if (path.fileName.toString() == "storage.yml") { + throw IllegalArgumentException( + "storage.yml has invalid YAML; check its syntax without sharing the file because it may contain credentials.", + ) + } + throw error + } + } return yaml.getValues(false).mapValues { (_, value) -> normalize(value) } } 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 049e2b8..c440367 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 @@ -27,7 +27,9 @@ internal class MysqlRuntimeBootstrap( ) { fun initializeOrOpen(): MysqlBootstrapResult { guard.checkAllowed() - val password = resolve(config.passwordReference, "mysql.password") + val password = if (config.passwordSetting.startsWith("${'$'}{")) { + resolve(config.passwordSetting, "mysql.password") + } else config.passwordSetting val secret = resolve(config.networkSecretReference, "mysql.network-secret") val hasher = NetworkAddressHasher.fromBase64(secret) var storage: MysqlInviteCodeStorage? = null diff --git a/invitecode-plugin/src/test/kotlin/io/github/command1264/invitecode/plugin/BukkitConfigurationLoaderTest.kt b/invitecode-plugin/src/test/kotlin/io/github/command1264/invitecode/plugin/BukkitConfigurationLoaderTest.kt index 2885cdc..4a3bc2a 100644 --- a/invitecode-plugin/src/test/kotlin/io/github/command1264/invitecode/plugin/BukkitConfigurationLoaderTest.kt +++ b/invitecode-plugin/src/test/kotlin/io/github/command1264/invitecode/plugin/BukkitConfigurationLoaderTest.kt @@ -2,6 +2,7 @@ package io.github.command1264.invitecode.plugin import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Test +import org.junit.jupiter.api.assertThrows import org.junit.jupiter.api.io.TempDir import java.nio.charset.StandardCharsets import java.nio.file.Files @@ -25,6 +26,40 @@ class BukkitConfigurationLoaderTest { assertEquals("no", configuration.messages.resolve("en_US", "value.no")) } + @Test + fun `loads quoted literal MySQL password from storage yaml without echoing it`() { + BundledConfigurationInstaller(dataDirectory) { resourcePath -> + javaClass.classLoader.getResourceAsStream(resourcePath) + }.installMissing() + val path = dataDirectory.resolve("storage.yml") + val sample = "sample-only:p@ss#word" + val updated = String(Files.readAllBytes(path), StandardCharsets.UTF_8) + .replace("${'$'}{INVITECODE_DB_PASSWORD}", sample) + Files.write(path, updated.toByteArray(StandardCharsets.UTF_8)) + + val configuration = BukkitConfigurationLoader(dataDirectory) {}.load() + + assertEquals(sample, configuration.storage.mysql.passwordSetting) + assertEquals(false, configuration.toString().contains(sample)) + } + + @Test + fun `invalid storage yaml does not expose a literal password in the error`() { + BundledConfigurationInstaller(dataDirectory) { resourcePath -> + javaClass.classLoader.getResourceAsStream(resourcePath) + }.installMissing() + val sample = "sample-only-password" + Files.write( + dataDirectory.resolve("storage.yml"), + "mysql:\n password: \"$sample".toByteArray(StandardCharsets.UTF_8), + ) + + val error = assertThrows { + BukkitConfigurationLoader(dataDirectory) {}.load() + } + assertEquals(false, error.toString().contains(sample)) + } + @Test fun `catalogs generated with unquoted yaml boolean keys remain compatible`() { BundledConfigurationInstaller(dataDirectory) { resourcePath -> diff --git a/invitecode-plugin/src/test/kotlin/io/github/command1264/invitecode/plugin/MysqlRuntimeBootstrapTest.kt b/invitecode-plugin/src/test/kotlin/io/github/command1264/invitecode/plugin/MysqlRuntimeBootstrapTest.kt index bd16b88..5cf8dcf 100644 --- a/invitecode-plugin/src/test/kotlin/io/github/command1264/invitecode/plugin/MysqlRuntimeBootstrapTest.kt +++ b/invitecode-plugin/src/test/kotlin/io/github/command1264/invitecode/plugin/MysqlRuntimeBootstrapTest.kt @@ -52,6 +52,17 @@ class MysqlRuntimeBootstrapTest { reopened.storage.close() reopened.networkHasher.close() } + val literal = MysqlRuntimeBootstrap( + config.copy(passwordSetting = password), guard, + environment = { name -> if (name == "NETWORK_SECRET") secret else null }, + ).initializeOrOpen() + try { + assertEquals(false, literal.initialized) + assertEquals(first.networkHasher.keyId, literal.networkHasher.keyId) + } finally { + literal.storage.close() + literal.networkHasher.close() + } assertThrows(MysqlStorageException::class.java) { MysqlRuntimeBootstrap(config, guard, environment = { name -> if (name == "DB_PASSWORD") password else Base64.getEncoder()