pqc_rails 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 91892e379a253edd7b6b4a8e89326c81d20e9059405b3d699482719fe119fa6f
4
- data.tar.gz: a8c899bac0730d9789629bcf2091505783b912df834e27424f8d123841232059
3
+ metadata.gz: 41bc4a54148be22522f18a002a2219af122b73c7d6a1c17724942c8ee2417256
4
+ data.tar.gz: f8ff205345965387bc2f9b8b7618caacca018490f5af2408b3ac4761291d6619
5
5
  SHA512:
6
- metadata.gz: 3ca6c3e9bd512a54cd73eaa53faaaf717253ea4cff7f0e4833c50e7a8ad7d73acb7814694215c8ee2c64d8496c2b7cd6a6d8aa5b4bc2879664598f824797563e
7
- data.tar.gz: 5278d644b9ac7bf9b1d7a38abda4555696b8e6cdfe215f3a02809fbddeb8d42172fc62568326f7bd800effd64af4758e71896e58716f2d792ec8f6c07fee163b
6
+ metadata.gz: c06207bd4e4f8ede4b809369d58d63282f3875e344156052558a4831dc844c3324ffe8bb7fb6b7945ed6bee757f48753572b19773701c8cbfd3852d017737846
7
+ data.tar.gz: c0b4c04dc6dfac82f4212229756f3ddc1e5268b1f22ee9d0eb32ffeb647e529733c02939fc6c3aaae4282ca85b59c680a573c662afa24c2a151c03c83177f0c0
data/CHANGELOG.md CHANGED
@@ -7,6 +7,201 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [0.4.0] - 2026-11-23
11
+
12
+ ### Added
13
+
14
+ - Platform gems for x86_64-linux-gnu, aarch64-linux-gnu, x86_64-linux-musl, aarch64-linux-musl
15
+ and arm64-darwin bundle a prebuilt liboqs, so `bundle install` no longer needs CMake or a C
16
+ compiler on those platforms. The prebuilt liboqs does not depend on OpenSSL, selects optimized
17
+ code for the CPU at run time, and on Linux runs on glibc 2.28 or later or on musl. Other
18
+ platforms keep installing the source gem, which builds liboqs as before.
19
+ - Ciphertexts for ActiveRecord columns and session cookies now record a format version, the
20
+ algorithm that produced them (for example `X25519+ML-KEM-768`) and the id of the key used. These
21
+ values are authenticated as AES-GCM associated data. Decryption uses the recorded algorithm, so
22
+ changing `pq_alg_name` no longer makes existing records and cookies undecryptable, and only keys
23
+ with a matching id are tried. Only registered algorithms and the configured algorithm are
24
+ accepted from a ciphertext. See "暗号文の形式" in the README and the algorithm change procedure
25
+ in docs/MIGRATION.md.
26
+ - `PqcRails.configuration.ciphertext_format`: set to `:v0` to keep writing the 0.3.0 format while
27
+ servers are updated one by one, then remove the setting. Defaults to `:v1`.
28
+ - `PqcRails::ActiveRecord::Context.install!` accepts `key_provider:`, so a custom key source can be
29
+ passed as described in docs/MIGRATION.md.
30
+ - `PqcRails.configuration.accept_legacy_records`: set to `false` to reject ActiveRecord ciphertexts
31
+ in the 0.3.0 format once all records have been re-encrypted. Defaults to `true`.
32
+ - `PqcRails.configuration.accept_legacy_cookies_until`: a `Time` until which session cookies in the
33
+ 0.3.0 format are read with keys generated by 0.3.0 or earlier. To keep existing sessions when
34
+ upgrading, set it to the time the last server stops writing the 0.3.0 format plus the longest
35
+ session lifetime. Defaults to `nil`: these cookies are rejected, except while `ciphertext_format`
36
+ is `:v0`.
37
+ - A `decryption_failed.pqc_rails` ActiveSupport::Notifications event is published when an
38
+ encrypted column or a session cookie cannot be decrypted, with the target (`:record` or
39
+ `:session`) and the exception class. Failures that are part of ActiveRecord trying `previous:`
40
+ schemes in turn are not reported.
41
+ - `PqcRails.liboqs_version` returns the version of the loaded liboqs, and `rails pqc_rails:status`
42
+ shows it.
43
+ - `rails pqc_rails:status` lists the model attributes encrypted with `encrypts` (eager loading the
44
+ application first) and the algorithm ids that new database and session ciphertexts use.
45
+ - `PqcRails::ActiveRecord::CiphertextInfo.parse(record.ciphertext_for(:attr))` reads the format
46
+ version, algorithm id and key id of a stored ciphertext without decrypting it, so records still
47
+ using an old key or the 0.3.0 format can be identified. `PqcRails::Cipher#algorithm_id` returns
48
+ the algorithm id written to new ciphertexts.
49
+ - Key pairs generated by `PqcRails::HybridKem#generate_keypair` include a random 32-byte
50
+ authentication key, stored as a third element of the encoded key. `rails pqc_rails:status`
51
+ reports keys without one.
52
+
53
+ ### Changed
54
+
55
+ - A key value of 32 or 64 bytes whose first byte is not zero, such as most ML-KEM or ML-DSA seeds
56
+ (a pqc_rails key value always starts with a zero byte), now fails with a message saying it looks like a seed-only secret key and pointing to
57
+ `rails generate pqc_rails:install`, instead of saying the key is truncated. `rails pqc_rails:status`
58
+ reports the same. The error is still a `PqcRails::Error`, and which values are accepted is unchanged.
59
+ - `PqcRails::Sig#verify` returns `false` when the signature is not a String (for example `nil`
60
+ from a missing request parameter) instead of raising `NoMethodError`. `PqcRails::Sig#sign` and
61
+ `#verify` raise `ArgumentError` instead of `NoMethodError` when the message is not a String, as
62
+ they already do for keys.
63
+ - docs/THREAT_MODEL.md states precisely how `PqcRails::Sig#verify` handles input lengths: a signature
64
+ longer than the maximum returns `false` without calling liboqs, a shorter one is checked by liboqs and
65
+ returns `false`, and a public key of the wrong length raises `ArgumentError`.
66
+ - docs/THREAT_MODEL.md describes what the in-memory secret key is protected from before what it is
67
+ not: the key never reaches the database, backups or logs, and an attacker who can read the running
68
+ process's memory is treated as holding that process's privileges, as in any software that keeps
69
+ keys in-process. The facts and recommended mitigations are unchanged.
70
+ - **Requires Ruby 3.3 or later.** Ruby 3.2 reached its end of life on 2026-04-01 and is no longer
71
+ supported. Ruby 4.0 is now tested in CI alongside 3.3 and 3.4.
72
+ - README adds ML-DSA key and signature sizes (and why SLH-DSA is not registered), explains the
73
+ constant-time and standards-based reasons for building on liboqs, and mentions DARPA's Quantum
74
+ Benchmarking Initiative. docs/THREAT_MODEL.md adds the NIST IR 8547 (final version) timeline,
75
+ the EU supervisory authorities' autumn 2026 risk update, DARPA QBI, and states that liboqs is not a
76
+ FIPS 140-3 validated module.
77
+ - README notes the German BSI's 2026-10-01 recommendation not to use Classic McEliece in new
78
+ developments, states that ML-KEM and ML-DSA are standardized in FIPS 203 and FIPS 204, and
79
+ lists blockchain and cryptocurrency transaction signatures as out of scope.
80
+ - README lists, for each protected value (session cookies, encrypted columns, signatures, TLS),
81
+ the cryptography Rails uses by default and what pqc_rails uses instead.
82
+ - README states that the default ML-KEM-768 is the parameter set NIST IR 8547 recommends as the
83
+ default for key establishment. docs/THREAT_MODEL.md notes that NIST IR 8547 typically expects
84
+ hybrid key establishment to be a temporary measure leading to a second transition to PQC-only
85
+ algorithms.
86
+ - README's API stability section now lists the key generation and encoding calls used in
87
+ docs/MIGRATION.md (`HybridKem.open` with `#generate_keypair`, `KeySource.encode` / `.decode`),
88
+ `CiphertextInfo`, `Cipher#algorithm_id`, `CiphertextFormat.key_id`, the new configuration
89
+ options and `MissingAuthenticationKeyError` as stable API.
90
+ - docs/MIGRATION.md adds a guide for replacing application-level RSA / ECDH data-key wrapping with
91
+ pqc_rails encrypted columns.
92
+ - docs/MIGRATION.md re-encrypts with `user.with_lock { user.encrypt }` so updates made while the
93
+ application keeps running are not overwritten, shows how to count records still using an old
94
+ key or the 0.3.0 format with `CiphertextInfo`, and states that public keys need not be
95
+ distributed.
96
+ - Keys generated by 0.3.0 and earlier have no authentication key and cannot write the new
97
+ ciphertext format; doing so raises `PqcRails::MissingAuthenticationKeyError`. They can still
98
+ decrypt existing data and write the 0.3.0 format with `ciphertext_format = :v0`. Generate new keys
99
+ and rotate to them when upgrading; see "0.3.0 以前からの更新" in docs/MIGRATION.md. Keys in the new
100
+ encoding can still be read by 0.3.0, which uses only the public and secret key.
101
+ - Ciphertexts grow by about 60 bytes per ActiveRecord column and about 30 bytes per session cookie
102
+ with ML-KEM-768. ActiveRecord ciphertexts written in the 0.3.0 format are still decrypted, using
103
+ the configured algorithm. Ciphertexts written in the new format cannot be decrypted by 0.3.0 or
104
+ earlier, so roll back only data written with `ciphertext_format = :v0`.
105
+ - `PqcRails::HybridKem` public keys and ciphertexts, the KEM ciphertext of encrypted ActiveRecord
106
+ attributes and session cookies with extra bytes after their last component now raise
107
+ `ArgumentError` (`ActiveRecord::Encryption::Errors::Decryption` for attributes, `PqcRails::Error`
108
+ for cookies). Previously the extra bytes were ignored, so the same plaintext could have more than
109
+ one valid encoding and a value with appended data was accepted silently. Values written by
110
+ pqc_rails never have extra bytes, so existing records, cookies and keys read as before. Hybrid
111
+ secret keys and key values are read as before.
112
+
113
+ ### Security
114
+
115
+ - When a key value cannot be read, the raised `PqcRails::Error` no longer carries the internal
116
+ unpacking error as its `cause`. That error's message held the first four bytes of the key value,
117
+ so error reports that include the cause could show part of a secret key or seed.
118
+ - Key pairs (`PqcRails::Sig::Keypair`, `Kem::Keypair`, `DhKem::Keypair` and
119
+ `HybridKem::Keypair`) no longer show secret key bytes in `inspect`, `to_s`, `pp` (used by IRB
120
+ and the Rails console) or string interpolation. Secret keys and the authentication key appear as
121
+ `[FILTERED]` and public keys as their length in bytes. `keypair.secret_key`, `to_a` and `==` are
122
+ unchanged.
123
+ - KEM results (`Kem::Encapsulation`, `DhKem::Encapsulation` and `HybridKem::Encapsulation`) no
124
+ longer show the shared secret in `inspect`, `to_s`, `pp` or string interpolation. The shared
125
+ secret appears as `[FILTERED]` and the ciphertext as its length in bytes.
126
+ - Key pairs and KEM results no longer expose secret values through `as_json` and `to_json`, which
127
+ `render json:` and JSON logs use. Public keys and ciphertexts appear as their length in bytes and
128
+ other values as `[FILTERED]`. Values read explicitly (`shared_secret`, `to_h`, `to_a`) and `==`
129
+ are unchanged, so passing those values to a log or to JSON still reveals them.
130
+ - `PqcRails::EnvelopeCipher` no longer shows its AES key in `inspect`, `pp`, `as_json` or `to_json`.
131
+ - Key pairs, KEM results and `EnvelopeCipher` no longer expose secret values in YAML (`to_yaml` and
132
+ the Rails `debug` view helper). They are written as a plain map with the same content as
133
+ `as_json`, and loading that YAML does not restore a key object. **Key pairs saved with `to_yaml`
134
+ no longer contain their secret key**; store keys with `PqcRails::KeySource.encode`. `Marshal.dump`
135
+ still contains the secret values, so do not store these objects in a cache or a log with it.
136
+ - Ciphertexts in the new format authenticate their creator. In 0.3.0 and earlier, the KEM shared
137
+ secret was used directly as the AES-256-GCM key, so anyone who knew the public key could create
138
+ ciphertexts that decrypt successfully: forged session cookies (for example with an arbitrary
139
+ `user_id`), or arbitrary values in encrypted columns for someone able to write to the database.
140
+ The AES key is now derived from both the KEM shared secret and a separate random authentication
141
+ key held with the key pair, so the authentication key is required to create a ciphertext. With
142
+ the default key storage (`PQC_SESSION_KEY` / `PQC_RECORD_KEY` or Rails credentials), the public
143
+ key is stored together with the secret key and is not exposed, so this was not exploitable unless
144
+ the public key was disclosed separately. Ciphertexts in the 0.3.0 format remain forgeable with the public
145
+ key; reject ActiveRecord ciphertexts with `accept_legacy_records` once they are no longer needed.
146
+ - Session cookies in the 0.3.0 format are no longer read by default, because their content is
147
+ restored with `Marshal.load` and a cookie forged with the public key could lead to code execution.
148
+ **Existing sessions end when upgrading** unless `accept_legacy_cookies_until` is set. These
149
+ cookies are read only with keys generated by 0.3.0 or earlier, before that deadline or while
150
+ `ciphertext_format` is `:v0`. They are not read when the session key is also configured as a
151
+ current or previous record key, because the 0.3.0 format cannot distinguish the two uses.
152
+ - ActiveRecord ciphertexts in the 0.3.0 format are now decrypted only with keys generated by 0.3.0
153
+ or earlier, so a value forged with a newer key's public key is rejected. Keep the original key as
154
+ a previous key until the records are re-encrypted. With a newer key, `ciphertext_format = :v0`
155
+ raises `PqcRails::Error` when writing a column value or a session cookie.
156
+ - Ciphertexts in the new format are bound to their use. The AES key derivation and associated data
157
+ distinguish ActiveRecord columns from session cookies, so with the same key configured for both,
158
+ a stored column value cannot be presented as a session cookie.
159
+ - An authentication key that is not a 32-byte string is now rejected instead of being used to
160
+ derive the AES key.
161
+ - Secret keys and shared secrets passed to and from liboqs are now zeroed in the native buffers
162
+ after each key generation, encapsulation, decapsulation and signature. Previously these buffers
163
+ were freed by the garbage collector without being cleared. Secret keys held as Ruby Strings cannot
164
+ be wiped reliably and stay in memory for the life of the process; see "中間値の破棄" in
165
+ docs/THREAT_MODEL.md.
166
+ - Fewer copies of secret keys are left in Ruby memory. Keys are decoded once per key source and
167
+ kept, instead of the previous keys being decoded again on every decryption, and the decoded key
168
+ blob and the X25519 and ML-KEM secret key copies made during decapsulation are zeroed after use.
169
+ Keys are therefore read once per process; restart the application after changing them, as was
170
+ already needed for the current key. docs/THREAT_MODEL.md lists what remains in memory and
171
+ recommends disabling core dumps and unencrypted swap in production.
172
+ - The bundled liboqs source is pinned to the upstream commit of its release tag. Gem builds and the
173
+ development fallback that clones liboqs stop if the tag resolves to a different commit, and
174
+ `rake vendor:verify` compares the bundled source file by file with that commit. Pass `DIR=` to
175
+ check the `ext/pqc_rails/vendor/liboqs` directory of a gem unpacked with `gem unpack`.
176
+
177
+ ### Fixed
178
+
179
+ - `PqcRails::Cipher#decrypt` no longer raises `NoMethodError` when ActiveRecord passes keys that
180
+ are not pqc_rails key pairs. This happens when Rails' standard encryption was configured
181
+ (`primary_key` set) and ActiveRecord adds previous schemes; an unreadable value now raises
182
+ `ActiveRecord::Encryption::Errors::Decryption` as expected.
183
+ - `bundle install` now builds liboqs correctly when the gem is installed under a path containing
184
+ spaces. The build scripts run `git` and `cmake` directly with argument lists instead of through
185
+ a shell, so the install path is no longer split or interpreted by the shell.
186
+ - `nil` keys and ciphertexts passed to `PqcRails::Kem` and `PqcRails::DhKem` now raise
187
+ `ArgumentError` instead of `NoMethodError`. Truncated or empty keys and ciphertexts passed to
188
+ `PqcRails::HybridKem` raise `ArgumentError` stating that the input is truncated, instead of
189
+ `TypeError` or `NoMethodError`. A `PqcRails::EnvelopeCipher` ciphertext shorter than the IV and
190
+ the 16-byte authentication tag raises `ArgumentError` before decryption, instead of an OpenSSL
191
+ error.
192
+ - A truncated session cookie now raises `PqcRails::Error`, for both the current and the 0.3.0
193
+ format. `PqcRails::Session::PqcCookieStore` treats it as an unreadable session as before.
194
+ - A key value in `ENV` or Rails credentials that is cut short now raises `PqcRails::Error` when
195
+ the key is loaded, and `rails pqc_rails:status` reports it instead of stopping. This also applies
196
+ to previous keys, so a cut-short previous key stops the application in the same way as a missing
197
+ current key. Previously such a key loaded and failed only when it was used.
198
+ - Encrypted ActiveRecord attributes holding non-ASCII text (for example Japanese) are now read back
199
+ as UTF-8 strings. Previously they were returned with the `ASCII-8BIT` (binary) encoding, so they
200
+ did not compare equal to the original string and could raise `Encoding::CompatibilityError` when
201
+ combined with UTF-8 strings in views. Stored ciphertexts are unchanged; existing records read
202
+ correctly after updating. Binary attributes are still returned as binary. Strings in encodings
203
+ other than UTF-8 are not restored to their original encoding.
204
+
10
205
  ## [0.3.0] - 2026-09-25
11
206
 
12
207
  ### Changed
@@ -176,7 +371,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
176
371
  documentation for decision-makers and developers.
177
372
  - CI workflow building liboqs from source and running the test suite on push/PR.
178
373
 
179
- [Unreleased]: https://github.com/mabutast/pqc_rails/compare/v0.3.0...HEAD
374
+ [Unreleased]: https://github.com/mabutast/pqc_rails/compare/v0.4.0...HEAD
375
+ [0.4.0]: https://github.com/mabutast/pqc_rails/compare/v0.3.0...v0.4.0
180
376
  [0.3.0]: https://github.com/mabutast/pqc_rails/compare/v0.2.1...v0.3.0
181
377
  [0.2.1]: https://github.com/mabutast/pqc_rails/compare/v0.2.0...v0.2.1
182
378
  [0.2.0]: https://github.com/mabutast/pqc_rails/compare/v0.1.0...v0.2.0
data/README.md CHANGED
@@ -23,7 +23,7 @@ PqcRails::ActiveRecord::Context.install!
23
23
 
24
24
  PQC 対応の義務化を待つ理由はありません。今この瞬間も、ハーベスト攻撃(Harvest Now, Decrypt Later:暗号化通信を今傍受し、将来の量子コンピュータで解読する攻撃)によってデータは蓄積され続けています。
25
25
 
26
- 過去に漏れたデータは取り返せませんが、これから先の通信は今日から守ることができます。`pqc_rails` は、既存の Rails アプリケーションに耐量子暗号を組み込み、この現在進行形のリスクに対処します。
26
+ 過去に漏れたデータは取り返せませんが、これから先の通信は今日から守ることができます。量子コンピュータの実現時期に確定的な予測はありませんが、米 DARPA は 2033 年までに産業上有用な量子コンピュータを構築できるかを、第三者の立場で検証する計画([Quantum Benchmarking Initiative](https://www.darpa.mil/research/programs/quantum-benchmarking-initiative))を進めています。`pqc_rails` は、既存の Rails アプリケーションに耐量子暗号を組み込み、この現在進行形のリスクに対処します。
27
27
 
28
28
  詳しい脅威モデルはこちら → [docs/THREAT_MODEL.md](docs/THREAT_MODEL.md)
29
29
 
@@ -39,6 +39,17 @@ PQC 対応の義務化を待つ理由はありません。今この瞬間も、
39
39
  | ActiveRecord::Encryption 連携 | ✅ 対応済み(`PqcRails::Cipher` + `KeyProvider`) |
40
40
  | 鍵ローテーション | ✅ 対応済み(セッション・DB 双方で旧鍵世代を併用可能。詳細は [docs/MIGRATION.md](docs/MIGRATION.md#鍵ローテーションpqc_rails鍵世代間)) |
41
41
 
42
+ 置き換える暗号は次の通りです。
43
+
44
+ | 保護するもの | Rails 標準 | pqc_rails |
45
+ | --- | --- | --- |
46
+ | セッション Cookie | AES-256-GCM。鍵は `secret_key_base` から導いた固定の鍵 | 値ごとに X25519 + ML-KEM(既定は ML-KEM-768)で鍵を作り、AES-256-GCM で暗号化 |
47
+ | DB カラム(`encrypts`) | AES-256-GCM。鍵は `primary_key` から導いた固定の鍵 | 同上 |
48
+ | 署名 | 該当する機能なし | ML-DSA(`PqcRails::Sig`、単体のプリミティブとして提供) |
49
+ | TLS 通信路 | 対象外(Web サーバ・ロードバランサの設定) | 対象外 |
50
+
51
+ ML-KEM は NIST FIPS 203、ML-DSA は NIST FIPS 204 で標準化されたアルゴリズムです。既定の ML-KEM-768 は、[NIST IR 8547](https://csrc.nist.gov/pubs/ir/8547/final) が鍵確立の既定として推奨するパラメータセットと同じです。読み込んでいる liboqs の版は `rails pqc_rails:status`(`PqcRails.liboqs_version`)で確認できます。
52
+
42
53
  KEM と DSA に加え、セッション Cookie と ActiveRecord::Encryption の両方を ML-KEM ベースのハイブリッド暗号(KEM-DEM 構成)で保護します。liboqs がサポートする他のアルゴリズムも、アルゴリズム名を文字列で指定するだけで利用できます(liboqs 側のビルド設定に依存します)。
43
54
 
44
55
  ## スコープ
@@ -46,7 +57,9 @@ KEM と DSA に加え、セッション Cookie と ActiveRecord::Encryption の
46
57
  - **対象はアプリケーション層の暗号化**(セッション Cookie・DB カラム)です。TLS 通信路そのものの PQC 化(Web サーバ・ロードバランサ側の設定)は対象外です。Ruby / RubyGems エコシステム側でも標準ライブラリ全体を PQC 対応させる議論([Ruby Feature #22068](https://bugs.ruby-lang.org/issues/22068))が進んでいますが、これは輸送路の話であり、`pqc_rails` が担うアプリケーションデータの暗号化とはレイヤーが異なります。Cloudflare のようなCDN/エッジ事業者がオリジンサーバーとの接続で PQC ハイブリッド鍵交換をデフォルト化しても、それは TLS 層の話であり、保存データ(Cookie・DB カラム)の保護には別途 `pqc_rails` のようなアプリケーション層の対応が必要です。
47
58
  - **PKI・証明書管理基盤の代替ではありません**。鍵の発行・ライフサイクル管理・監査ログといった機能は提供しません。`pqc_rails` が担うのは Rails アプリ内のセッション・DB カラムの暗号化のみです。
48
59
  - **量子コンピュータそのものを使う暗号方式(QKD、量子署名など)は対象外です**。`pqc_rails` が提供するのは、古典コンピュータ上で動作し量子コンピュータに対して耐性を持つ暗号(PQC: Post-Quantum Cryptography)です。
49
- - **JWT/トークン署名は対象外です**。`PqcRails::Sig`(ML-DSA)はスタンドアロンの署名プリミティブとして提供していますが、セッション・DB統合と違いJWT等のトークンフォーマットへの統合は行っていません。この用途には [jwt-pq](https://rubygems.org/gems/jwt-pq) のような専用 gem を検討してください(`pqc_rails` とは別々の liboqs を読み込むため、併用しても競合しません)。
60
+ - **暗号資産・ブロックチェーンの取引署名の移行は対象外です**。`pqc_rails` が統合しているのはデータの暗号化(機密性)で、ウォレットやチェーン上の署名方式の移行は扱いません。
61
+ - **署名の移行(証明書・コード署名など)は対象外です**。`pqc_rails` が Rails に統合しているのは KEM による暗号化(セッション Cookie・DB カラム)だけなので、ML-DSA などへの署名の移行は別に計画してください。
62
+ - **JWT/トークン署名は対象外です**。`PqcRails::Sig`(ML-DSA)は単体の署名プリミティブとして提供していますが、セッション・DB統合と違いJWT等のトークンフォーマットへの統合は行っていません。この用途には [jwt-pq](https://rubygems.org/gems/jwt-pq) のような専用 gem を検討してください(`pqc_rails` とは別々の liboqs を読み込むため、併用しても競合しません)。
50
63
 
51
64
  より詳しい対応範囲・スコープ外は [docs/THREAT_MODEL.md](docs/THREAT_MODEL.md#for-developers) を参照してください。
52
65
 
@@ -54,8 +67,10 @@ KEM と DSA に加え、セッション Cookie と ActiveRecord::Encryption の
54
67
 
55
68
  Ruby 向けの耐量子暗号実装には、`pqc_rails` のように [liboqs](https://github.com/open-quantum-safe/liboqs) へ FFI バインディングする方式のほかに、参照実装(`mlkem-native` / `mldsa-native` 等)のソースを gem 自体に直接バンドルする方式もあります(例: [pq_crypto](https://rubygems.org/gems/pq_crypto))。`pqc_rails` が liboqs 経由の方式を選んでいる理由は次の通りです。
56
69
 
57
- - **アルゴリズムカバレッジの広さ**: ML-KEM/ML-DSA に加え、Classic McEliece・HQC など NIST 標準化プロセスの周辺にあるアルゴリズムも、liboqs がビルドしていれば追加コード無しで利用できます(本 README 後述の「レジストリ未登録のアルゴリズムを使う」参照)。
70
+ - **アルゴリズムカバレッジの広さ**: ML-KEM/ML-DSA に加え、HQC・Classic McEliece など NIST 標準化プロセスの周辺にあるアルゴリズムも、liboqs がビルドしていれば追加コード無しで利用できます(本 README 後述の「レジストリ未登録のアルゴリズムを使う」参照)。
58
71
  - **Open Quantum Safe プロジェクトによる継続的なメンテナンス**: NIST の標準化状況の変化(追加署名 Round3 候補の選定・撤退、パラメータセットの追加等)に対して、liboqs 本体の更新に追従するだけで対応できます。
72
+ - **定数時間の実装**: liboqs が ML-KEM に使う実装(mlkem-native)は、秘密のデータによって処理の分岐やメモリの読み方が変わらない(定数時間)よう設計され、その性質が検査されています。Ruby だけで書かれた実装は、整数演算やメモリ管理をインタプリタに任せるため、同じ性質を保証するのは困難です。`pqc_rails` は、liboqs との受け渡しに一時的に使う C のバッファのうち秘密鍵・共有鍵を置くものを、使い終わりにゼロで埋めます(復号に使う鍵そのものはプロセスが保持します。詳細は [docs/THREAT_MODEL.md](docs/THREAT_MODEL.md) の表の「中間値の破棄」と、その下の既知の限界)。
73
+ - **標準化されたアルゴリズムと OSS**: `pqc_rails` が使うのは NIST が標準化したアルゴリズム(FIPS 203 / FIPS 204)で、独自の暗号方式は使いません。liboqs は MIT ライセンスの OSS で、ソースを確認し、自分の環境でビルドできます。
59
74
  - **追加署名 Round3 候補への追従のしやすさ**: liboqs は SQIsign 等の Round3 候補も実装しているため、将来これらをサポート対象に加える判断をした場合の実装コストが小さくなります。
60
75
 
61
76
  一方で、liboqs 自体の成熟度に関する留保(本 README 前述の「liboqs の成熟度について」)や、C ライブラリのビルド・配置が必要になる運用上の負担は、この設計判断のトレードオフです。
@@ -70,12 +85,15 @@ Ruby 向けの耐量子暗号実装には、`pqc_rails` のように [liboqs](ht
70
85
 
71
86
  ## 必要要件
72
87
 
73
- - Ruby >= 3.2.0
88
+ - Ruby >= 3.3.0
74
89
  - Rails >= 7.1
75
90
  - RubyGems / Bundler >= 4.0.16 を推奨(rubygems.org は X25519MLKEM768 + ML-DSA-65 によるハイブリッド TLS を提供しており、4.0.16 未満では `Gem::Request` / `Bundler::Fetcher` のクライアント証明書鍵種別が RSA に決め打ちされる不具合の影響を受けます)
76
- - CMake・Cコンパイラ(`cmake`、`make`、`gcc`/`clang` 等)が利用できること(`bundle install` 時に liboqs をソースからビルドするため。動作確認済み環境は macOS arm64 / Linux arm64(Dockerコンテナ)です。x86_64・Windows は未検証です)
91
+ - 次の環境では、ビルド済みの liboqs を同梱した gem が入るため、CMake・Cコンパイラは不要です
92
+ - Linux x86_64 / arm64(glibc 2.28 以上、または musl)
93
+ - macOS arm64
94
+ - それ以外の環境(Intel Mac・Windows 等)では、CMake・Cコンパイラ(`cmake`、`make`、`gcc`/`clang` 等)が利用できること(`bundle install` 時に liboqs をソースからビルドするため)
77
95
 
78
- `bundle install` を実行すると、liboqs のソース(gem に同梱済み)を自動的にビルドし、事前準備なしで利用できます。既に liboqs をシステムにインストール済みの場合や、ビルド環境が無い場合は、`bundle config set build.pqc_rails --skip-liboqs` (または環境変数 `PQC_RAILS_SKIP_LIBOQS_BUILD=1`)でビルドをスキップし、`config.liboqs_path` で既存の liboqs を明示的に指定できます。
96
+ Bundler は、環境に合ったビルド済みの gem を自動的に選びます。ビルド済みの liboqs は OpenSSL に依存せず、実行時に CPU の機能を調べて最適な実装を選びます。ビルド済みの gem が無い環境では、`bundle install` が liboqs のソース(gem に同梱済み)を自動的にビルドし、事前準備なしで利用できます。既に liboqs をシステムにインストール済みの場合や、ビルド環境が無い場合は、`bundle config set build.pqc_rails --skip-liboqs` (または環境変数 `PQC_RAILS_SKIP_LIBOQS_BUILD=1`)でビルドをスキップし、`config.liboqs_path` で既存の liboqs を明示的に指定できます。
79
97
 
80
98
  ## ⚠️ liboqs の成熟度について
81
99
 
@@ -133,12 +151,12 @@ Rails の `cookie_store` を ML-KEM ベースの PQC ストアで完全に置き
133
151
 
134
152
  #### Cookie サイズについて
135
153
 
136
- `HybridKem` の ciphertext を含むため、Cookie は Rails 標準(AES-256-GCM)より大きくなります。実測値(開発機、単純なセッション内容での計測)は次の通りです。
154
+ `HybridKem` の ciphertext を含むため、Cookie は Rails 標準(AES-256-GCM)より大きくなります。実測値は次の通りです(開発機、ML-KEM-768。Cookie の値を URL エスケープした長さ。Rails 標準は ActiveSupport::MessageEncryptor で同じ内容を AES-256-GCM で暗号化した値)。
137
155
 
138
156
  | 内容 | pqc_rails(ML-KEM-768、デフォルト) | Rails 標準 |
139
157
  | ----------------------------- | ------------------------------------ | ---------- |
140
- | 空セッション | 約1,770 bytes | 約170 bytes |
141
- | `user_id` + CSRF トークン程度 | 約1,850 bytes | 約260 bytes |
158
+ | 空セッション | 約1,700 bytes | 約130 bytes |
159
+ | `user_id` + CSRF トークン程度 | 約1,800 bytes | 約230 bytes |
142
160
 
143
161
  単一 Cookie の上限(多くのブラウザで4,096 bytes)には収まりますが、他の Cookie(analytics・A/B テスト用等)と合算されるリクエストヘッダ全体の上限(多くのサーバ/プロキシで8KB前後)には注意してください。
144
162
 
@@ -166,6 +184,53 @@ end
166
184
 
167
185
  鍵は Rails credentials の `pqc_record_key` から読み込みます。環境変数 `PQC_RECORD_KEY` で上書き可能です。セッション用の鍵とは別管理です。
168
186
 
187
+ ### 暗号文の形式
188
+
189
+ DB カラム・セッション Cookie とも、暗号文は形式バージョン・アルゴリズムID(例: `X25519+ML-KEM-768`)・鍵IDを持ちます。復号は暗号文に書かれたアルゴリズムで行い、鍵IDが一致する鍵だけを試します。これらの値は AES-256-GCM の追加認証データに含まれるため、書き換えられた暗号文は復号できません。暗号文に書かれたアルゴリズムのうち、復号に使うのはアルゴリズムのレジストリに登録されたものと、設定で指定したものだけです。
190
+
191
+ 鍵ペアは、公開鍵・秘密鍵に加えて、32バイトのランダムな認証鍵を持ちます。AES-256-GCM の鍵は、KEM の共有鍵と認証鍵の両方から導きます。暗号化には認証鍵が必要になるため、公開鍵を知っている者でも、正しく復号できる暗号文は作れません(作成元の認証)。公開鍵は秘密にする必要がありません。認証鍵は KEM の鍵と無関係な乱数なので、量子コンピュータで公開鍵から秘密鍵を求められても、暗号文は作れません。
192
+
193
+ 0.3.0 以前に生成した鍵は認証鍵を持たないため、新しい形式の暗号文を書けません(`PqcRails::MissingAuthenticationKeyError` が発生します)。新しい鍵を生成してローテーションしてください。手順は [docs/MIGRATION.md](docs/MIGRATION.md#030-以前からの更新) を参照してください。`rails pqc_rails:status` は、認証鍵を持たない鍵を報告します。
194
+
195
+ 0.3.0 以前の版が DB カラムに書いた暗号文(これらの値を持たない形式)は、認証鍵を持たない元の鍵で引き続き復号できます。元の鍵は旧鍵に残してください。その場合は設定のアルゴリズムで復号します。この旧形式は作成元の認証を持たず、公開鍵だけで作れます。全レコードを再暗号化したら、旧形式を受け付けない設定にしてください。
196
+
197
+ 旧形式のセッション Cookie は、既定では読みません。Cookie の中身は Ruby の `Marshal` で復元するため、公開鍵だけで作れる Cookie を読むと、サーバー上でコードを実行される危険があります。0.3.0 から更新する時に既存のセッションを保つには、`accept_legacy_cookies_until` に期限を設定します。設定しない場合、既存のセッションは更新時に切れます。期限内でも、旧形式を読むのは認証鍵を持たない鍵(0.3.0 以前に生成した鍵)だけです。
198
+
199
+ 新しい形式の AES 鍵の導出と追加認証データには、DB カラムとセッション Cookie の用途の区別も入ります。同じ鍵を両方に設定しても、一方の暗号文を他方として復号することはできません。旧形式には用途の区別が無いため、セッションの鍵が DB の鍵(現行・旧鍵)と同じ場合、旧形式の Cookie は読みません。
200
+
201
+ ```ruby
202
+ # config/initializers/pqc_rails.rb
203
+ PqcRails.configure do |config|
204
+ # 全レコードを再暗号化した後に false にする(既定は true)
205
+ config.accept_legacy_records = false
206
+ # 0.3.0 から更新する時だけ設定する。旧形式の Cookie の発行が止まる日時に最長のセッション有効期限を足した日時まで旧形式の Cookie を読む(既定は nil で読まない)
207
+ config.accept_legacy_cookies_until = Time.utc(2026, 12, 1)
208
+ end
209
+ ```
210
+
211
+ DB カラムに保存された暗号文は、復号せずに形式バージョン・アルゴリズムID・鍵IDを調べられます。鍵ローテーションやアルゴリズム変更の後に、旧い鍵・旧い形式のまま残っているレコードを見分けるのに使えます。
212
+
213
+ ```ruby
214
+ info = PqcRails::ActiveRecord::CiphertextInfo.parse(user.ciphertext_for(:email))
215
+ info.format_version # => 1(0.3.0 以前の形式は 0)
216
+ info.algorithm_id # => "X25519+ML-KEM-768"
217
+ info.key_id # => "2e3a"(PqcRails::CiphertextFormat.key_id(公開鍵) と同じ値)
218
+ info.legacy? # => false
219
+ ```
220
+
221
+ 暗号文のサイズは、ML-KEM-768 で増えます。DB カラムは、Rails 標準の暗号文と比べて約1,550 bytes 増えます。セッション Cookie は、暗号化前の値に対して約1,600 bytes 増えます(Base64 にする前の長さ)。増加の大半は ML-KEM-768 の暗号文(1,088 bytes)です(開発機での計測)。
222
+
223
+ 複数台のサーバーを順番に更新する場合、更新中は 0.3.0 以前の版が動いているサーバーが新しい形式の暗号文を読めません。更新が終わるまでは旧形式で書くよう設定し、全台の更新後にこの設定を削除してください。この設定の間は、期限によらず 0.3.0 以前の鍵宛の旧形式の Cookie を読みます。認証鍵を持つ新しい鍵ではこの設定で暗号文を書けず、DB と同じ鍵ではこの設定で Cookie を書けません。どちらも `PqcRails::Error` が発生します。設定の消し忘れは `rails pqc_rails:status` が報告します。
224
+
225
+ ```ruby
226
+ # config/initializers/pqc_rails.rb
227
+ PqcRails.configure do |config|
228
+ config.ciphertext_format = :v0 # 全台の更新後に削除する(既定は :v1)
229
+ end
230
+ ```
231
+
232
+ 新しい形式で暗号文を書いた後に 0.3.0 以前の版へ戻すと、その暗号文は復号できません。アルゴリズムを変更する手順は [docs/MIGRATION.md](docs/MIGRATION.md#アルゴリズムパラメータセットの変更) を参照してください。
233
+
169
234
  ## 使い方
170
235
 
171
236
  ### アルゴリズムの指定方法
@@ -199,7 +264,9 @@ PqcRails::Kem.open("Classic-McEliece-348864") do |kem|
199
264
  end
200
265
  ```
201
266
 
202
- 公開鍵サイズが大きい(348864 パラメータセットで約255KB)ため TLS ハンドシェイクのような頻繁な鍵交換には向きませんが、鍵交換の頻度が低い長期保存データの暗号化では ML-KEM が万一破られた場合のバックアップとして選択肢になります。異なる数学的困難性(符号の復号問題)に安全性の根拠を置くため、ML-KEM(格子問題)とは異なるリスクプロファイルを持ちます。
267
+ 公開鍵サイズが大きい(348864 パラメータセットで約255KB)ため、TLS ハンドシェイクのような頻繁な鍵交換には向きません。異なる数学的困難性(符号の復号問題)に安全性の根拠を置くため、ML-KEM(格子問題)とは異なるリスクプロファイルを持ちます。
268
+
269
+ ただし、ドイツ連邦情報セキュリティ庁(BSI)は 2026年10月1日、暗号解析の進展により想定より安全性の水準が大きく下がっている可能性があるとして、Classic McEliece を当面、新規の開発・新しい用途に使わないよう勧告しました([BSI の発表](https://www.bsi.bund.de/DE/Service-Navi/Presse/Alle-Meldungen-News/Meldungen/2026/Classic-McEliece_261001.html))。ML-KEM・FrodoKEM・HQC はこの影響を受けないとされています。新しく採用する場合は ML-KEM(既定)を使ってください。
203
270
 
204
271
  同様に、NIST が ML-KEM のバックアップとして選定した符号ベースKEM「HQC」も liboqs 0.16.0 以降ではデフォルトで有効化されており、生の名前(`"HQC-1"` / `"HQC-3"` / `"HQC-5"`)を渡すことで利用できます。ただしHQCはまだNIST標準化作業中(FIPS番号未確定)のため、シンボルレジストリには未登録です。`bundle install` が既定で自動ビルドする liboqs は 0.16.0([必要要件](#必要要件)参照)のため、下記の例はそのまま動作します。`--skip-liboqs` で `OQS_ENABLE_KEM_HQC` を無効化した古いバージョン・カスタムビルドの liboqs を指定した場合は利用できません。
205
272
 
@@ -277,14 +344,26 @@ sig.length_secret_key # => 2560
277
344
  sig.length_signature # => 2420(最大長。実際の署名はこれより短いことがあります)
278
345
  ```
279
346
 
347
+ 署名を保存・送信する用途では、サイズが選択の目安になります。
348
+
349
+ | アルゴリズム | 公開鍵 | 署名 | NIST セキュリティレベル |
350
+ | --- | --- | --- | --- |
351
+ | ML-DSA-44 | 1,312 バイト | 2,420 バイト | 2 |
352
+ | ML-DSA-65 | 1,952 バイト | 3,309 バイト | 3 |
353
+ | ML-DSA-87 | 2,592 バイト | 4,627 バイト | 5 |
354
+
355
+ 値は FIPS 204 によります。ハッシュ関数だけに安全性の根拠を置く SLH-DSA(FIPS 205)は、署名が 7,856〜49,856 バイトとさらに大きく、Cookie や HTTP ヘッダーに載せる用途には向きません(レジストリには登録していません)。
356
+
280
357
  ## API の安定性
281
358
 
282
- pqc_rails は現在 `0.y.z` 版(`0.2.0`)で開発中です。将来 `1.0` を名乗る時点で SemVer の対象にする
359
+ pqc_rails は現在 `0.y.z` 版で開発中です。将来 `1.0` を名乗る時点で SemVer の対象にする
283
360
  つもりのクラス・メソッドを、この時点で明確にしておきます。
284
361
 
285
362
  **安定した公開 API**(1.0 以降は SemVer の対象にする想定)
286
363
 
287
- - `PqcRails.configure` / `PqcRails::Configuration#liboqs_path`
364
+ - `PqcRails.configure` / `PqcRails.liboqs_version` / `PqcRails::Configuration#liboqs_path` / `#ciphertext_format` / `#accept_legacy_records` / `#accept_legacy_cookies_until`
365
+ - 鍵の生成と保存形式:`PqcRails::HybridKem.open(アルゴリズム) { |hybrid| hybrid.generate_keypair }` と `PqcRails::KeySource.encode` / `.decode`([docs/MIGRATION.md](docs/MIGRATION.md) の鍵ローテーションの手順で使うもの)
366
+ - `PqcRails::ActiveRecord::CiphertextInfo.parse`(`#format_version` / `#algorithm_id` / `#key_id` / `#pqc?` / `#legacy?`)、`PqcRails::Cipher#algorithm_id`、`PqcRails::CiphertextFormat.key_id`
288
367
  - `config.session_store :pqc_cookie_store`(`keypair:` / `previous_keypairs:` / `pq_alg_name:` オプション含む)
289
368
  - `PqcRails::ActiveRecord::Context.install!`
290
369
  - `PqcRails::ActiveRecord::KeyProvider`(HSM 連携・ロールバック時の `previous:` スキームで使う拡張点。[docs/MIGRATION.md](docs/MIGRATION.md) 参照)
@@ -292,31 +371,41 @@ pqc_rails は現在 `0.y.z` 版(`0.2.0`)で開発中です。将来 `1.0`
292
371
  - `PqcRails::KeySource::EnvCredentials`、および `#current_keypair` / `#previous_keypairs` の2メソッドを実装する独自鍵ソースという拡張契約(HSM/PKCS#11連携用)
293
372
  - `PqcRails::Kem` / `PqcRails::Sig`(アルゴリズムプリミティブ。本 README「使い方」に記載の全メソッド)
294
373
  - `PqcRails::Algorithms::UnknownAlgorithmError`
295
- - `PqcRails::Error` / `PqcRails::MissingKeyError`
374
+ - `PqcRails::Error` / `PqcRails::MissingKeyError` / `PqcRails::MissingAuthenticationKeyError`
375
+ - `decryption_failed.pqc_rails` イベント(payload の `target` / `error`)
296
376
  - `rails generate pqc_rails:install`
297
377
  - `rails pqc_rails:status` / `PqcRails::StatusCheck.run`(戻り値の`Result`が持つ`name` / `ok` / `detail`)
298
378
  - 環境変数・credentials キー名(`PQC_SESSION_KEY` / `PQC_SESSION_PREVIOUS_KEYS` / `PQC_RECORD_KEY` / `PQC_RECORD_PREVIOUS_KEYS` 等、本 README「設定」に記載のもの)
299
379
 
300
380
  **内部実装**(予告なく変更されうるため、直接使わないでください)
301
381
 
302
- - `PqcRails::HybridKem` / `PqcRails::DhKem` / `PqcRails::EnvelopeCipher` / `PqcRails::BlobPacking`(`Cipher` / セッションストアが内部で使うKEM-DEM構成の実装詳細)
382
+ - `PqcRails::HybridKem`(`.open` と `#generate_keypair` を除く)/ `PqcRails::DhKem` / `PqcRails::EnvelopeCipher` / `PqcRails::BlobPacking`(`Cipher` / セッションストアが内部で使うKEM-DEM構成の実装詳細)
303
383
  - `PqcRails::Session::Encryptor` / `PqcRails::Session::KeyManager`
304
384
  - `PqcRails::Algorithms` の直接呼び出し(`.find_kem` 等)。シンボル指定(`:ml_kem_512` 等)を `Kem.new` / `Sig.new` に渡した「結果」は安定していますが、`Algorithms` モジュール自体のメソッドは内部実装です
305
- - `PqcRails::KeySource` のモジュール関数(`.fetch` / `.fetch!` / `.fetch_keypair!`)。`EnvCredentials` クラス自体は上記の通り安定した拡張点です
385
+ - `PqcRails::KeySource` のモジュール関数のうち `.fetch` / `.fetch!` / `.fetch_keypair!`。`EnvCredentials` クラス自体は上記の通り安定した拡張点です
306
386
 
307
387
  ## エラーハンドリング
308
388
 
309
389
  - 未知のアルゴリズム名や、liboqs が有効化していないアルゴリズムを指定すると `PqcRails::Error` が発生します。
310
390
  - `encapsulate` / `decapsulate` / `sign` に渡すバイト列の長さが不正な場合は `ArgumentError` が発生します。
311
391
  - `free` 済みのインスタンスに対する操作は `PqcRails::Error` が発生します。
312
- - `PqcRails::Sig#verify` は、署名が無効な場合でも例外を発生させず `false` を返します(KEM とは異なる設計です)。
392
+ - `PqcRails::Sig#verify` は、署名が無効な場合でも例外を発生させず `false` を返します(KEM とは異なる設計です)。署名が文字列でない値(`nil` など)の場合も `false` を返します。
393
+ - `PqcRails::Sig#sign` / `#verify` に渡すメッセージが文字列でない場合は `ArgumentError` が発生します。
313
394
  - `ActiveRecord::Encryption` で復号に失敗した場合は `ActiveRecord::Encryption::Errors::Decryption` が発生します。
314
395
  - セッション Cookie が不正・改竄されている場合は空のセッションとして扱います(クラッシュしません)。
315
396
  - 環境変数にも Rails credentials にも鍵が設定されていない場合、`PqcRails::MissingKeyError`(`PqcRails::Error` のサブクラス)が発生します。`rails generate pqc_rails:install` を実行済みか確認してください。
316
397
 
398
+ DB カラム・セッション Cookie の復号に失敗すると、`ActiveSupport::Notifications` の `decryption_failed.pqc_rails` イベントを発行します。payload は `target`(`:record` は DB カラム、`:session` はセッション Cookie)と `error`(例外のクラス名)で、値・鍵・例外のメッセージは含みません。鍵の設定の誤りや、改ざんされた値を見つけるのに使えます。`previous:` で指定した旧方式の暗号文を読むときのように、ActiveRecord が復号方式を順に試す過程の失敗では発行しません。
399
+
400
+ ```ruby
401
+ ActiveSupport::Notifications.subscribe("decryption_failed.pqc_rails") do |event|
402
+ Rails.logger.warn("pqc_rails decryption failed: #{event.payload[:target]} #{event.payload[:error]}")
403
+ end
404
+ ```
405
+
317
406
  ## ステータス確認
318
407
 
319
- `rails pqc_rails:status` で、鍵の設定状況・セッションストア・`ActiveRecord::Encryption` の設定が実際に有効になっているかを確認できます。
408
+ `rails pqc_rails:status` で、鍵の設定状況・セッションストア・`ActiveRecord::Encryption` の設定が実際に有効になっているかを確認できます。あわせて、`encrypts` で暗号化している属性の一覧と、DB・セッションが新しく暗号化する時のアルゴリズムを表示します。
320
409
 
321
410
  ```
322
411
  $ rails pqc_rails:status
@@ -327,6 +416,9 @@ $ rails pqc_rails:status
327
416
  ✅ DBレコード旧鍵 (PQC_RECORD_PREVIOUS_KEYS): 未設定(ローテーション中ではありません)
328
417
  ✅ セッションストア: :pqc_cookie_store が有効です
329
418
  ❌ ActiveRecord::Encryption: PqcRails::ActiveRecord::Context.install! が呼ばれていません
419
+ ✅ 暗号化している属性: Patient(diagnosis, note), User(phone)
420
+ ✅ 使うアルゴリズム: DB: pqc_railsを使っていません、セッション: X25519+ML-KEM-768
421
+ 暗号文の件数・鍵とアルゴリズムごとの内訳・CBOM は、pqc_rails Pro の rails pqc_rails:pro:inventory で出せます
330
422
  ```
331
423
 
332
424
  鍵の未設定(`MissingKeyError`)は実際に暗号化・復号が走るまで発覚しない遅延的なエラーです。デプロイ前や導入直後にこのコマンドで能動的に確認することで、本番トラフィックで初めて気づくという事態を避けられます。いずれかのチェックが失敗している場合、終了コードは1になります(CI・デプロイフックへの組み込みにも使えます)。
@@ -335,7 +427,7 @@ $ rails pqc_rails:status
335
427
 
336
428
  PQC 移行は「計画は立てたが実装が進まない」という組織が多い分野です([DigiCert の2026年グローバル調査](https://www.digicert.com/news/quantum-readiness-gap-a-digicert-study-on-quantum-safe-encryption)では、移行計画の策定率87%に対し実導入率は7%に留まるという結果が示されています)。導入初回に発生しやすいつまずきをここにまとめます。迷ったらまず [`rails pqc_rails:status`](#ステータス確認) を実行してください。
337
429
 
338
- - **`LoadError: Could not open library 'liboqs.dylib'` のようなエラーが出る**: liboqs の共有ライブラリが見つかっていません。通常は `bundle install` 時に自動ビルドされますが、`--skip-liboqs` でビルドをスキップした場合や、ビルド自体が失敗していた場合([必要要件](#必要要件)の CMake・Cコンパイラが揃っているか確認してください)に発生します。既存の liboqs を使う場合は、環境変数 `LIBOQS_PATH` または `config.liboqs_path`([liboqs ライブラリパス](#liboqs-ライブラリパス)参照)で明示的にパスを指定してください。
430
+ - **`LoadError: Could not open library 'liboqs.dylib'` のようなエラーが出る**: liboqs の共有ライブラリが見つかっていません。通常はビルド済みの gem に同梱されているか、`bundle install` 時に自動ビルドされますが、`--skip-liboqs` でビルドをスキップした場合や、ビルド自体が失敗していた場合(ビルド済みの gem が無い環境では、[必要要件](#必要要件)の CMake・Cコンパイラが揃っているか確認してください)に発生します。既存の liboqs を使う場合は、環境変数 `LIBOQS_PATH` または `config.liboqs_path`([liboqs ライブラリパス](#liboqs-ライブラリパス)参照)で明示的にパスを指定してください。
339
431
  - **`PqcRails::Algorithms::UnknownAlgorithmError` が発生する**: シンボル指定(`:ml_kem_512` 等)がレジストリに未登録の場合に発生します。[現在レジストリに登録済みのアルゴリズム](#アルゴリズムの指定方法)の一覧を確認するか、liboqs の生の名前(`"ML-KEM-512"` 等)で直接指定してください。生の名前でも `PqcRails::Error` が発生する場合は、liboqs 側のビルド設定でそのアルゴリズムが有効化されていない可能性があります。
340
432
  - **`config.session_store :pqc_cookie_store` に切り替えたら全ユーザーがログアウトされた**: 想定通りの挙動です。暗号方式が変わるため、切り替え前に発行された既存セッションは復号できません([セッション暗号化](#セッション暗号化)参照)。メンテナンスウィンドウを設けるか、ユーザーへの事前告知を検討してください。
341
433
  - **`ActiveRecord::Encryption::Context.install!` 後、既存データの復号に失敗する**: pqc_rails 導入前に Rails 標準の `ActiveRecord::Encryption` で暗号化されたデータは、切り替え後はデフォルトでは復号できません。段階的に移行する方法は [docs/MIGRATION.md](docs/MIGRATION.md) を参照してください。
@@ -354,10 +446,12 @@ Puma のようなマルチスレッド型アプリケーションサーバーは
354
446
 
355
447
  ## 動作確認済み環境
356
448
 
357
- - Ruby 3.2 / 3.3 / 3.4
449
+ - Ruby 3.3 / 3.4 / 4.0
358
450
  - Rails 7.1 / 8.1
359
451
  - liboqs 0.16.0 / 0.15.0
360
452
 
453
+ ビルド済みの gem は、[CI](.github/workflows/native-gems.yml) で、対応する各環境のコンパイラの入っていない Ruby 3.3 / 4.0 にインストールし、ML-KEM の暗号化・復号が通ることを確かめています。
454
+
361
455
  [CI](.github/workflows/test.yml) では、上記の Ruby × Rails × liboqs の組み合わせ(liboqs 0.15.0 は Ruby 3.4 + Rails 8.1 との組み合わせのみ)を push・PR のたびにマトリクスで継続的に検証しています。CIには別途 `extension-build` ジョブがあり、`bundle install` によるliboqsの自動ビルド〜動作(KEM 往復)までを Linux 上で継続的に検証しています。
362
456
 
363
457
  ## 開発
data/Rakefile CHANGED
@@ -9,4 +9,10 @@ namespace :vendor do
9
9
  require_relative "ext/pqc_rails/vendor_liboqs"
10
10
  PqcRails::VendorLiboqs.run
11
11
  end
12
+
13
+ desc "Verify that the vendored liboqs source matches the pinned upstream commit (DIR= to check another directory)"
14
+ task :verify do
15
+ require_relative "ext/pqc_rails/vendor_liboqs"
16
+ PqcRails::VendorLiboqs.verify(ENV.fetch("DIR", PqcRails::VendorLiboqs::VENDOR_DIR))
17
+ end
12
18
  end
@@ -12,8 +12,8 @@
12
12
  | **暗号利用場面** | セッションCookieの暗号化(`PqcCookieStore` 経由)。ActiveRecordモデルの特定カラムの暗号化(`encrypts` 宣言経由) |
13
13
  | **暗号用途** | セッション: ユーザーとの通信内容(セッションデータ)の保護。DBカラム: お客様情報を安全に保存するため |
14
14
  | **暗号実装箇所** | 自組織外から提供された製品(gem `pqc_rails`)。内部では [liboqs](https://github.com/open-quantum-safe/liboqs) へのFFIバインディングを経由 |
15
- | **利用アルゴリズム** | 鍵交換: ML-KEM(NIST FIPS 203) + X25519のハイブリッド構成(`HybridKem`)。データ本体: AES-256-GCM(`EnvelopeCipher`)。デフォルトパラメータセットは ML-KEM-768 |
16
- | **利用している暗号鍵長** | ML-KEM-768: 公開鍵1184バイト / 秘密鍵2400バイト / 暗号文1088バイト / 共有鍵32バイト。AES-256-GCM: 256ビット鍵 |
15
+ | **利用アルゴリズム** | 鍵交換: ML-KEM(NIST FIPS 203) + X25519のハイブリッド構成(`HybridKem`)。データ本体: AES-256-GCM(`EnvelopeCipher`)。AES鍵はKEMの共有鍵と認証鍵からHKDF-SHA256で導きます(作成元の認証)。デフォルトパラメータセットは ML-KEM-768 |
16
+ | **利用している暗号鍵長** | ML-KEM-768: 公開鍵1184バイト / 秘密鍵2400バイト / 暗号文1088バイト / 共有鍵32バイト。認証鍵: 32バイト(鍵ペアごとのランダムな共通鍵)。AES-256-GCM: 256ビット鍵 |
17
17
  | **暗号鍵の更新頻度** | 複数世代の鍵ローテーションに対応しています。セッション・DBカラムとも新旧鍵を併用しながら切り替えられます。手順は[docs/MIGRATION.md](MIGRATION.md#鍵ローテーションpqc_rails鍵世代間)を参照してください |
18
18
  | **暗号鍵管理方法** | Rails credentials(`pqc_session_key` / `pqc_record_key`)、または環境変数(`PQC_SESSION_KEY` / `PQC_RECORD_KEY`)。セッション用とDB用で鍵は分離されています。HSM・クラウドKMSとの統合は現時点で未対応です |
19
19
  | **長期保護データとの接点有無** | セッションCookieは通常ログインセッション程度の短期間ですが、DBカラムに保存するデータの保護期間はアプリケーションの用途に依存します。医療記録・法務文書・金融取引データ等、長期保護が必要なデータをこの経路で扱う場合は、[THREAT_MODEL.md](THREAT_MODEL.md#どのデータが危険か) のX+Y>Zフレームワークで緊急度を評価してください |
@@ -28,6 +28,8 @@
28
28
 
29
29
  これらはコード解析ツール(`grep -rn "encrypts \|pqc_cookie_store\|Context.install"` 等)で機械的に検出可能です。
30
30
 
31
+ `rails pqc_rails:status` は、アプリケーションを起動した状態で、`encrypts` で暗号化している属性の一覧と、DB・セッションが新しく暗号化する時のアルゴリズム(例: `X25519+ML-KEM-768`)を表示します。コードの検索では分からない、実際に有効になっている設定を確かめられます。
32
+
31
33
  ## 自組織用の記入欄(空欄テンプレート)
32
34
 
33
35
  | 項目 | 記入欄 |