Skip to content

armgit / ente

Public Imported from GitHub
0

πŸ’š End-to-end encrypted cloud for everything.

Add post-quantum encryption to Cast pairing

Manav Rathi01a0ee142fa5
diff --git a/apple/apps/cast/Cast/Services/CastPairingService.swift b/apple/apps/cast/Cast/Services/CastPairingService.swift
index 030d185a69..d9883e5afa 100644
--- a/apple/apps/cast/Cast/Services/CastPairingService.swift
+++ b/apple/apps/cast/Cast/Services/CastPairingService.swift
@@ -68,7 +68,10 @@ class RealCastPairingService {
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
- let requestBody = ["publicKey": receiver.publicKey()]
+ let requestBody = [
+ "publicKey": receiver.publicKey(),
+ "pqPublicKey": receiver.pqPublicKey(),
+ ]
request.httpBody = try JSONSerialization.data(withJSONObject: requestBody)
let (data, response) = try await URLSession.shared.data(for: request)
diff --git a/mobile/apps/photos/lib/gateways/cast/cast_gateway.dart b/mobile/apps/photos/lib/gateways/cast/cast_gateway.dart
index 0e43cf9c6a..eb172516e0 100644
--- a/mobile/apps/photos/lib/gateways/cast/cast_gateway.dart
+++ b/mobile/apps/photos/lib/gateways/cast/cast_gateway.dart
@@ -31,10 +31,15 @@ class CastGateway {
CastGateway(this._enteDio);
- Future<String?> getPublicKey(String deviceCode) async {
+ Future<({String publicKey, String? pqPublicKey})?> getPublicKeys(
+ String deviceCode,
+ ) async {
try {
final response = await _enteDio.get("/cast/device-info/$deviceCode");
- return response.data["publicKey"];
+ return (
+ publicKey: response.data["publicKey"] as String,
+ pqPublicKey: response.data["pqPublicKey"] as String?,
+ );
} catch (e) {
if (e is DioException && e.response != null) {
if (e.response!.statusCode == 404) {
diff --git a/mobile/apps/photos/lib/services/auto_cast_service.dart b/mobile/apps/photos/lib/services/auto_cast_service.dart
index e5fd02c73d..caee946473 100644
--- a/mobile/apps/photos/lib/services/auto_cast_service.dart
+++ b/mobile/apps/photos/lib/services/auto_cast_service.dart
@@ -5,7 +5,11 @@ import "package:photos/models/collection/collection.dart";
import "package:photos/src/rust/api/cast_api.dart";
typedef CastPayloadEncoder =
- PreparedCastPayload Function(Collection collection, String publicKey);
+ PreparedCastPayload Function(
+ Collection collection,
+ String publicKey,
+ String? pqPublicKey,
+ );
class AutoCastDeviceNotFoundException implements Exception {
const AutoCastDeviceNotFoundException();
@@ -36,11 +40,15 @@ class AutoCastService {
collectionID: collection.id,
);
try {
- final publicKey = await _gateway.getPublicKey(code);
- if (publicKey == null) {
+ final publicKeys = await _gateway.getPublicKeys(code);
+ if (publicKeys == null) {
throw const AutoCastDeviceNotFoundException();
}
- final prepared = _encodePayload(collection, publicKey);
+ final prepared = _encodePayload(
+ collection,
+ publicKeys.publicKey,
+ publicKeys.pqPublicKey,
+ );
final deviceID = await _gateway.publishCastPayload(
code,
prepared.encryptedPayload,
diff --git a/mobile/apps/photos/lib/services/collections_service.dart b/mobile/apps/photos/lib/services/collections_service.dart
index 9836b4d2d9..6fdbe219e1 100644
--- a/mobile/apps/photos/lib/services/collections_service.dart
+++ b/mobile/apps/photos/lib/services/collections_service.dart
@@ -793,9 +793,11 @@ class CollectionsService {
PreparedCastPayload prepareCastPayloadForCollection(
Collection collection,
String publicKey,
+ String? pqPublicKey,
) {
return prepareCastPayload(
publicKey: publicKey,
+ pqPublicKey: pqPublicKey,
collectionId: collection.id,
collectionKey: CryptoUtil.bin2base64(getCollectionKey(collection.id)),
);
diff --git a/mobile/apps/photos/lib/ui/cast/pair_with_code.dart b/mobile/apps/photos/lib/ui/cast/pair_with_code.dart
index 2ed4ef8194..117baa2ec6 100644
--- a/mobile/apps/photos/lib/ui/cast/pair_with_code.dart
+++ b/mobile/apps/photos/lib/ui/cast/pair_with_code.dart
@@ -23,13 +23,14 @@ Future<void> _pairWithCode(
if (!flagService.enableMultiCast) {
await gw.revokeAllTokens();
}
- final publicKey = await gw.getPublicKey(code);
- if (publicKey == null) {
+ final publicKeys = await gw.getPublicKeys(code);
+ if (publicKeys == null) {
throw const _DeviceNotFoundException();
}
final prepared = collectionsService.prepareCastPayloadForCollection(
collection,
- publicKey,
+ publicKeys.publicKey,
+ publicKeys.pqPublicKey,
);
await gw.publishCastPayload(
code,
diff --git a/mobile/apps/photos/test/services/auto_cast_service_test.dart b/mobile/apps/photos/test/services/auto_cast_service_test.dart
index 4064b05606..398711b332 100644
--- a/mobile/apps/photos/test/services/auto_cast_service_test.dart
+++ b/mobile/apps/photos/test/services/auto_cast_service_test.dart
@@ -14,7 +14,7 @@ void main() {
final service = AutoCastService(
transport: transport,
gateway: gateway,
- encodePayload: (_, _) => const PreparedCastPayload(
+ encodePayload: (_, _, _) => const PreparedCastPayload(
castToken: "cast-token",
encryptedPayload: "encrypted-payload",
),
@@ -54,8 +54,10 @@ class _FakeCastGateway extends Fake implements CastGateway {
Future<void>? revokeFuture;
@override
- Future<String?> getPublicKey(String deviceCode) async {
- return "public-key";
+ Future<({String publicKey, String? pqPublicKey})?> getPublicKeys(
+ String deviceCode,
+ ) async {
+ return (publicKey: "public-key", pqPublicKey: "pq-public-key");
}
@override
diff --git a/rust/Cargo.lock b/rust/Cargo.lock
index 3d29ca07d5..4de8f73b5c 100644
--- a/rust/Cargo.lock
+++ b/rust/Cargo.lock
@@ -43,6 +43,16 @@ dependencies = [
"generic-array",
]
+[[package]]
+name = "aead"
+version = "0.6.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1973cfbc1a2daf9cf550e74e1f088c28e7f7d8c1e1418fb6c9dc5184b7e84c99"
+dependencies = [
+ "crypto-common 0.2.2",
+ "inout 0.2.2",
+]
+
[[package]]
name = "aes"
version = "0.8.4"
@@ -50,7 +60,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b169f7a6d4742236a0a00c541b845991d0ac43e546831af1249753ab4c3aa3a0"
dependencies = [
"cfg-if",
- "cipher",
+ "cipher 0.4.4",
"cpufeatures 0.2.17",
]
@@ -806,6 +816,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cdd35008169921d80bc60d3d0ab416eecb028c4cd653352907921d95084790be"
dependencies = [
"hybrid-array",
+ "zeroize",
]
[[package]]
@@ -1054,7 +1065,7 @@ version = "0.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "26b52a9543ae338f279b96b0b9fed9c8093744685043739079ce85cd58f289a6"
dependencies = [
- "cipher",
+ "cipher 0.4.4",
]
[[package]]
@@ -1142,7 +1153,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c3613f74bd2eac03dad61bd53dbe620703d4371614fe0bc3b9f04dd36fe4e818"
dependencies = [
"cfg-if",
- "cipher",
+ "cipher 0.4.4",
"cpufeatures 0.2.17",
]
@@ -1153,10 +1164,23 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6f8d983286843e49675a4b7a2d174efe136dc93a18d69130dd18198a6c167601"
dependencies = [
"cfg-if",
+ "cipher 0.5.2",
"cpufeatures 0.3.0",
"rand_core 0.10.1",
]
+[[package]]
+name = "chacha20poly1305"
+version = "0.11.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9b89e1c441e926b9c82a8d023f6e1b7ae0adcfaa7d621814e4d60789bac751cb"
+dependencies = [
+ "aead 0.6.1",
+ "chacha20 0.10.0",
+ "cipher 0.5.2",
+ "poly1305 0.9.1",
+]
+
[[package]]
name = "chrono"
version = "0.4.44"
@@ -1178,10 +1202,21 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad"
dependencies = [
"crypto-common 0.1.7",
- "inout",
+ "inout 0.1.4",
"zeroize",
]
+[[package]]
+name = "cipher"
+version = "0.5.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e8cf2a2c93cd704877c0858356ed03480ff301ee950b43f1cbe4573b088bfa6c"
+dependencies = [
+ "block-buffer 0.12.0",
+ "crypto-common 0.2.2",
+ "inout 0.2.2",
+]
+
[[package]]
name = "clang-sys"
version = "1.8.1"
@@ -1579,11 +1614,12 @@ dependencies = [
[[package]]
name = "crypto-common"
-version = "0.2.1"
+version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "77727bb15fa921304124b128af125e7e3b968275d1b108b379190264f4423710"
+checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453"
dependencies = [
"hybrid-array",
+ "rand_core 0.10.1",
]
[[package]]
@@ -1592,10 +1628,10 @@ version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b9d6cf87adf719ddf43a805e92c6870a531aedda35ff640442cbaf8674e141e1"
dependencies = [
- "aead",
- "cipher",
+ "aead 0.5.2",
+ "cipher 0.4.4",
"generic-array",
- "poly1305",
+ "poly1305 0.8.0",
"salsa20",
"subtle",
"zeroize",
@@ -1607,10 +1643,10 @@ version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9a6419214057ad50a13efccb3ad7714b86b848e3a5aa7b6cf5a3ff07edf387eb"
dependencies = [
- "aead",
+ "aead 0.5.2",
"chacha20 0.9.1",
"getrandom 0.2.17",
- "poly1305",
+ "poly1305 0.8.0",
"rand_core 0.6.4",
"subtle",
]
@@ -2020,8 +2056,9 @@ checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2"
dependencies = [
"block-buffer 0.12.0",
"const-oid",
- "crypto-common 0.2.1",
+ "crypto-common 0.2.2",
"ctutils",
+ "zeroize",
]
[[package]]
@@ -2433,6 +2470,7 @@ dependencies = [
"futures-core",
"getrandom 0.4.3",
"gloo-timers",
+ "hpke",
"log",
"md-5 0.11.0",
"mockito",
@@ -2444,6 +2482,7 @@ dependencies = [
"subtle",
"thiserror 2.0.18",
"tokio",
+ "x-wing",
"x25519-dalek",
"zeroize",
]
@@ -3832,6 +3871,29 @@ version = "3.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "62adaabb884c94955b19907d60019f4e145d091c75345379e70d1ee696f7854f"
+[[package]]
+name = "hpke"
+version = "0.14.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "dd5130e119706b4d8c2180da6126f7e60b6c38c2d340d539219f57051f0a7af7"
+dependencies = [
+ "aead 0.6.1",
+ "chacha20poly1305",
+ "getrandom 0.4.3",
+ "hkdf 0.13.0",
+ "hybrid-array",
+ "ml-kem",
+ "rand_core 0.10.1",
+ "sha2 0.11.0",
+ "sha3 0.12.0",
+ "shake",
+ "subtle",
+ "turboshake",
+ "x-wing",
+ "x25519-dalek",
+ "zeroize",
+]
+
[[package]]
name = "html-escape"
version = "0.2.13"
@@ -3904,11 +3966,13 @@ checksum = "135b12329e5e3ce057a9f972339ea52bc954fe1e9358ef27f95e89716fbc5424"
[[package]]
name = "hybrid-array"
-version = "0.4.12"
+version = "0.4.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "9155a582abd142abc056962c29e3ce5ff2ad5469f4246b537ed42c5deba857da"
+checksum = "707114b52a152fa7bdb290cd7cd5912d9467273b6d74e21b8d81aca1f8533f6b"
dependencies = [
+ "ctutils",
"typenum",
+ "zeroize",
]
[[package]]
@@ -4673,6 +4737,15 @@ dependencies = [
"generic-array",
]
+[[package]]
+name = "inout"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4250ce6452e92010fdf7268ccc5d14faa80bb12fc741938534c58f16804e03c7"
+dependencies = [
+ "hybrid-array",
+]
+
[[package]]
name = "interpolate_name"
version = "0.2.4"
@@ -5121,6 +5194,26 @@ dependencies = [
"mutate_once",
]
+[[package]]
+name = "keccak"
+version = "0.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ffd9697dc4a9a62e2da93389f34400b77a28f0287711263cabb203b3ccb9c0e4"
+dependencies = [
+ "cfg-if",
+ "cpufeatures 0.3.0",
+]
+
+[[package]]
+name = "kem"
+version = "0.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "01737161ba802849cfd486b5bd209d38ba4943494c249a8126005170c7621edd"
+dependencies = [
+ "crypto-common 0.2.2",
+ "rand_core 0.10.1",
+]
+
[[package]]
name = "keyboard-types"
version = "0.7.0"
@@ -5549,6 +5642,20 @@ dependencies = [
"windows-sys 0.61.2",
]
+[[package]]
+name = "ml-kem"
+version = "0.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5e15f3e5b957493873e396a66914e83e616b6afe335cdef7efe5c6e1216aba66"
+dependencies = [
+ "hybrid-array",
+ "kem",
+ "module-lattice",
+ "rand_core 0.10.1",
+ "sha3 0.11.0",
+ "zeroize",
+]
+
[[package]]
name = "mockito"
version = "1.7.2"
@@ -5574,6 +5681,18 @@ dependencies = [
"tokio",
]
+[[package]]
+name = "module-lattice"
+version = "0.2.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0c61b87c9683ab7cb1c6871d261ad5479b6b10ceb52c4352aaca3b5d35a8febe"
+dependencies = [
+ "ctutils",
+ "hybrid-array",
+ "num-traits",
+ "zeroize",
+]
+
[[package]]
name = "moxcms"
version = "0.8.1"
@@ -6667,7 +6786,17 @@ checksum = "8159bd90725d2df49889a078b54f4f79e87f1f8a8444194cdca81d38f5393abf"
dependencies = [
"cpufeatures 0.2.17",
"opaque-debug",
- "universal-hash",
+ "universal-hash 0.5.1",
+]
+
+[[package]]
+name = "poly1305"
+version = "0.9.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6e2d0073b297041425c7c3df6eb4792d598a15323fe63346852b092eca02904c"
+dependencies = [
+ "cpufeatures 0.3.0",
+ "universal-hash 0.6.1",
]
[[package]]
@@ -7678,7 +7807,7 @@ version = "0.10.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "97a22f5af31f73a954c10289c93e8a50cc23d971e80ee446f1f6f7137a088213"
dependencies = [
- "cipher",
+ "cipher 0.4.4",
]
[[package]]
@@ -8188,6 +8317,38 @@ dependencies = [
"digest 0.11.3",
]
+[[package]]
+name = "sha3"
+version = "0.11.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "be176f1a57ce4e3d31c1a166222d9768de5954f811601fb7ca06fc8203905ce1"
+dependencies = [
+ "digest 0.11.3",
+ "keccak",
+]
+
+[[package]]
+name = "sha3"
+version = "0.12.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bc9bad02c26382724b2d2692c6f179285e4b54eeecd7968f52a50059c3c11759"
+dependencies = [
+ "digest 0.11.3",
+ "keccak",
+ "sponge-cursor",
+]
+
+[[package]]
+name = "shake"
+version = "0.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "09057cb2149ad4cbd2da1e26b351f9a4c354219421229c69c3063e6f61947c4a"
+dependencies = [
+ "digest 0.11.3",
+ "keccak",
+ "sponge-cursor",
+]
+
[[package]]
name = "shell-words"
version = "1.1.1"
@@ -8369,6 +8530,15 @@ dependencies = [
"system-deps",
]
+[[package]]
+name = "sponge-cursor"
+version = "0.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3a0219bd7d979d58245a4f41f695e1ac9f8befdffadd7f61f1bae9e39abc6620"
+dependencies = [
+ "zeroize",
+]
+
[[package]]
name = "sqlite-wasm-rs"
version = "0.5.2"
@@ -8506,7 +8676,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4b5f622c2d21b826b3501f4c620ccc4696e4a09a6b51727fcb21036dec87c101"
dependencies = [
"crypto-bigint",
- "crypto-common 0.2.1",
+ "crypto-common 0.2.2",
"digest 0.11.3",
"subtle",
]
@@ -9120,7 +9290,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"
dependencies = [
"fastrand",
- "getrandom 0.3.4",
+ "getrandom 0.4.3",
"once_cell",
"rustix",
"windows-sys 0.61.2",
@@ -9660,6 +9830,17 @@ version = "0.25.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d2df906b07856748fa3f6e0ad0cbaa047052d4a7dd609e231c4f72cee8c36f31"
+[[package]]
+name = "turboshake"
+version = "0.7.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f892c6904b0bd5a9241eac848347abcbbbd2b9f3892bad23ac3e6efab8d6f06a"
+dependencies = [
+ "digest 0.11.3",
+ "keccak",
+ "sponge-cursor",
+]
+
[[package]]
name = "typeid"
version = "1.0.3"
@@ -9899,6 +10080,16 @@ dependencies = [
"subtle",
]
+[[package]]
+name = "universal-hash"
+version = "0.6.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f4987bdc12753382e0bec4a65c50738ffaabc998b9cdd1f952fb5f39b0048a96"
+dependencies = [
+ "crypto-common 0.2.2",
+ "ctutils",
+]
+
[[package]]
name = "unsafe-libyaml"
version = "0.2.11"
@@ -10991,6 +11182,20 @@ dependencies = [
"x11-dl",
]
+[[package]]
+name = "x-wing"
+version = "0.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b51507b887016c3925c84591108dadb8c099f776eb04fec6a60ae3519fee856f"
+dependencies = [
+ "kem",
+ "ml-kem",
+ "sha3 0.12.0",
+ "shake",
+ "x25519-dalek",
+ "zeroize",
+]
+
[[package]]
name = "x11"
version = "2.21.0"
diff --git a/rust/bindings/frb/photos/src/api/cast_api.rs b/rust/bindings/frb/photos/src/api/cast_api.rs
index a1e0e0f103..205659d8d9 100644
--- a/rust/bindings/frb/photos/src/api/cast_api.rs
+++ b/rust/bindings/frb/photos/src/api/cast_api.rs
@@ -7,11 +7,17 @@ pub struct PreparedCastPayload {
#[flutter_rust_bridge::frb(sync)]
pub fn prepare_cast_payload(
public_key: String,
+ pq_public_key: Option<String>,
collection_id: i64,
collection_key: String,
) -> Result<PreparedCastPayload, String> {
- let prepared = ente_cast::prepare_payload(&public_key, collection_id, &collection_key)
- .map_err(|error| error.to_string())?;
+ let prepared = ente_cast::prepare_payload(
+ &public_key,
+ pq_public_key.as_deref(),
+ collection_id,
+ &collection_key,
+ )
+ .map_err(|error| error.to_string())?;
Ok(PreparedCastPayload {
cast_token: prepared.cast_token,
encrypted_payload: prepared.encrypted_payload,
diff --git a/rust/bindings/uniffi/cast/src/lib.rs b/rust/bindings/uniffi/cast/src/lib.rs
index 2a104485ee..163cd62373 100644
--- a/rust/bindings/uniffi/cast/src/lib.rs
+++ b/rust/bindings/uniffi/cast/src/lib.rs
@@ -60,6 +60,10 @@ impl CastReceiver {
self.inner.public_key()
}
+ pub fn pq_public_key(&self) -> String {
+ self.inner.pq_public_key()
+ }
+
pub fn open_payload(&self, encrypted_payload: String) -> Result<CastPayload, CastCryptoError> {
Ok(self.inner.open_payload(&encrypted_payload)?.into())
}
diff --git a/rust/bindings/wasm/cast/src/lib.rs b/rust/bindings/wasm/cast/src/lib.rs
index f4f033287a..f2f631e41e 100644
--- a/rust/bindings/wasm/cast/src/lib.rs
+++ b/rust/bindings/wasm/cast/src/lib.rs
@@ -28,6 +28,11 @@ impl CastReceiver {
self.inner.public_key()
}
+ #[wasm_bindgen(getter, js_name = pqPublicKey)]
+ pub fn pq_public_key(&self) -> String {
+ self.inner.pq_public_key()
+ }
+
#[wasm_bindgen(js_name = openPayload)]
pub fn open_payload(&self, encrypted_payload: &str) -> Result<CastPayload, JsError> {
Ok(self.inner.open_payload(encrypted_payload)?.into())
@@ -90,8 +95,15 @@ impl PreparedCastPayload {
#[wasm_bindgen(js_name = preparePayload)]
pub fn prepare_payload(
public_key: &str,
+ pq_public_key: Option<String>,
collection_id: i64,
collection_key: &str,
) -> Result<PreparedCastPayload, JsError> {
- Ok(ente_cast::prepare_payload(public_key, collection_id, collection_key)?.into())
+ Ok(ente_cast::prepare_payload(
+ public_key,
+ pq_public_key.as_deref(),
+ collection_id,
+ collection_key,
+ )?
+ .into())
}
diff --git a/rust/crates/cast/src/lib.rs b/rust/crates/cast/src/lib.rs
index ff42f09af8..3abaaaf7f1 100644
--- a/rust/crates/cast/src/lib.rs
+++ b/rust/crates/cast/src/lib.rs
@@ -1,4 +1,4 @@
-use ente_core::crypto::{self, PublicKey, SecretKey};
+use ente_core::crypto::{self, PublicKey, SecretKey, hpke};
use ente_core::{b64, id};
use serde::{Deserialize, Serialize};
use thiserror::Error;
@@ -17,6 +17,8 @@ pub enum Error {
pub type Result<T> = std::result::Result<T, Error>;
+const HPKE_INFO: &[u8] = b"ente-cast";
+
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CastPayload {
@@ -34,12 +36,14 @@ pub struct PreparedCastPayload {
pub struct ReceiverCredentials {
secret_key: SecretKey,
+ pq_secret_key: hpke::SecretKey,
}
impl ReceiverCredentials {
pub fn generate() -> Self {
Self {
secret_key: SecretKey::generate(),
+ pq_secret_key: hpke::SecretKey::generate(),
}
}
@@ -47,22 +51,29 @@ impl ReceiverCredentials {
b64::encode(self.secret_key.public_key().as_bytes())
}
+ pub fn pq_public_key(&self) -> String {
+ b64::encode(self.pq_secret_key.public_key().as_bytes())
+ }
+
pub fn open_payload(&self, encrypted_payload: &str) -> Result<CastPayload> {
let ciphertext = b64::decode(encrypted_payload)?;
- let public_key = self.secret_key.public_key();
- let plaintext = crypto::sealed::open(&ciphertext, &public_key, &self.secret_key)?;
+ let plaintext = hpke::open(&ciphertext, &self.pq_secret_key, HPKE_INFO).or_else(|_| {
+ crypto::sealed::open(&ciphertext, &self.secret_key.public_key(), &self.secret_key)
+ })?;
Ok(serde_json::from_slice(&plaintext)?)
}
}
pub fn prepare_payload(
public_key: &str,
+ pq_public_key: Option<&str>,
collection_id: i64,
collection_key: &str,
) -> Result<PreparedCastPayload> {
let cast_token = id::random("cast");
let encrypted_payload = seal_payload(
public_key,
+ pq_public_key,
&CastPayload {
collection_id,
cast_token: cast_token.clone(),
@@ -75,10 +86,20 @@ pub fn prepare_payload(
})
}
-fn seal_payload(public_key: &str, payload: &CastPayload) -> Result<String> {
- let public_key = PublicKey::try_from_slice(&b64::decode(public_key)?)?;
+fn seal_payload(
+ public_key: &str,
+ pq_public_key: Option<&str>,
+ payload: &CastPayload,
+) -> Result<String> {
let plaintext = serde_json::to_vec(payload)?;
- Ok(b64::encode(&crypto::sealed::seal(&plaintext, &public_key)?))
+ let ciphertext = if let Some(pq_public_key) = pq_public_key {
+ let public_key = hpke::PublicKey::try_from_slice(&b64::decode(pq_public_key)?)?;
+ hpke::seal(&plaintext, &public_key, HPKE_INFO)?
+ } else {
+ let public_key = PublicKey::try_from_slice(&b64::decode(public_key)?)?;
+ crypto::sealed::seal(&plaintext, &public_key)?
+ };
+ Ok(b64::encode(&ciphertext))
}
#[cfg(test)]
@@ -94,10 +115,11 @@ mod tests {
}
#[test]
- fn round_trip() {
+ fn pq_round_trip() {
let receiver = ReceiverCredentials::generate();
let prepared = prepare_payload(
&receiver.public_key(),
+ Some(&receiver.pq_public_key()),
payload().collection_id,
&payload().collection_key,
)
@@ -124,6 +146,7 @@ mod tests {
let secret_key: [u8; 32] = std::array::from_fn(|index| index as u8);
let receiver = ReceiverCredentials {
secret_key: SecretKey::from_seed(&secret_key).unwrap(),
+ pq_secret_key: hpke::SecretKey::generate(),
};
assert_eq!(
receiver.public_key(),
@@ -136,18 +159,94 @@ mod tests {
#[test]
fn rejects_invalid_inputs() {
- assert!(prepare_payload("not base64", 42, "collection_key").is_err());
+ assert!(prepare_payload("not base64", None, 42, "collection_key").is_err());
let receiver = ReceiverCredentials::generate();
assert!(receiver.open_payload("not base64").is_err());
assert!(receiver.open_payload(&b64::encode(&[0; 48])).is_err());
}
+ #[test]
+ fn sender_does_not_fallback_from_invalid_pq_key() {
+ let receiver = ReceiverCredentials::generate();
+ assert!(
+ prepare_payload(
+ &receiver.public_key(),
+ Some("not base64"),
+ 42,
+ "collection_key"
+ )
+ .is_err()
+ );
+ }
+
+ #[test]
+ fn sender_uses_classical_without_pq_key() {
+ let receiver = ReceiverCredentials::generate();
+ let prepared = prepare_payload(
+ &receiver.public_key(),
+ None,
+ payload().collection_id,
+ &payload().collection_key,
+ )
+ .unwrap();
+
+ assert_eq!(
+ receiver.open_payload(&prepared.encrypted_payload).unwrap(),
+ CastPayload {
+ cast_token: prepared.cast_token,
+ ..payload()
+ }
+ );
+ }
+
+ #[test]
+ fn corrupted_payloads_fail() {
+ let receiver = ReceiverCredentials::generate();
+ for pq_public_key in [Some(receiver.pq_public_key()), None] {
+ let prepared = prepare_payload(
+ &receiver.public_key(),
+ pq_public_key.as_deref(),
+ 42,
+ "collection_key",
+ )
+ .unwrap();
+ let mut ciphertext = b64::decode(&prepared.encrypted_payload).unwrap();
+ *ciphertext.last_mut().unwrap() ^= 1;
+ assert!(receiver.open_payload(&b64::encode(&ciphertext)).is_err());
+ }
+ }
+
+ #[test]
+ fn wrong_hpke_domain_fails() {
+ let receiver = ReceiverCredentials::generate();
+ let ciphertext = hpke::seal(
+ &serde_json::to_vec(&payload()).unwrap(),
+ &receiver.pq_secret_key.public_key(),
+ b"other-domain",
+ )
+ .unwrap();
+
+ assert!(receiver.open_payload(&b64::encode(&ciphertext)).is_err());
+ }
+
+ #[test]
+ fn invalid_pq_plaintext_is_not_retried_as_classical() {
+ let receiver = ReceiverCredentials::generate();
+ let ciphertext =
+ hpke::seal(b"not JSON", &receiver.pq_secret_key.public_key(), HPKE_INFO).unwrap();
+
+ assert!(matches!(
+ receiver.open_payload(&b64::encode(&ciphertext)),
+ Err(Error::Payload(_))
+ ));
+ }
+
#[test]
fn generates_cast_token() {
let receiver = ReceiverCredentials::generate();
- let first = prepare_payload(&receiver.public_key(), 42, "collection_key").unwrap();
- let second = prepare_payload(&receiver.public_key(), 42, "collection_key").unwrap();
+ let first = prepare_payload(&receiver.public_key(), None, 42, "collection_key").unwrap();
+ let second = prepare_payload(&receiver.public_key(), None, 42, "collection_key").unwrap();
assert_eq!(first.cast_token.len(), 27);
assert!(first.cast_token.starts_with("cast_"));
diff --git a/rust/crates/core/Cargo.toml b/rust/crates/core/Cargo.toml
index 603bb2ad83..ec8853abcf 100644
--- a/rust/crates/core/Cargo.toml
+++ b/rust/crates/core/Cargo.toml
@@ -11,6 +11,7 @@ blake2b_simd = "1.0"
crypto_secretbox = { version = "0.1", default-features = false, features = ["alloc", "salsa20"] }
crypto_secretstream = "=0.2.0"
getrandom = { version = "0.4", features = ["wasm_js"] }
+hpke = { version = "0.14", default-features = false, features = ["alloc", "chacha", "getrandom", "mlkem", "x25519"] }
log.workspace = true
md-5.workspace = true
rand_core_06 = { package = "rand_core", version = "0.6", features = ["getrandom"] }
@@ -20,6 +21,9 @@ serde.workspace = true
serde_json.workspace = true
subtle = "2"
thiserror.workspace = true
+# Remove when hpke fix for accidentally not enabling xwing zeroize is released.
+# https://github.com/rozbb/rust-hpke/issues/110
+x-wing = { version = "0.1", default-features = false, features = ["zeroize"] }
x25519-dalek = { version = "3.0", features = ["static_secrets"] }
zeroize.workspace = true
diff --git a/rust/crates/core/src/crypto/hpke.rs b/rust/crates/core/src/crypto/hpke.rs
new file mode 100644
index 0000000000..dc85d195a1
--- /dev/null
+++ b/rust/crates/core/src/crypto/hpke.rs
@@ -0,0 +1,191 @@
+use hpke::{Deserializable, Kem as HpkeKem, OpModeR, OpModeS, Serializable};
+use subtle::ConstantTimeEq;
+use zeroize::ZeroizeOnDrop;
+
+use crate::crypto::{Error, Result, fill_random};
+
+type Aead = ::hpke::aead::ChaCha20Poly1305;
+type Kdf = ::hpke::kdf::HkdfSha256;
+type Kem = ::hpke::kem::XWing;
+
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct PublicKey([u8; Self::BYTES]);
+
+impl PublicKey {
+ pub const BYTES: usize = 1216;
+
+ pub fn try_from_slice(bytes: &[u8]) -> Result<Self> {
+ if bytes.len() != Self::BYTES {
+ return Err(Error::InvalidKeyLength {
+ expected: Self::BYTES,
+ actual: bytes.len(),
+ });
+ }
+ <Kem as HpkeKem>::PublicKey::from_bytes(bytes).map_err(|_| Error::InvalidPublicKey)?;
+ Ok(Self(bytes.try_into()?))
+ }
+
+ pub fn as_bytes(&self) -> &[u8; Self::BYTES] {
+ &self.0
+ }
+
+ fn hpke_key(&self) -> <Kem as HpkeKem>::PublicKey {
+ <Kem as HpkeKem>::PublicKey::from_bytes(&self.0)
+ .expect("PublicKey is validated when constructed")
+ }
+}
+
+#[derive(ZeroizeOnDrop)]
+pub struct SecretKey([u8; Self::BYTES]);
+
+impl SecretKey {
+ pub const BYTES: usize = 32;
+
+ pub fn generate() -> Self {
+ let mut bytes = [0u8; Self::BYTES];
+ fill_random(&mut bytes);
+ Self(bytes)
+ }
+
+ pub fn from_bytes(bytes: [u8; Self::BYTES]) -> Self {
+ Self(bytes)
+ }
+
+ pub fn try_from_slice(bytes: &[u8]) -> Result<Self> {
+ Ok(Self(bytes.try_into().map_err(|_| {
+ Error::InvalidKeyLength {
+ expected: Self::BYTES,
+ actual: bytes.len(),
+ }
+ })?))
+ }
+
+ pub fn public_key(&self) -> PublicKey {
+ let bytes = Kem::sk_to_pk(&self.hpke_key()).to_bytes();
+ PublicKey(bytes.as_slice().try_into().expect("X-Wing public key size"))
+ }
+
+ pub fn as_bytes(&self) -> &[u8; Self::BYTES] {
+ &self.0
+ }
+
+ fn hpke_key(&self) -> <Kem as HpkeKem>::PrivateKey {
+ <Kem as HpkeKem>::PrivateKey::from_bytes(&self.0)
+ .expect("X-Wing accepts every 32-byte private key")
+ }
+}
+
+impl std::fmt::Debug for SecretKey {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.write_str("SecretKey([REDACTED])")
+ }
+}
+
+impl PartialEq for SecretKey {
+ fn eq(&self, other: &Self) -> bool {
+ self.0.ct_eq(&other.0).into()
+ }
+}
+
+impl Eq for SecretKey {}
+
+pub const OVERHEAD: usize = 1136;
+const ENCAPSULATED_KEY_BYTES: usize = 1120;
+
+pub fn seal(plaintext: &[u8], public_key: &PublicKey, info: &[u8]) -> Result<Vec<u8>> {
+ let (encapped_key, ciphertext) = ::hpke::single_shot_seal::<Aead, Kdf, Kem>(
+ &OpModeS::Base,
+ &public_key.hpke_key(),
+ info,
+ plaintext,
+ &[],
+ )
+ .map_err(|_| Error::EncryptionFailed)?;
+
+ let mut sealed = encapped_key.to_bytes().to_vec();
+ sealed.extend_from_slice(&ciphertext);
+ Ok(sealed)
+}
+
+pub fn open(ciphertext: &[u8], secret_key: &SecretKey, info: &[u8]) -> Result<Vec<u8>> {
+ if ciphertext.len() < OVERHEAD {
+ return Err(Error::CiphertextTooShort {
+ minimum: OVERHEAD,
+ actual: ciphertext.len(),
+ });
+ }
+ let (encapped_key, ciphertext) = ciphertext.split_at(ENCAPSULATED_KEY_BYTES);
+ let encapped_key = <Kem as HpkeKem>::EncappedKey::from_bytes(encapped_key)
+ .map_err(|_| Error::DecryptionFailed)?;
+
+ ::hpke::single_shot_open::<Aead, Kdf, Kem>(
+ &OpModeR::Base,
+ &secret_key.hpke_key(),
+ &encapped_key,
+ info,
+ ciphertext,
+ &[],
+ )
+ .map_err(|_| Error::DecryptionFailed)
+}
+
+#[cfg(test)]
+mod tests {
+ use base64::Engine;
+
+ use super::*;
+
+ const INFO: &[u8] = b"ente-test";
+
+ #[test]
+ fn seal_and_open() {
+ let secret_key = SecretKey::generate();
+ let public_key = secret_key.public_key();
+ let plaintext = b"hello";
+
+ let ciphertext = seal(plaintext, &public_key, INFO).unwrap();
+
+ assert_eq!(ciphertext.len(), plaintext.len() + OVERHEAD);
+ assert_ne!(ciphertext, seal(plaintext, &public_key, INFO).unwrap());
+ assert_eq!(open(&ciphertext, &secret_key, INFO).unwrap(), plaintext);
+ assert_eq!(
+ SecretKey::try_from_slice(secret_key.as_bytes()).unwrap(),
+ secret_key
+ );
+ assert_eq!(
+ PublicKey::try_from_slice(public_key.as_bytes()).unwrap(),
+ public_key
+ );
+ }
+
+ #[test]
+ fn authentication_failures() {
+ let secret_key = SecretKey::generate();
+ let ciphertext = seal(b"hello", &secret_key.public_key(), INFO).unwrap();
+
+ assert!(open(&ciphertext, &SecretKey::generate(), INFO).is_err());
+ assert!(open(&ciphertext, &secret_key, b"other-info").is_err());
+ assert!(matches!(
+ open(&ciphertext[..OVERHEAD - 1], &secret_key, INFO),
+ Err(Error::CiphertextTooShort { .. })
+ ));
+
+ let mut corrupted = ciphertext;
+ *corrupted.last_mut().unwrap() ^= 1;
+ assert!(open(&corrupted, &secret_key, INFO).is_err());
+ }
+
+ #[test]
+ fn opens_go_ciphertext() {
+ // Generated with Go 1.26's crypto/hpke and private-key bytes 0..31.
+ let secret_key = SecretKey::from_bytes(std::array::from_fn(|i| i as u8));
+ let ciphertext = base64::engine::general_purpose::STANDARD
+ .decode(include_str!("../../tests/data/hpke_go.sealed.b64").trim())
+ .unwrap();
+
+ assert_eq!(
+ open(&ciphertext, &secret_key, b"ente-go-interop").unwrap(),
+ b"sealed by Go"
+ );
+ }
+}
diff --git a/rust/crates/core/src/crypto/mod.rs b/rust/crates/core/src/crypto/mod.rs
index 948f648e32..9f26d60e72 100644
--- a/rust/crates/core/src/crypto/mod.rs
+++ b/rust/crates/core/src/crypto/mod.rs
@@ -5,6 +5,7 @@ mod types;
pub mod argon;
pub mod blob;
pub mod hash;
+pub mod hpke;
pub mod kdf;
pub mod sealed;
pub mod secretbox;
diff --git a/rust/crates/core/tests/data/hpke_go.sealed.b64 b/rust/crates/core/tests/data/hpke_go.sealed.b64
new file mode 100644
index 0000000000..3f21cd962a
--- /dev/null
+++ b/rust/crates/core/tests/data/hpke_go.sealed.b64
@@ -0,0 +1 @@
+3Vww2rajn/3GZjLXtU6xS+dcvUoWmJzNkdlxH15YojWVAiTMWrBwRs37tXJ+T7OletjTbuGGMZGlJ6PnJdmzqi7XobajPRHgkVIjkSp8ZfyZGvQqoEc0llLHysSbU9Z6uUB2b1bfLKu6aMSFz90GN1+mI4nrwCTOKv91ms18feGh757v77KoJdtzYOnJWbstRSVdLTdPmTrBg9aQtGN4dn2gEFUbzaTAflxEkbTJ21tXfUe0yVuauBQnyi3TvI+iqfo9Rg7IX1RtzUG0VlEdNa0dfUR3tzvXCrGSq/wytqZqREpj+utd2utfWL4IvUfA71iiQ1ZYFyUdubvBVTmfIYmaC8fo5cK3dtcjL+ZTtShQT/AMxXKhDhzbXxv8dyFkZDcxvizt4FQF6qAPvPV1MXhn/MwcopI+BDSVMalph3ToCFG0Fg0QC/azOSJdxZTJYy6BpRGiEG9CFDjPJ5D1LM4Xeodqwd0A/8vMIcJ9Lf2mHdvMqCwVumUZ6gwqLfVRs6TsF7gmyIuTyufpejw0gWms3e5UyAq/ryrafEULW14cUdQa/kuOzli+O4VispncncF4uBgeTq4KYhbXBYsNggJYoh1joSkx1RfSGtAWfA+8JWGbMxGrqwI/qzSjAY/32GLqW6kYwdB7I+JeE8qGovPZoqcQ8ksyFAOquZ7C4Uhgf3WnWj/8rILdPhuV/uAAGYOTlLSkGECCb5mU8ThjOpXu3Z8BqCMzIXhtjrR4Latqel/nhag70UlBtFN3D7LGzmlhsNvlywOQdOS47pycnCZTvixUimNxKkD130TWKz6wO68C+RewfwPky7p2N2HrGVreShPyJ3aRicU+lUyV0I9Oc+W6zXiVON0D/8gan50lL5Z5/g6hRJ25TKH1E88+C/Qq9dlFdUW7HnrYLtxRDa698zJU/41Y38CY2E4EJ9coOEJw73Bjko01bP3owgMKRCpAt5hmfp2IOS11zEtDJlPEI3+guLzhdZ81Inuny0+vdVZLoQNJchp8vSE15ofw7eXDnGuorgu4o2Cv55i+h4j3C1k7zQCTPLTPIOa979i3MfE6wRu54N82WFCGObbq6WXWbrYQKYRRh4GF5j4f9+hbvF6WTY9zxL8aFxkORX1s94KMka3cgCGQJmWxH/72u/dVRZCwfGLmHYVTpXi5E7KzabJS1Nz5mxIMK3kwk7dckUni67vl2GkNlWtJKEG3+ihweDV3A4BNnMCDnXqtfPOqIJhlBqOmdML565sqMn4t+BkuxZIv5JqzJIlXBbsEUlk1L8Tm9RaE0u6tCageAy0+ND99UukADJVyImKkZuBMewSd4KpGnbtdiL+JCh6k/1BLDMlFjmOnj4GTN1AfwH0AXoqX5XwKlJpaRyXyNCOeB71XAsozW7ksCkcx5uTDUc9VzDLDMdm9W36F9KLdVZ8mWAeTh8tpNwWSHNjahjbaqRFqpf/bgQZccEG6xOJ59DYiwNRjTQybsgyBNqoIa2IyMDlvtNbqgbCWxtLfXXA8ddjnpntTvCQDYdQ=
diff --git a/server/ente/cast/entity.go b/server/ente/cast/entity.go
index b60d310c58..dd038da3fc 100644
--- a/server/ente/cast/entity.go
+++ b/server/ente/cast/entity.go
@@ -10,7 +10,13 @@ type CastRequest struct {
}
type RegisterDeviceRequest struct {
- PublicKey string `json:"publicKey" binding:"required"`
+ PublicKey string `json:"publicKey" binding:"required"`
+ PQPublicKey *string `json:"pqPublicKey"`
+}
+
+type DeviceInfo struct {
+ PublicKey string `json:"publicKey"`
+ PQPublicKey *string `json:"pqPublicKey,omitempty"`
}
type AuthContext struct {
diff --git a/server/migrations/131_cast_pq_public_key.down.sql b/server/migrations/131_cast_pq_public_key.down.sql
new file mode 100644
index 0000000000..4ebbea32ff
--- /dev/null
+++ b/server/migrations/131_cast_pq_public_key.down.sql
@@ -0,0 +1 @@
+ALTER TABLE casting DROP COLUMN pq_public_key;
diff --git a/server/migrations/131_cast_pq_public_key.up.sql b/server/migrations/131_cast_pq_public_key.up.sql
new file mode 100644
index 0000000000..aff6160858
--- /dev/null
+++ b/server/migrations/131_cast_pq_public_key.up.sql
@@ -0,0 +1 @@
+ALTER TABLE casting ADD COLUMN pq_public_key TEXT;
diff --git a/server/pkg/api/cast.go b/server/pkg/api/cast.go
index e294b15ebb..2e52203d63 100644
--- a/server/pkg/api/cast.go
+++ b/server/pkg/api/cast.go
@@ -41,14 +41,12 @@ func (h *CastHandler) RegisterDevice(c *gin.Context) {
func (h *CastHandler) GetDeviceInfo(c *gin.Context) {
deviceCode := getDeviceCode(c)
- publicKey, err := h.Ctrl.GetPublicKey(c, deviceCode)
+ deviceInfo, err := h.Ctrl.GetDeviceInfo(c, deviceCode)
if err != nil {
- handler.Error(c, stacktrace.Propagate(err, "failed to get public key"))
+ handler.Error(c, stacktrace.Propagate(err, "failed to get device info"))
return
}
- c.JSON(http.StatusOK, gin.H{
- "publicKey": publicKey,
- })
+ c.JSON(http.StatusOK, deviceInfo)
}
func (h *CastHandler) GetAllDevices(c *gin.Context) {
diff --git a/server/pkg/controller/cast/controller.go b/server/pkg/controller/cast/controller.go
index 0ad4ed86d9..5b87b5f95e 100644
--- a/server/pkg/controller/cast/controller.go
+++ b/server/pkg/controller/cast/controller.go
@@ -2,6 +2,7 @@ package cast
import (
"context"
+ "encoding/base64"
"github.com/ente/museum/ente"
"github.com/ente/museum/ente/cast"
@@ -21,7 +22,10 @@ type Controller struct {
AccessCtrl access.Controller
}
-const maxRegisterDeviceUserAgentBytes = 1000
+const (
+ maxRegisterDeviceUserAgentBytes = 1000
+ pqPublicKeyBytes = 1216
+)
func NewController(castRepo *castRepo.Repository,
accessCtrl access.Controller,
@@ -33,6 +37,9 @@ func NewController(castRepo *castRepo.Repository,
}
func (c *Controller) RegisterDevice(ctx *gin.Context, request *cast.RegisterDeviceRequest) (string, error) {
+ if err := validatePQPublicKey(request.PQPublicKey); err != nil {
+ return "", err
+ }
ipAddress := network.GetClientIP(ctx)
userAgent := ctx.GetHeader("User-Agent")
if len(userAgent) > maxRegisterDeviceUserAgentBytes {
@@ -47,7 +54,21 @@ func (c *Controller) RegisterDevice(ctx *gin.Context, request *cast.RegisterDevi
}).Warn("RegisterDevice: failed to get device type")
deviceName = ipAddress
}
- return c.CastRepo.AddCode(ctx, request.PublicKey, ipAddress, deviceName)
+ return c.CastRepo.AddCode(ctx, request.PublicKey, request.PQPublicKey, ipAddress, deviceName)
+}
+
+func validatePQPublicKey(publicKey *string) error {
+ if publicKey == nil {
+ return nil
+ }
+ if len(*publicKey) != base64.StdEncoding.EncodedLen(pqPublicKeyBytes) {
+ return stacktrace.Propagate(ente.ErrBadRequest, "invalid pqPublicKey length")
+ }
+ decoded, err := base64.StdEncoding.DecodeString(*publicKey)
+ if err != nil || len(decoded) != pqPublicKeyBytes {
+ return stacktrace.Propagate(ente.ErrBadRequest, "invalid pqPublicKey")
+ }
+ return nil
}
func (c *Controller) GetAllDevices(ctx *gin.Context, userID int64) ([]cast.CastInfo, error) {
@@ -58,19 +79,19 @@ func (c *Controller) DeleteDevice(ctx *gin.Context, userID int64, deviceID uuid.
return c.CastRepo.RevokeForGivenUserAndDevice(ctx, userID, deviceID)
}
-func (c *Controller) GetPublicKey(ctx *gin.Context, deviceCode string) (string, error) {
- pubKey, ip, err := c.CastRepo.GetPubKeyAndIp(ctx, deviceCode)
+func (c *Controller) GetDeviceInfo(ctx *gin.Context, deviceCode string) (*cast.DeviceInfo, error) {
+ deviceInfo, ip, err := c.CastRepo.GetDeviceInfoAndIP(ctx, deviceCode)
if err != nil {
- return "", stacktrace.Propagate(err, "")
+ return nil, stacktrace.Propagate(err, "")
}
if ip != network.GetClientIP(ctx) {
logrus.WithFields(logrus.Fields{
"deviceCode": deviceCode,
"ip": ip,
"clientIP": network.GetClientIP(ctx),
- }).Warn("GetPublicKey: IP mismatch")
+ }).Warn("GetDeviceInfo: IP mismatch")
}
- return pubKey, nil
+ return deviceInfo, nil
}
func (c *Controller) GetEncCastData(ctx context.Context, deviceCode string) (*string, error) {
diff --git a/server/pkg/controller/cast/controller_test.go b/server/pkg/controller/cast/controller_test.go
index db04bb3fa6..b640fd1dce 100644
--- a/server/pkg/controller/cast/controller_test.go
+++ b/server/pkg/controller/cast/controller_test.go
@@ -1,6 +1,8 @@
package cast
import (
+ "encoding/base64"
+ "errors"
"net/http"
"net/http/httptest"
"strings"
@@ -12,6 +14,29 @@ import (
"github.com/stretchr/testify/require"
)
+func TestValidatePQPublicKey(t *testing.T) {
+ valid := base64.StdEncoding.EncodeToString(make([]byte, pqPublicKeyBytes))
+ invalidBase64 := strings.Repeat("!", len(valid))
+ wrongLength := base64.StdEncoding.EncodeToString(make([]byte, pqPublicKeyBytes-1))
+
+ for name, key := range map[string]*string{
+ "omitted": nil,
+ "valid": &valid,
+ "invalid base64": &invalidBase64,
+ "wrong length": &wrongLength,
+ } {
+ t.Run(name, func(t *testing.T) {
+ err := validatePQPublicKey(key)
+ if (name == "omitted" || name == "valid") != (err == nil) {
+ t.Fatalf("validatePQPublicKey() error = %v", err)
+ }
+ if err != nil && !errors.Is(err, ente.ErrBadRequest) {
+ t.Fatalf("validatePQPublicKey() error = %v, want bad request", err)
+ }
+ })
+ }
+}
+
func TestRegisterDeviceRejectsOversizedUserAgent(t *testing.T) {
gin.SetMode(gin.TestMode)
diff --git a/server/pkg/repo/cast/repo.go b/server/pkg/repo/cast/repo.go
index 3319ae8512..dd275fc364 100644
--- a/server/pkg/repo/cast/repo.go
+++ b/server/pkg/repo/cast/repo.go
@@ -17,13 +17,13 @@ type Repository struct {
DB *sql.DB
}
-func (r *Repository) AddCode(ctx context.Context, pubKey string, ip string, deviceName string) (string, error) {
+func (r *Repository) AddCode(ctx context.Context, pubKey string, pqPubKey *string, ip string, deviceName string) (string, error) {
codeValue, err := random.GenerateAlphaNumString(6)
if err != nil {
return "", err
}
codeValue = strings.ToUpper(codeValue)
- _, err = r.DB.ExecContext(ctx, "INSERT INTO casting (code, public_key, id, ip, device_name) VALUES ($1, $2, $3, $4, $5)", codeValue, pubKey, uuid.New(), ip, deviceName)
+ _, err = r.DB.ExecContext(ctx, "INSERT INTO casting (code, public_key, pq_public_key, id, ip, device_name) VALUES ($1, $2, $3, $4, $5, $6)", codeValue, pubKey, pqPubKey, uuid.New(), ip, deviceName)
if err != nil {
return "", err
}
@@ -65,18 +65,19 @@ func (r *Repository) InsertCastData(ctx context.Context, castUserID int64, code
return deviceID, err
}
-func (r *Repository) GetPubKeyAndIp(ctx context.Context, code string) (string, string, error) {
+func (r *Repository) GetDeviceInfoAndIP(ctx context.Context, code string) (*cast.DeviceInfo, string, error) {
code = strings.ToUpper(code)
- var pubKey, ip string
- row := r.DB.QueryRowContext(ctx, "SELECT public_key, ip FROM casting WHERE code = $1 and is_deleted=false", code)
- err := row.Scan(&pubKey, &ip)
+ var deviceInfo cast.DeviceInfo
+ var ip string
+ row := r.DB.QueryRowContext(ctx, "SELECT public_key, pq_public_key, ip FROM casting WHERE code = $1 and is_deleted=false", code)
+ err := row.Scan(&deviceInfo.PublicKey, &deviceInfo.PQPublicKey, &ip)
if err != nil {
if err == sql.ErrNoRows {
- return "", "", ente.ErrNotFoundError.NewErr("code not found")
+ return nil, "", ente.ErrNotFoundError.NewErr("code not found")
}
- return "", "", err
+ return nil, "", err
}
- return pubKey, ip, nil
+ return &deviceInfo, ip, nil
}
func (r *Repository) GetEncCastData(ctx context.Context, code string) (*string, error) {
diff --git a/server/pkg/repo/cast/repo_test.go b/server/pkg/repo/cast/repo_test.go
index 9cc3c90539..0a55610093 100644
--- a/server/pkg/repo/cast/repo_test.go
+++ b/server/pkg/repo/cast/repo_test.go
@@ -80,6 +80,56 @@ func TestInsertCastDataReturnsDeviceID(t *testing.T) {
}
}
+func TestGetDeviceInfo(t *testing.T) {
+ testutil.WithServerRoot(t)
+ db := testutil.RequireTestDB(t)
+ testutil.ResetTables(t, db)
+ t.Cleanup(func() {
+ testutil.ResetTables(t, db)
+ })
+ repository := &Repository{DB: db}
+ _, err := db.Exec(
+ `INSERT INTO casting (id, code, public_key, pq_public_key, ip) VALUES ($1, $2, $3, $4, $5)`,
+ uuid.New(),
+ "ABC123",
+ "public-key",
+ "pq-public-key",
+ "127.0.0.1",
+ )
+ if err != nil {
+ t.Fatalf("failed to insert casting row: %v", err)
+ }
+
+ info, ip, err := repository.GetDeviceInfoAndIP(t.Context(), "abc123")
+ if err != nil {
+ t.Fatalf("GetDeviceInfoAndIP() error = %v", err)
+ }
+ if info.PublicKey != "public-key" || info.PQPublicKey == nil || *info.PQPublicKey != "pq-public-key" {
+ t.Fatalf("GetDeviceInfoAndIP() info = %+v", info)
+ }
+ if ip != "127.0.0.1" {
+ t.Fatalf("GetDeviceInfoAndIP() IP = %q", ip)
+ }
+
+ _, err = db.Exec(
+ `INSERT INTO casting (id, code, public_key, ip) VALUES ($1, $2, $3, $4)`,
+ uuid.New(),
+ "DEF456",
+ "classical-only",
+ "127.0.0.2",
+ )
+ if err != nil {
+ t.Fatalf("failed to insert classical casting row: %v", err)
+ }
+ info, _, err = repository.GetDeviceInfoAndIP(t.Context(), "DEF456")
+ if err != nil {
+ t.Fatalf("GetDeviceInfoAndIP() classical error = %v", err)
+ }
+ if info.PQPublicKey != nil {
+ t.Fatalf("GetDeviceInfoAndIP() PQ public key = %q", *info.PQPublicKey)
+ }
+}
+
func getCastDeviceIsDeleted(t *testing.T, db *sql.DB, deviceID uuid.UUID) bool {
t.Helper()
var isDeleted bool
diff --git a/web/apps/cast/src/services/pair.ts b/web/apps/cast/src/services/pair.ts
index ac1ca22967..1fa039a243 100644
--- a/web/apps/cast/src/services/pair.ts
+++ b/web/apps/cast/src/services/pair.ts
@@ -18,7 +18,10 @@ export const register = async (): Promise<Registration> => {
let pairingCode: string | undefined;
while (true) {
try {
- pairingCode = await registerDevice(receiver.publicKey);
+ pairingCode = await registerDevice(
+ receiver.publicKey,
+ receiver.pqPublicKey,
+ );
} catch (e) {
log.error("Failed to register public key with server", e);
}
@@ -29,11 +32,11 @@ export const register = async (): Promise<Registration> => {
return { pairingCode, receiver };
};
-const registerDevice = async (publicKey: string) => {
+const registerDevice = async (publicKey: string, pqPublicKey: string) => {
const res = await fetch(await apiURL("/cast/device-info"), {
method: "POST",
headers: publicRequestHeaders(),
- body: JSON.stringify({ publicKey }),
+ body: JSON.stringify({ publicKey, pqPublicKey }),
});
ensureOk(res);
return z.object({ deviceCode: z.string() }).parse(await res.json())
diff --git a/web/apps/photos/src/services/cast.ts b/web/apps/photos/src/services/cast.ts
index d2e2bbc174..b24c57da33 100644
--- a/web/apps/photos/src/services/cast.ts
+++ b/web/apps/photos/src/services/cast.ts
@@ -11,14 +11,15 @@ export const revokeAllCastTokens = async () =>
}),
);
-const publicKeyForPairingCode = async (code: string) => {
+const publicKeysForPairingCode = async (code: string) => {
const res = await fetch(await apiURL(`/cast/device-info/${code}`), {
headers: await authenticatedRequestHeaders(),
});
if (res.status == 404) return undefined;
ensureOk(res);
- return z.object({ publicKey: z.string() }).parse(await res.json())
- .publicKey;
+ return z
+ .object({ publicKey: z.string(), pqPublicKey: z.string().optional() })
+ .parse(await res.json());
};
// AlbumCastDialog matches this exact message.
@@ -28,12 +29,13 @@ export const publishCastPayload = async (
deviceCode: string,
collection: Collection,
) => {
- const publicKey = await publicKeyForPairingCode(deviceCode);
- if (!publicKey) throw new Error(unknownDeviceCodeErrorMessage);
+ const publicKeys = await publicKeysForPairingCode(deviceCode);
+ if (!publicKeys) throw new Error(unknownDeviceCodeErrorMessage);
const { preparePayload } = await import("ente-cast-wasm");
const { castToken, encryptedPayload } = preparePayload(
- publicKey,
+ publicKeys.publicKey,
+ publicKeys.pqPublicKey,
BigInt(collection.id),
collection.key,
);