π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Disambiguate Space key wrap fields
Neeraj Gupta9f3645f8029e
diff --git a/rust/bindings/wasm/ente-wasm/src/space.rs b/rust/bindings/wasm/ente-wasm/src/space.rsindex 059c318c48..8ccd60e123 100644--- a/rust/bindings/wasm/ente-wasm/src/space.rs+++ b/rust/bindings/wasm/ente-wasm/src/space.rs@@ -54,7 +54,9 @@ impl From<CoreSpaceError> for WasmSpaceError {CoreSpaceError::Auth(_) => ("auth", None),CoreSpaceError::InvalidInput(_) => ("invalid_input", None),CoreSpaceError::MissingSecretKey => ("missing_secret_key", None),- CoreSpaceError::MissingEncryptedSpaceKey => ("missing_encrypted_space_key", None),+ CoreSpaceError::MissingFriendSealedSpaceKey => {+ ("missing_friend_sealed_space_key", None)+ }CoreSpaceError::EntityKeyConflict => ("entity_key_conflict", None),};Self {@@ -105,7 +107,7 @@ struct CreatedSpaceJs {space_slug: String,key_version: i32,space_key_b64: String,- encrypted_space_key: String,+ root_wrapped_space_key: String,encrypted_profile: String,}@@ -320,7 +322,7 @@ fn created_space_to_js(value: CreatedSpace) -> CreatedSpaceJs {space_slug: value.space_slug,key_version: value.key_version,space_key_b64: encode_b64(&value.space_key),- encrypted_space_key: value.encrypted_space_key,+ root_wrapped_space_key: value.root_wrapped_space_key,encrypted_profile: value.encrypted_profile,}}diff --git a/rust/space/src/client.rs b/rust/space/src/client.rsindex 299d69c876..1b2e0ddda1 100644--- a/rust/space/src/client.rs+++ b/rust/space/src/client.rs@@ -247,9 +247,9 @@ impl AccountSpaceCtx {share: &FriendShareResponse,) -> Result<DecryptedFriendShare> {let identity = self.default_space_identity().await?;- let ciphertext = decode_b64(&share.encrypted_space_key)?;+ let ciphertext = decode_b64(&share.friend_sealed_space_key)?;if ciphertext.is_empty() {- return Err(SpaceError::MissingEncryptedSpaceKey);+ return Err(SpaceError::MissingFriendSealedSpaceKey);}let space_key = open_with_keypair(&ciphertext, &identity.public_key, &identity.secret_key)?;Ok(DecryptedFriendShare {@@ -272,7 +272,7 @@ impl AccountSpaceCtx {.into_iter().next().ok_or_else(|| SpaceError::InvalidInput("no owned space is available".into()))?;- let packed = decode_b64(&space.encrypted_space_key)?;+ let packed = decode_b64(&space.root_wrapped_space_key)?;let space_key = decrypt_secretbox_payload(&space_root_key, &packed)?;Ok((space, space_key))}@@ -304,14 +304,14 @@ impl AccountSpaceCtx {profile: &[u8],) -> Result<CreatedSpace> {let space_root_key = self.get_or_create_space_root_key().await?;- let encrypted_space_key =+ let root_wrapped_space_key =encode_b64(&encrypt_secretbox_payload(&space_root_key, space_key)?);let (public_key, secret_key) = generate_keypair()?;let encrypted_secret_key = encrypt_secretbox_payload(&space_root_key, &secret_key)?;let encrypted_profile = encode_b64(&encrypt_secretbox_payload(space_key, profile)?);let request = CreateSpaceRequest {space_slug: space_slug.to_owned(),- encrypted_space_key: encrypted_space_key.clone(),+ root_wrapped_space_key: root_wrapped_space_key.clone(),public_key: encode_b64(&public_key),encrypted_secret_key: encode_b64(&encrypted_secret_key),encrypted_profile: encrypted_profile.clone(),@@ -323,7 +323,7 @@ impl AccountSpaceCtx {self.cache_created_owned_space(SpaceKeyResponse {space_id: response.space_id.clone(),space_slug: response.space_slug.clone(),- encrypted_space_key: encrypted_space_key.clone(),+ root_wrapped_space_key: root_wrapped_space_key.clone(),public_key: request.public_key.clone(),encrypted_secret_key: request.encrypted_secret_key.clone(),encrypted_profile: encrypted_profile.clone(),@@ -338,7 +338,7 @@ impl AccountSpaceCtx {space_slug: response.space_slug,key_version: response.key_version,space_key: space_key.to_vec(),- encrypted_space_key,+ root_wrapped_space_key,encrypted_profile,})}@@ -502,7 +502,7 @@ impl AccountSpaceCtx {let request = RotateSpaceKeyRequest {space_id: space_id.to_owned(),key_version: current.key_version,- encrypted_space_key: encode_b64(&encrypt_secretbox_payload(+ root_wrapped_space_key: encode_b64(&encrypt_secretbox_payload(&space_root_key,&next_space_key,)?),@@ -525,7 +525,7 @@ impl AccountSpaceCtx {space_slug: response.space_slug,key_version: response.key_version,space_key: next_space_key,- encrypted_space_key: request.encrypted_space_key,+ root_wrapped_space_key: request.root_wrapped_space_key,encrypted_profile: request.encrypted_profile,})}@@ -909,7 +909,7 @@ impl AccountSpaceCtx {let mut owned = Vec::with_capacity(owned_records.len());if let Some(space_root_key) = space_root_key {for record in owned_records {- let packed = decode_b64(&record.encrypted_space_key)?;+ let packed = decode_b64(&record.root_wrapped_space_key)?;let space_key = decrypt_secretbox_payload(&space_root_key, &packed)?;owned.push((record.space_id, space_key));}@@ -1325,7 +1325,7 @@ impl AccountSpaceCtx {target_space_id: Some(target_space_id.to_owned()),target_username: None,requester_space_id: requester_space.space_id,- requester_encrypted_space_key: encode_b64(&requester_share),+ requester_friend_sealed_space_key: encode_b64(&requester_share),requester_key_version: requester_space.key_version,};self.client@@ -1376,7 +1376,7 @@ impl AccountSpaceCtx {let (target_space, target_space_key) = self.default_profile_space_access().await?;let target_share = seal_with_public_key(&target_space_key, &requester_public_key)?;let payload = ConfirmFriendRequestPayload {- target_encrypted_space_key: encode_b64(&target_share),+ target_friend_sealed_space_key: encode_b64(&target_share),target_key_version: target_space.key_version,};let path = format!("/space/friends/requests/{request_id}/confirm");@@ -1458,7 +1458,7 @@ impl AccountSpaceCtx {let sealed_share = seal_with_public_key(&access.space_key, &public_key)?;updates.push(ShareUpdatePayload {friend_space_id: friend.friend.space_id,- encrypted_space_key: encode_b64(&sealed_share),+ friend_sealed_space_key: encode_b64(&sealed_share),});}if updates.is_empty() {@@ -1520,7 +1520,7 @@ impl AccountSpaceCtx {space_id: space_id.to_owned(),auth_key: encode_b64(&auth_key),key_version: access.key_version,- encrypted_space_key: encode_b64(&encrypt_secretbox_payload(+ link_wrapped_space_key: encode_b64(&encrypt_secretbox_payload(&wrap_key,&access.space_key,)?),@@ -1589,7 +1589,7 @@ impl AccountSpaceCtx {let Some(record) = spaces.into_iter().find(|value| value.space_id == space_id) else {return Ok(None);};- let packed = decode_b64(&record.encrypted_space_key)?;+ let packed = decode_b64(&record.root_wrapped_space_key)?;let space_key = decrypt_secretbox_payload(&space_root_key, &packed)?;Ok(Some(ResolvedOwnedSpaceAccess {space_root_key,@@ -1875,7 +1875,7 @@ impl SpaceLinkCtx {.await?;client.set_auth_token(Some(response.session_token.clone()));let space_key =- decrypt_secretbox_payload(&wrap_key, &decode_b64(&response.encrypted_space_key)?)?;+ decrypt_secretbox_payload(&wrap_key, &decode_b64(&response.link_wrapped_space_key)?)?;Ok(Self {client,session_token: response.session_token,@@ -2308,7 +2308,7 @@ mod tests {json!([{"spaceId": space_id,"spaceSlug": space_slug,- "encryptedSpaceKey": encode_b64(+ "rootWrappedSpaceKey": encode_b64(&encrypt_secretbox_payload(space_root_key, space_key).expect("space key wrap")),"encryptedProfile": "",@@ -2355,8 +2355,8 @@ mod tests {space_link_access_key_material(access_key).expect("access key material");let auth_key = derive_space_link_auth_key(&access_key_material).expect("auth key");let wrap_key = derive_space_link_wrap_key(&access_key_material).expect("wrap key");- let encrypted_space_key = encode_b64(- &encrypt_secretbox_payload(&wrap_key, &space_key).expect("encrypted space key"),+ let link_wrapped_space_key = encode_b64(+ &encrypt_secretbox_payload(&wrap_key, &space_key).expect("link wrapped space key"),);let lookup = server@@ -2390,7 +2390,7 @@ mod tests {"spaceSlug": "owner-gallery","owner": "owner-handle","keyVersion": 3,- "encryptedSpaceKey": encrypted_space_key,+ "linkWrappedSpaceKey": link_wrapped_space_key,"encryptedProfile": "",}).to_string(),@@ -2431,8 +2431,9 @@ mod tests {derive_space_link_auth_key(&wrong_access_key_material).expect("auth key");let correct_wrap_key =derive_space_link_wrap_key(&correct_access_key_material).expect("wrap key");- let encrypted_space_key = encode_b64(- &encrypt_secretbox_payload(&correct_wrap_key, &space_key).expect("encrypted space key"),+ let link_wrapped_space_key = encode_b64(+ &encrypt_secretbox_payload(&correct_wrap_key, &space_key)+ .expect("link wrapped space key"),);let lookup = server@@ -2466,7 +2467,7 @@ mod tests {"spaceSlug": "owner-gallery","owner": "owner-handle","keyVersion": 3,- "encryptedSpaceKey": encrypted_space_key,+ "linkWrappedSpaceKey": link_wrapped_space_key,}).to_string(),)@@ -2643,7 +2644,7 @@ mod tests {);let sealed_share = seal_with_public_key(&friend_space_key, &test_public_key(&ctx)).expect("friend share seal");- let encrypted_space_key = encode_b64(&sealed_share);+ let friend_sealed_space_key = encode_b64(&sealed_share);let spaces = server.mock("GET", "/space")@@ -2668,7 +2669,7 @@ mod tests {"friend": "friend","spaceId": "space_friend","spaceSlug": "friend",- "encryptedSpaceKey": encrypted_space_key,+ "friendSealedSpaceKey": friend_sealed_space_key,"keyVersion": 1}]).to_string(),@@ -3121,7 +3122,7 @@ mod tests {.match_header("x-space-session-token", "space-session-token").match_body(Matcher::AllOf(vec![Matcher::Regex("\"spaceSlug\":\"owner-main\"".into()),- Matcher::Regex("\"encryptedSpaceKey\":\"[^\"]+\"".into()),+ Matcher::Regex("\"rootWrappedSpaceKey\":\"[^\"]+\"".into()),Matcher::Regex("\"publicKey\":\"[^\"]+\"".into()),Matcher::Regex("\"encryptedSecretKey\":\"[^\"]+\"".into()),Matcher::Regex("\"encryptedProfile\":\"[^\"]+\"".into()),@@ -3131,7 +3132,7 @@ mod tests {json!({"spaceId": "space_owner_main","spaceSlug": "owner-main",- "encryptedSpaceKey": "",+ "rootWrappedSpaceKey": "","encryptedProfile": "","keyVersion": 1})@@ -3177,7 +3178,7 @@ mod tests {json!({"spaceId": "space_owner_main","spaceSlug": "owner-main",- "encryptedSpaceKey": "",+ "rootWrappedSpaceKey": "","encryptedProfile": "","keyVersion": 1})@@ -3260,7 +3261,10 @@ mod tests {assert_eq!(second.len(), 1);assert_eq!(second[0].space_id, first[0].space_id);assert_eq!(second[0].space_slug, first[0].space_slug);- assert_eq!(second[0].encrypted_space_key, first[0].encrypted_space_key);+ assert_eq!(+ second[0].root_wrapped_space_key,+ first[0].root_wrapped_space_key+ );assert_eq!(second[0].key_version, first[0].key_version);list_spaces.assert_async().await;}@@ -3279,7 +3283,7 @@ mod tests {json!([{"spaceId": "space_owner_main","spaceSlug": "owner-main",- "encryptedSpaceKey": encode_b64(&encrypt_secretbox_payload(&space_root_key, &space_key).expect("space key wrap")),+ "rootWrappedSpaceKey": encode_b64(&encrypt_secretbox_payload(&space_root_key, &space_key).expect("space key wrap")),"encryptedProfile": "","keyVersion": 3}])@@ -3504,7 +3508,7 @@ mod tests {json!([{"spaceId": "space_viewer_main","spaceSlug": "viewer-main",- "encryptedSpaceKey": encode_b64(&encrypt_secretbox_payload(&space_root_key, &requester_space_key).expect("space key wrap")),+ "rootWrappedSpaceKey": encode_b64(&encrypt_secretbox_payload(&space_root_key, &requester_space_key).expect("space key wrap")),"encryptedProfile": "","keyVersion": 4}])@@ -3519,7 +3523,7 @@ mod tests {Matcher::Regex("\"targetSpaceId\":\"space_owner_main\"".into()),Matcher::Regex("\"requesterSpaceId\":\"space_viewer_main\"".into()),Matcher::Regex("\"requesterKeyVersion\":4".into()),- Matcher::Regex("\"requesterEncryptedSpaceKey\":\"[^\"]+\"".into()),+ Matcher::Regex("\"requesterFriendSealedSpaceKey\":\"[^\"]+\"".into()),])).with_status(200).with_body(json!({"status": "requested"}).to_string())@@ -3996,7 +4000,7 @@ mod tests {json!([{"spaceId": "space_owner_main","spaceSlug": "owner-main",- "encryptedSpaceKey": encode_b64(&encrypt_secretbox_payload(&space_root_key, &space_key).expect("space key wrap")),+ "rootWrappedSpaceKey": encode_b64(&encrypt_secretbox_payload(&space_root_key, &space_key).expect("space key wrap")),"encryptedProfile": "","keyVersion": 3}])@@ -4106,7 +4110,7 @@ mod tests {Matcher::Regex("\"spaceId\":\"space_owner_main\"".into()),Matcher::Regex("\"authKey\":\"[^\"]+\"".into()),Matcher::Regex("\"keyVersion\":3".into()),- Matcher::Regex("\"encryptedSpaceKey\":\"[^\"]+\"".into()),+ Matcher::Regex("\"linkWrappedSpaceKey\":\"[^\"]+\"".into()),Matcher::Regex("\"encryptedAccessKey\":\"[^\"]+\"".into()),])).with_status(200)@@ -4131,7 +4135,7 @@ mod tests {Matcher::Regex("\"spaceId\":\"space_owner_main\"".into()),Matcher::Regex("\"authKey\":\"[^\"]+\"".into()),Matcher::Regex("\"keyVersion\":3".into()),- Matcher::Regex("\"encryptedSpaceKey\":\"[^\"]+\"".into()),+ Matcher::Regex("\"linkWrappedSpaceKey\":\"[^\"]+\"".into()),Matcher::Regex("\"encryptedAccessKey\":\"[^\"]+\"".into()),])).with_status(200)@@ -4220,7 +4224,7 @@ mod tests {Matcher::Regex("\"spaceId\":\"space_owner_main\"".into()),Matcher::Regex("\"authKey\":\"[^\"]+\"".into()),Matcher::Regex("\"keyVersion\":3".into()),- Matcher::Regex("\"encryptedSpaceKey\":\"[^\"]+\"".into()),+ Matcher::Regex("\"linkWrappedSpaceKey\":\"[^\"]+\"".into()),Matcher::Regex("\"encryptedAccessKey\":\"[^\"]+\"".into()),])).with_status(200)@@ -4366,7 +4370,7 @@ mod tests {json!([{"spaceId": "space_owner_gallery","spaceSlug": "owner-gallery",- "encryptedSpaceKey": encode_b64(&encrypt_secretbox_payload(&space_root_key, &space_key).expect("space key wrap")),+ "rootWrappedSpaceKey": encode_b64(&encrypt_secretbox_payload(&space_root_key, &space_key).expect("space key wrap")),"encryptedProfile": "","keyVersion": 3}])@@ -4432,7 +4436,7 @@ mod tests {json!([{"spaceId": "space_owner_gallery","spaceSlug": "owner-gallery",- "encryptedSpaceKey": encode_b64(&encrypt_secretbox_payload(&space_root_key, &owned_space_key).expect("owned wrap")),+ "rootWrappedSpaceKey": encode_b64(&encrypt_secretbox_payload(&space_root_key, &owned_space_key).expect("owned wrap")),"encryptedProfile": "","keyVersion": 1}])@@ -4449,7 +4453,7 @@ mod tests {"friend": "owner","spaceId": "space_shared_gallery","spaceSlug": "shared-gallery",- "encryptedSpaceKey": encode_b64(&sealed_share),+ "friendSealedSpaceKey": encode_b64(&sealed_share),"encryptedProfile": "","keyVersion": 4}])diff --git a/rust/space/src/error.rs b/rust/space/src/error.rsindex 1ba5119d98..a7c4d9fa90 100644--- a/rust/space/src/error.rs+++ b/rust/space/src/error.rs@@ -18,8 +18,8 @@ pub enum SpaceError {#[error("missing secret key material")]MissingSecretKey,- #[error("missing encrypted space key")]- MissingEncryptedSpaceKey,+ #[error("missing friend sealed space key")]+ MissingFriendSealedSpaceKey,#[error("entity key conflict")]EntityKeyConflict,diff --git a/rust/space/src/models.rs b/rust/space/src/models.rsindex 7da4fa3936..648ea1660d 100644--- a/rust/space/src/models.rs+++ b/rust/space/src/models.rs@@ -31,7 +31,7 @@ pub struct CreatedSpace {pub space_slug: String,pub key_version: i32,pub space_key: Vec<u8>,- pub encrypted_space_key: String,+ pub root_wrapped_space_key: String,pub encrypted_profile: String,}diff --git a/rust/space/src/transport.rs b/rust/space/src/transport.rsindex f7fc12f002..52d5580054 100644--- a/rust/space/src/transport.rs+++ b/rust/space/src/transport.rs@@ -35,7 +35,7 @@ pub struct StatusResponse {#[serde(rename_all = "camelCase")]pub struct CreateSpaceRequest {pub space_slug: String,- pub encrypted_space_key: String,+ pub root_wrapped_space_key: String,pub public_key: String,pub encrypted_secret_key: String,pub encrypted_profile: String,@@ -46,7 +46,7 @@ pub struct CreateSpaceRequest {pub struct SpaceKeyResponse {pub space_id: String,pub space_slug: String,- pub encrypted_space_key: String,+ pub root_wrapped_space_key: String,#[serde(default)]pub public_key: String,#[serde(default)]@@ -384,7 +384,7 @@ pub struct SpaceProfileResponse {#[serde(rename_all = "camelCase")]pub struct RotateSpaceKeyRequest {pub space_id: String,- pub encrypted_space_key: String,+ pub root_wrapped_space_key: String,pub key_version: i32,pub wrapped_prev_key: String,pub encrypted_profile: String,@@ -526,14 +526,14 @@ pub struct AddFriendPayload {#[serde(skip_serializing_if = "Option::is_none")]pub target_username: Option<String>,pub requester_space_id: String,- pub requester_encrypted_space_key: String,+ pub requester_friend_sealed_space_key: String,pub requester_key_version: i32,}#[derive(Debug, Clone, Serialize)]#[serde(rename_all = "camelCase")]pub struct ConfirmFriendRequestPayload {- pub target_encrypted_space_key: String,+ pub target_friend_sealed_space_key: String,pub target_key_version: i32,}@@ -579,7 +579,7 @@ pub struct SpaceFriendRequestResponse {#[serde(rename_all = "camelCase")]pub struct ShareUpdatePayload {pub friend_space_id: String,- pub encrypted_space_key: String,+ pub friend_sealed_space_key: String,}#[derive(Debug, Clone, Serialize)]@@ -596,7 +596,7 @@ pub struct FriendShareResponse {pub friend: String,pub space_id: String,pub space_slug: String,- pub encrypted_space_key: String,+ pub friend_sealed_space_key: String,pub key_version: i32,}@@ -633,7 +633,7 @@ pub struct SpaceLinkCreateRequest {pub space_id: String,pub auth_key: String,pub key_version: i32,- pub encrypted_space_key: String,+ pub link_wrapped_space_key: String,pub encrypted_access_key: String,}@@ -654,7 +654,7 @@ pub struct SpaceLinkLoginResponse {#[serde(default)]pub public_key: String,pub key_version: i32,- pub encrypted_space_key: String,+ pub link_wrapped_space_key: String,}#[derive(Debug, Clone, Serialize, Deserialize)]diff --git a/server/migrations/125_space.up.sql b/server/migrations/125_space.up.sqlindex 8ec8564b69..73e3dbece7 100644--- a/server/migrations/125_space.up.sql+++ b/server/migrations/125_space.up.sql@@ -2,7 +2,7 @@ CREATE TABLE IF NOT EXISTS spaces (space_id TEXT PRIMARY KEY,owner_id BIGINT NOT NULL REFERENCES users (user_id) ON DELETE CASCADE,space_slug TEXT NOT NULL,- encrypted_space_key BYTEA NOT NULL,+ root_wrapped_space_key BYTEA NOT NULL,public_key BYTEA NOT NULL,encrypted_secret_key BYTEA NOT NULL,encrypted_profile BYTEA NOT NULL DEFAULT '\x'::bytea,@@ -96,7 +96,7 @@ EXECUTE PROCEDURE trigger_updated_at_microseconds_column();CREATE TABLE IF NOT EXISTS space_key_versions (space_id TEXT NOT NULL REFERENCES spaces (space_id) ON DELETE CASCADE,version INTEGER NOT NULL,- encrypted_space_key BYTEA NOT NULL,+ root_wrapped_space_key BYTEA NOT NULL,encrypted_profile BYTEA NOT NULL DEFAULT '\x'::bytea,wrapped_prev_key BYTEA,created_at BIGINT NOT NULL DEFAULT now_utc_micro_seconds(),@@ -193,7 +193,7 @@ CREATE TABLE IF NOT EXISTS space_friend_shares (space_id TEXT NOT NULL REFERENCES spaces (space_id) ON DELETE CASCADE,friend_id BIGINT NOT NULL REFERENCES users (user_id) ON DELETE CASCADE,friend_space_id TEXT NOT NULL REFERENCES spaces (space_id) ON DELETE CASCADE,- encrypted_space_key BYTEA NOT NULL,+ friend_sealed_space_key BYTEA NOT NULL,key_version INTEGER NOT NULL DEFAULT 1,created_at BIGINT NOT NULL DEFAULT now_utc_micro_seconds(),updated_at BIGINT NOT NULL DEFAULT now_utc_micro_seconds(),@@ -217,7 +217,7 @@ CREATE TABLE IF NOT EXISTS space_friend_requests (requester_space_id TEXT NOT NULL REFERENCES spaces (space_id) ON DELETE CASCADE,target_id BIGINT NOT NULL REFERENCES users (user_id) ON DELETE CASCADE,target_space_id TEXT NOT NULL REFERENCES spaces (space_id) ON DELETE CASCADE,- requester_encrypted_space_key BYTEA NOT NULL,+ requester_friend_sealed_space_key BYTEA NOT NULL,requester_key_version INTEGER NOT NULL DEFAULT 1,is_deleted BOOLEAN NOT NULL DEFAULT FALSE,resolved_at BIGINT,@@ -373,7 +373,7 @@ CREATE TABLE IF NOT EXISTS space_links (space_id TEXT NOT NULL REFERENCES spaces (space_id) ON DELETE CASCADE,auth_key_hash BYTEA NOT NULL UNIQUE,key_version INTEGER NOT NULL,- encrypted_space_key BYTEA NOT NULL,+ link_wrapped_space_key BYTEA NOT NULL,encrypted_access_key BYTEA NOT NULL,active BOOLEAN NOT NULL DEFAULT TRUE,created_at BIGINT NOT NULL DEFAULT now_utc_micro_seconds(),diff --git a/server/space/api/test_helpers_test.go b/server/space/api/test_helpers_test.goindex dc31f1a280..4f375b157c 100644--- a/server/space/api/test_helpers_test.go+++ b/server/space/api/test_helpers_test.go@@ -10,6 +10,6 @@ func testSpaceBytes(value string) []byte {return []byte(value)}-func testCreateSpace(ctx context.Context, module *spacerepo.Module, ownerID int64, spaceSlug string, encryptedSpaceKey string, publicKey string, encryptedSecretKey string, _ string, encryptedProfile string) (*spacerepo.SpaceRecord, error) {- return module.Spaces.CreateSpace(ctx, ownerID, spaceSlug, testSpaceBytes(encryptedSpaceKey), testSpaceBytes(publicKey), testSpaceBytes(encryptedSecretKey), testSpaceBytes(encryptedProfile))+func testCreateSpace(ctx context.Context, module *spacerepo.Module, ownerID int64, spaceSlug string, rootWrappedSpaceKey string, publicKey string, encryptedSecretKey string, _ string, encryptedProfile string) (*spacerepo.SpaceRecord, error) {+ return module.Spaces.CreateSpace(ctx, ownerID, spaceSlug, testSpaceBytes(rootWrappedSpaceKey), testSpaceBytes(publicKey), testSpaceBytes(encryptedSecretKey), testSpaceBytes(encryptedProfile))}diff --git a/server/space/controller/friends.go b/server/space/controller/friends.goindex ab2219b859..092a052c6c 100644--- a/server/space/controller/friends.go+++ b/server/space/controller/friends.go@@ -27,11 +27,11 @@ func (c *FriendsController) Add(ctx *gin.Context, req models.AddFriendPayload) (}if (strings.TrimSpace(req.TargetSpaceID) == "" && strings.TrimSpace(req.TargetUsername) == "") ||strings.TrimSpace(req.RequesterSpaceID) == "" ||- strings.TrimSpace(req.RequesterEncryptedSpaceKey) == "" ||+ strings.TrimSpace(req.RequesterFriendSealedSpaceKey) == "" ||req.RequesterKeyVersion <= 0 {- return nil, ente.NewBadRequestWithMessage("targetSpaceId or targetUsername, requesterSpaceId, requesterEncryptedSpaceKey and requesterKeyVersion are required")+ return nil, ente.NewBadRequestWithMessage("targetSpaceId or targetUsername, requesterSpaceId, requesterFriendSealedSpaceKey and requesterKeyVersion are required")}- requesterEncryptedSpaceKey, err := decodeEncodedSpaceField("requesterEncryptedSpaceKey", req.RequesterEncryptedSpaceKey, maxSpaceEncryptedKeyEncodedBytes, maxSpaceEncryptedKeyDecodedBytes)+ requesterFriendSealedSpaceKey, err := decodeEncodedSpaceField("requesterFriendSealedSpaceKey", req.RequesterFriendSealedSpaceKey, maxSpaceEncryptedKeyEncodedBytes, maxSpaceEncryptedKeyDecodedBytes)if err != nil {return nil, err}@@ -54,7 +54,7 @@ func (c *FriendsController) Add(ctx *gin.Context, req models.AddFriendPayload) (userID,requesterSpace.SpaceID,targetSpace.SpaceID,- requesterEncryptedSpaceKey,+ requesterFriendSealedSpaceKey,req.RequesterKeyVersion,)if err != nil {@@ -108,10 +108,10 @@ func (c *FriendsController) ConfirmRequest(ctx *gin.Context, requestIDValue striif err != nil || requestID <= 0 {return nil, ente.ErrBadRequest}- if strings.TrimSpace(req.TargetEncryptedSpaceKey) == "" || req.TargetKeyVersion <= 0 {- return nil, ente.NewBadRequestWithMessage("targetEncryptedSpaceKey and targetKeyVersion are required")+ if strings.TrimSpace(req.TargetFriendSealedSpaceKey) == "" || req.TargetKeyVersion <= 0 {+ return nil, ente.NewBadRequestWithMessage("targetFriendSealedSpaceKey and targetKeyVersion are required")}- targetEncryptedSpaceKey, err := decodeEncodedSpaceField("targetEncryptedSpaceKey", req.TargetEncryptedSpaceKey, maxSpaceEncryptedKeyEncodedBytes, maxSpaceEncryptedKeyDecodedBytes)+ targetFriendSealedSpaceKey, err := decodeEncodedSpaceField("targetFriendSealedSpaceKey", req.TargetFriendSealedSpaceKey, maxSpaceEncryptedKeyEncodedBytes, maxSpaceEncryptedKeyDecodedBytes)if err != nil {return nil, err}@@ -124,7 +124,7 @@ func (c *FriendsController) ConfirmRequest(ctx *gin.Context, requestIDValue striuserID,targetSpace.SpaceID,requestID,- targetEncryptedSpaceKey,+ targetFriendSealedSpaceKey,req.TargetKeyVersion,)if err != nil {@@ -246,16 +246,16 @@ func (c *FriendsController) RefreshShares(ctx *gin.Context, req models.RefreshFr}updates := make([]repo.SpaceShareUpdateRecord, 0, len(req.Shares))for _, share := range req.Shares {- if strings.TrimSpace(share.FriendSpaceID) == "" || strings.TrimSpace(share.EncryptedSpaceKey) == "" {- return ente.NewBadRequestWithMessage("friendSpaceId and encryptedSpaceKey are required for each share")+ if strings.TrimSpace(share.FriendSpaceID) == "" || strings.TrimSpace(share.FriendSealedSpaceKey) == "" {+ return ente.NewBadRequestWithMessage("friendSpaceId and friendSealedSpaceKey are required for each share")}- encryptedSpaceKey, err := decodeEncodedSpaceField("encryptedSpaceKey", share.EncryptedSpaceKey, maxSpaceEncryptedKeyEncodedBytes, maxSpaceEncryptedKeyDecodedBytes)+ friendSealedSpaceKey, err := decodeEncodedSpaceField("friendSealedSpaceKey", share.FriendSealedSpaceKey, maxSpaceEncryptedKeyEncodedBytes, maxSpaceEncryptedKeyDecodedBytes)if err != nil {return err}updates = append(updates, repo.SpaceShareUpdateRecord{- FriendSpaceID: strings.TrimSpace(share.FriendSpaceID),- EncryptedSpaceKey: encryptedSpaceKey,+ FriendSpaceID: strings.TrimSpace(share.FriendSpaceID),+ FriendSealedSpaceKey: friendSealedSpaceKey,})}if err := c.FriendsRepo.UpdateShares(ctx.Request.Context(), space.SpaceID, updates, req.KeyVersion); err != nil {@@ -279,11 +279,11 @@ func (c *FriendsController) ListShares(ctx *gin.Context) ([]models.FriendShareReresp := make([]models.FriendShareResponse, 0, len(shares))for _, share := range shares {resp = append(resp, models.FriendShareResponse{- Friend: share.SpaceSlug,- SpaceID: share.SpaceID,- SpaceSlug: share.SpaceSlug,- EncryptedSpaceKey: encodeSpaceField(share.EncryptedSpaceKey),- KeyVersion: share.KeyVersion,+ Friend: share.SpaceSlug,+ SpaceID: share.SpaceID,+ SpaceSlug: share.SpaceSlug,+ FriendSealedSpaceKey: encodeSpaceField(share.FriendSealedSpaceKey),+ KeyVersion: share.KeyVersion,})}return resp, nildiff --git a/server/space/controller/friends_test.go b/server/space/controller/friends_test.goindex 18612ff0cf..87b2f1611b 100644--- a/server/space/controller/friends_test.go+++ b/server/space/controller/friends_test.go@@ -49,10 +49,10 @@ func TestAddFriendRejectsOwnSpace(t *testing.T) {require.NoError(t, err)resp, err := friends.Add(newSpaceControllerContext(aliceID), models.AddFriendPayload{- TargetSpaceID: aliceSpace.SpaceID,- RequesterSpaceID: aliceSpace.SpaceID,- RequesterEncryptedSpaceKey: base64.StdEncoding.EncodeToString([]byte("alice-requester-key")),- RequesterKeyVersion: aliceSpace.CurrentVersion,+ TargetSpaceID: aliceSpace.SpaceID,+ RequesterSpaceID: aliceSpace.SpaceID,+ RequesterFriendSealedSpaceKey: base64.StdEncoding.EncodeToString([]byte("alice-requester-key")),+ RequesterKeyVersion: aliceSpace.CurrentVersion,})require.Nil(t, resp)diff --git a/server/space/controller/helpers.go b/server/space/controller/helpers.goindex 714ac9c51b..b62066dc32 100644--- a/server/space/controller/helpers.go+++ b/server/space/controller/helpers.go@@ -114,13 +114,13 @@ func visibleActor(visible map[string]bool, actor spacerepo.SpaceActorRecord) boofunc toSpaceKeyResponse(space *spacerepo.SpaceRecord) *models.SpaceKeyResponse {return &models.SpaceKeyResponse{- SpaceID: space.SpaceID,- SpaceSlug: space.SpaceSlug,- EncryptedSpaceKey: encodeSpaceField(space.EncryptedSpaceKey),- PublicKey: encodeSpaceField(space.PublicKey),- EncryptedSecretKey: encodeSpaceField(space.EncryptedSecretKey),- EncryptedProfile: encodeSpaceField(space.EncryptedProfile),- KeyVersion: space.CurrentVersion,+ SpaceID: space.SpaceID,+ SpaceSlug: space.SpaceSlug,+ RootWrappedSpaceKey: encodeSpaceField(space.RootWrappedSpaceKey),+ PublicKey: encodeSpaceField(space.PublicKey),+ EncryptedSecretKey: encodeSpaceField(space.EncryptedSecretKey),+ EncryptedProfile: encodeSpaceField(space.EncryptedProfile),+ KeyVersion: space.CurrentVersion,}}diff --git a/server/space/controller/links.go b/server/space/controller/links.goindex 5d62d79236..254ceba14a 100644--- a/server/space/controller/links.go+++ b/server/space/controller/links.go@@ -61,13 +61,13 @@ func (c *LinksController) writeLink(ctx *gin.Context, req models.SpaceLinkCreateif err != nil {return nil, err}- if strings.TrimSpace(req.SpaceID) == "" || strings.TrimSpace(req.AuthKey) == "" || strings.TrimSpace(req.EncryptedSpaceKey) == "" || strings.TrimSpace(req.EncryptedAccessKey) == "" || req.KeyVersion <= 0 {- return nil, ente.NewBadRequestWithMessage("spaceId, authKey, encryptedSpaceKey, encryptedAccessKey and keyVersion are required")+ if strings.TrimSpace(req.SpaceID) == "" || strings.TrimSpace(req.AuthKey) == "" || strings.TrimSpace(req.LinkWrappedSpaceKey) == "" || strings.TrimSpace(req.EncryptedAccessKey) == "" || req.KeyVersion <= 0 {+ return nil, ente.NewBadRequestWithMessage("spaceId, authKey, linkWrappedSpaceKey, encryptedAccessKey and keyVersion are required")}if len(strings.TrimSpace(req.AuthKey)) > maxSpaceEncryptedKeyEncodedBytes {return nil, ente.NewBadRequestWithMessage("authKey is too large")}- encryptedSpaceKey, err := decodeEncodedSpaceField("encryptedSpaceKey", req.EncryptedSpaceKey, maxSpaceEncryptedKeyEncodedBytes, maxSpaceEncryptedKeyDecodedBytes)+ linkWrappedSpaceKey, err := decodeEncodedSpaceField("linkWrappedSpaceKey", req.LinkWrappedSpaceKey, maxSpaceEncryptedKeyEncodedBytes, maxSpaceEncryptedKeyDecodedBytes)if err != nil {return nil, err}@@ -89,9 +89,9 @@ func (c *LinksController) writeLink(ctx *gin.Context, req models.SpaceLinkCreatesum := sha256.Sum256(authKeyBytes)var link *repo.SpaceLinkRecordif rotate {- link, err = c.LinksRepo.RotateLink(ctx.Request.Context(), space.SpaceID, sum[:], req.KeyVersion, encryptedSpaceKey, encryptedAccessKey)+ link, err = c.LinksRepo.RotateLink(ctx.Request.Context(), space.SpaceID, sum[:], req.KeyVersion, linkWrappedSpaceKey, encryptedAccessKey)} else {- link, err = c.LinksRepo.UpsertLink(ctx.Request.Context(), space.SpaceID, sum[:], req.KeyVersion, encryptedSpaceKey, encryptedAccessKey)+ link, err = c.LinksRepo.UpsertLink(ctx.Request.Context(), space.SpaceID, sum[:], req.KeyVersion, linkWrappedSpaceKey, encryptedAccessKey)}if err != nil {if errors.Is(err, sql.ErrNoRows) {@@ -165,12 +165,12 @@ func (c *LinksController) Login(ctx *gin.Context, req models.SpaceLinkLoginRequereturn nil, err}return &models.SpaceLinkLoginResponse{- SessionToken: sessionToken,- SpaceID: link.SpaceID,- SpaceSlug: link.SpaceSlug,- Owner: link.OwnerSlug,- PublicKey: encodeSpaceField(publicKey),- KeyVersion: link.KeyVersion,- EncryptedSpaceKey: encodeSpaceField(link.EncryptedSpaceKey),+ SessionToken: sessionToken,+ SpaceID: link.SpaceID,+ SpaceSlug: link.SpaceSlug,+ Owner: link.OwnerSlug,+ PublicKey: encodeSpaceField(publicKey),+ KeyVersion: link.KeyVersion,+ LinkWrappedSpaceKey: encodeSpaceField(link.LinkWrappedSpaceKey),}, nil}diff --git a/server/space/controller/links_test.go b/server/space/controller/links_test.goindex e35e9b4f1a..a24076267b 100644--- a/server/space/controller/links_test.go+++ b/server/space/controller/links_test.go@@ -21,11 +21,11 @@ func TestCreateSpaceLinkReturnsExistingActiveLink(t *testing.T) {}resp, err := module.Links.Create(newSpaceControllerContext(aliceID), models.SpaceLinkCreateRequest{- SpaceID: space.SpaceID,- AuthKey: base64.StdEncoding.EncodeToString(authKey),- KeyVersion: space.CurrentVersion,- EncryptedSpaceKey: base64.StdEncoding.EncodeToString([]byte("new-space-link-key")),- EncryptedAccessKey: base64.StdEncoding.EncodeToString([]byte("new-owner-link-secret")),+ SpaceID: space.SpaceID,+ AuthKey: base64.StdEncoding.EncodeToString(authKey),+ KeyVersion: space.CurrentVersion,+ LinkWrappedSpaceKey: base64.StdEncoding.EncodeToString([]byte("new-space-link-key")),+ EncryptedAccessKey: base64.StdEncoding.EncodeToString([]byte("new-owner-link-secret")),})require.NoError(t, err)@@ -34,5 +34,5 @@ func TestCreateSpaceLinkReturnsExistingActiveLink(t *testing.T) {require.Equal(t, existing.SpaceID, resp.SpaceID)require.Equal(t, existing.SpaceSlug, resp.SpaceSlug)require.Equal(t, existing.KeyVersion, resp.KeyVersion)- require.Equal(t, existing.EncryptedAccessKey, resp.EncryptedAccessKey)+ require.Equal(t, base64.StdEncoding.EncodeToString(existing.EncryptedAccessKey), resp.EncryptedAccessKey)}diff --git a/server/space/controller/notifications_test.go b/server/space/controller/notifications_test.goindex 15bfc89cf0..ea811946f5 100644--- a/server/space/controller/notifications_test.go+++ b/server/space/controller/notifications_test.go@@ -146,10 +146,10 @@ func TestAddFriendSendsEmailOnce(t *testing.T) {bobSpace, err := testCreateSpace(ctx, repos, bobID, "bob_friend_email", "bob-space-key", "bob-friend-email-public", "bob-friend-email-secret", "bob-friend-email-secret-nonce", "bob-profile")require.NoError(t, err)req := models.AddFriendPayload{- TargetSpaceID: aliceSpace.SpaceID,- RequesterSpaceID: bobSpace.SpaceID,- RequesterEncryptedSpaceKey: base64.StdEncoding.EncodeToString([]byte("bob-requester-key")),- RequesterKeyVersion: bobSpace.CurrentVersion,+ TargetSpaceID: aliceSpace.SpaceID,+ RequesterSpaceID: bobSpace.SpaceID,+ RequesterFriendSealedSpaceKey: base64.StdEncoding.EncodeToString([]byte("bob-requester-key")),+ RequesterKeyVersion: bobSpace.CurrentVersion,}resp, err := friends.Add(newSpaceControllerContext(bobID), req)@@ -168,8 +168,8 @@ func TestAddFriendSendsEmailOnce(t *testing.T) {require.Equal(t, bobSpace.SpaceSlug, requests[0].Requester.SpaceSlug)resp, err = friends.ConfirmRequest(newSpaceControllerContext(aliceID), base10(requests[0].RequestID), models.ConfirmFriendRequestPayload{- TargetEncryptedSpaceKey: base64.StdEncoding.EncodeToString([]byte("alice-target-key")),- TargetKeyVersion: aliceSpace.CurrentVersion,+ TargetFriendSealedSpaceKey: base64.StdEncoding.EncodeToString([]byte("alice-target-key")),+ TargetKeyVersion: aliceSpace.CurrentVersion,})require.NoError(t, err)require.Equal(t, "friend", resp.Status)diff --git a/server/space/controller/spaces.go b/server/space/controller/spaces.goindex 505ae6a786..4ad95f15d7 100644--- a/server/space/controller/spaces.go+++ b/server/space/controller/spaces.go@@ -39,10 +39,10 @@ func (c *SpacesController) Create(ctx *gin.Context, req models.CreateSpaceRequesif err != nil {return nil, err}- if strings.TrimSpace(req.SpaceSlug) == "" || strings.TrimSpace(req.EncryptedSpaceKey) == "" || strings.TrimSpace(req.PublicKey) == "" || strings.TrimSpace(req.EncryptedSecretKey) == "" {- return nil, ente.NewBadRequestWithMessage("spaceSlug, encryptedSpaceKey and space identity keys are required")+ if strings.TrimSpace(req.SpaceSlug) == "" || strings.TrimSpace(req.RootWrappedSpaceKey) == "" || strings.TrimSpace(req.PublicKey) == "" || strings.TrimSpace(req.EncryptedSecretKey) == "" {+ return nil, ente.NewBadRequestWithMessage("spaceSlug, rootWrappedSpaceKey and space identity keys are required")}- encryptedSpaceKey, err := decodeEncodedSpaceField("encryptedSpaceKey", req.EncryptedSpaceKey, maxSpaceEncryptedKeyEncodedBytes, maxSpaceEncryptedKeyDecodedBytes)+ rootWrappedSpaceKey, err := decodeEncodedSpaceField("rootWrappedSpaceKey", req.RootWrappedSpaceKey, maxSpaceEncryptedKeyEncodedBytes, maxSpaceEncryptedKeyDecodedBytes)if err != nil {return nil, err}@@ -58,7 +58,7 @@ func (c *SpacesController) Create(ctx *gin.Context, req models.CreateSpaceRequesif err != nil {return nil, err}- space, err := c.SpacesRepo.CreateSpace(ctx.Request.Context(), userID, req.SpaceSlug, encryptedSpaceKey, publicKey, encryptedSecretKey, encryptedProfile)+ space, err := c.SpacesRepo.CreateSpace(ctx.Request.Context(), userID, req.SpaceSlug, rootWrappedSpaceKey, publicKey, encryptedSecretKey, encryptedProfile)if err != nil {return nil, err}@@ -243,10 +243,10 @@ func (c *SpacesController) RotateKey(ctx *gin.Context, req models.RotateSpaceKeyif err != nil {return nil, err}- if strings.TrimSpace(req.SpaceID) == "" || strings.TrimSpace(req.EncryptedSpaceKey) == "" || strings.TrimSpace(req.WrappedPrevKey) == "" || strings.TrimSpace(req.EncryptedProfile) == "" || req.KeyVersion <= 0 {- return nil, ente.NewBadRequestWithMessage("spaceId, keyVersion, encryptedSpaceKey, wrappedPrevKey and encryptedProfile are required")+ if strings.TrimSpace(req.SpaceID) == "" || strings.TrimSpace(req.RootWrappedSpaceKey) == "" || strings.TrimSpace(req.WrappedPrevKey) == "" || strings.TrimSpace(req.EncryptedProfile) == "" || req.KeyVersion <= 0 {+ return nil, ente.NewBadRequestWithMessage("spaceId, keyVersion, rootWrappedSpaceKey, wrappedPrevKey and encryptedProfile are required")}- encryptedSpaceKey, err := decodeEncodedSpaceField("encryptedSpaceKey", req.EncryptedSpaceKey, maxSpaceEncryptedKeyEncodedBytes, maxSpaceEncryptedKeyDecodedBytes)+ rootWrappedSpaceKey, err := decodeEncodedSpaceField("rootWrappedSpaceKey", req.RootWrappedSpaceKey, maxSpaceEncryptedKeyEncodedBytes, maxSpaceEncryptedKeyDecodedBytes)if err != nil {return nil, err}@@ -265,7 +265,7 @@ func (c *SpacesController) RotateKey(ctx *gin.Context, req models.RotateSpaceKeyif req.KeyVersion != current.CurrentVersion {return nil, ente.NewBadRequestWithMessage("keyVersion does not match current space version")}- space, err := c.SpacesRepo.RotateKey(ctx.Request.Context(), userID, req.SpaceID, req.KeyVersion, encryptedSpaceKey, wrappedPrevKey, encryptedProfile)+ space, err := c.SpacesRepo.RotateKey(ctx.Request.Context(), userID, req.SpaceID, req.KeyVersion, rootWrappedSpaceKey, wrappedPrevKey, encryptedProfile)if err != nil {if errors.Is(stacktrace.RootCause(err), sql.ErrNoRows) {return nil, ente.NewBadRequestWithMessage("keyVersion does not match current space version")diff --git a/server/space/controller/spaces_test.go b/server/space/controller/spaces_test.goindex ce3e5be74f..d895e2d9b2 100644--- a/server/space/controller/spaces_test.go+++ b/server/space/controller/spaces_test.go@@ -3,6 +3,7 @@ package controllerimport ("crypto/sha256""database/sql"+ "encoding/base64""strconv""testing"@@ -36,7 +37,7 @@ func TestGetProfileReturnsHistoricalVersion(t *testing.T) {require.Equal(t, space.SpaceID, resp.SpaceID)require.Equal(t, "alice", resp.SpaceSlug)require.Equal(t, 1, resp.Version)- require.Equal(t, "alice-profile-v1", resp.EncryptedProfile)+ require.Equal(t, base64.StdEncoding.EncodeToString([]byte("alice-profile-v1")), resp.EncryptedProfile)require.NotEmpty(t, resp.UpdatedAt)require.Nil(t, resp.Avatar)}@@ -145,11 +146,11 @@ func TestRotateKeyRejectsStaleKeyVersion(t *testing.T) {ginCtx.Request.Header.Set("X-Auth-User-ID", strconv.FormatInt(aliceID, 10))resp, err := module.Spaces.RotateKey(ginCtx, models.RotateSpaceKeyRequest{- SpaceID: space.SpaceID,- KeyVersion: space.CurrentVersion + 1,- EncryptedSpaceKey: "YWxpY2Utc3BhY2Uta2V5LXYy",- WrappedPrevKey: "d3JhcHBlZC1wcmV2LWtleQ==",- EncryptedProfile: "YWxpY2UtcHJvZmlsZS12Mg==",+ SpaceID: space.SpaceID,+ KeyVersion: space.CurrentVersion + 1,+ RootWrappedSpaceKey: "YWxpY2Utc3BhY2Uta2V5LXYy",+ WrappedPrevKey: "d3JhcHBlZC1wcmV2LWtleQ==",+ EncryptedProfile: "YWxpY2UtcHJvZmlsZS12Mg==",})require.Nil(t, resp)diff --git a/server/space/controller/test_helpers_test.go b/server/space/controller/test_helpers_test.goindex ab9eff5423..7492c59982 100644--- a/server/space/controller/test_helpers_test.go+++ b/server/space/controller/test_helpers_test.go@@ -30,24 +30,24 @@ func testSpaceBytes(value string) []byte {return []byte(value)}-func testCreateSpace(ctx context.Context, module *spacerepo.Module, ownerID int64, spaceSlug string, encryptedSpaceKey string, publicKey string, encryptedSecretKey string, _ string, encryptedProfile string) (*spacerepo.SpaceRecord, error) {- return module.Spaces.CreateSpace(ctx, ownerID, spaceSlug, testSpaceBytes(encryptedSpaceKey), testSpaceBytes(publicKey), testSpaceBytes(encryptedSecretKey), testSpaceBytes(encryptedProfile))+func testCreateSpace(ctx context.Context, module *spacerepo.Module, ownerID int64, spaceSlug string, rootWrappedSpaceKey string, publicKey string, encryptedSecretKey string, _ string, encryptedProfile string) (*spacerepo.SpaceRecord, error) {+ return module.Spaces.CreateSpace(ctx, ownerID, spaceSlug, testSpaceBytes(rootWrappedSpaceKey), testSpaceBytes(publicKey), testSpaceBytes(encryptedSecretKey), testSpaceBytes(encryptedProfile))}func testUpdateProfile(ctx context.Context, module *spacerepo.Module, ownerID int64, spaceID string, keyVersion int, encryptedProfile string, avatar *spacerepo.ProfileAssetUpdate, cover *spacerepo.ProfileAssetUpdate, removeAvatar bool, removeCover bool) (*spacerepo.SpaceRecord, error) {return module.Spaces.UpdateProfile(ctx, ownerID, spaceID, keyVersion, testSpaceBytes(encryptedProfile), avatar, cover, removeAvatar, removeCover)}-func testRotateKey(ctx context.Context, module *spacerepo.Module, ownerID int64, spaceID string, keyVersion int, encryptedSpaceKey string, wrappedPrevKey string, encryptedProfile string) (*spacerepo.SpaceRecord, error) {- return module.Spaces.RotateKey(ctx, ownerID, spaceID, keyVersion, testSpaceBytes(encryptedSpaceKey), testSpaceBytes(wrappedPrevKey), testSpaceBytes(encryptedProfile))+func testRotateKey(ctx context.Context, module *spacerepo.Module, ownerID int64, spaceID string, keyVersion int, rootWrappedSpaceKey string, wrappedPrevKey string, encryptedProfile string) (*spacerepo.SpaceRecord, error) {+ return module.Spaces.RotateKey(ctx, ownerID, spaceID, keyVersion, testSpaceBytes(rootWrappedSpaceKey), testSpaceBytes(wrappedPrevKey), testSpaceBytes(encryptedProfile))}-func testAddFriend(ctx context.Context, module *spacerepo.Module, requesterID int64, requesterSpaceID string, targetSpaceID string, targetEncryptedSpaceKey string, targetKeyVersion int, requesterEncryptedSpaceKey string, requesterKeyVersion int) error {- return module.Friends.AddFriend(ctx, requesterID, requesterSpaceID, targetSpaceID, testSpaceBytes(targetEncryptedSpaceKey), targetKeyVersion, testSpaceBytes(requesterEncryptedSpaceKey), requesterKeyVersion)+func testAddFriend(ctx context.Context, module *spacerepo.Module, requesterID int64, requesterSpaceID string, targetSpaceID string, targetFriendSealedSpaceKey string, targetKeyVersion int, requesterFriendSealedSpaceKey string, requesterKeyVersion int) error {+ return module.Friends.AddFriend(ctx, requesterID, requesterSpaceID, targetSpaceID, testSpaceBytes(targetFriendSealedSpaceKey), targetKeyVersion, testSpaceBytes(requesterFriendSealedSpaceKey), requesterKeyVersion)}-func testUpsertLink(ctx context.Context, module *spacerepo.Module, spaceID string, authKeyHash []byte, keyVersion int, encryptedSpaceKey string, encryptedAccessKey string) (*spacerepo.SpaceLinkRecord, error) {- return module.Links.UpsertLink(ctx, spaceID, authKeyHash, keyVersion, testSpaceBytes(encryptedSpaceKey), testSpaceBytes(encryptedAccessKey))+func testUpsertLink(ctx context.Context, module *spacerepo.Module, spaceID string, authKeyHash []byte, keyVersion int, linkWrappedSpaceKey string, encryptedAccessKey string) (*spacerepo.SpaceLinkRecord, error) {+ return module.Links.UpsertLink(ctx, spaceID, authKeyHash, keyVersion, testSpaceBytes(linkWrappedSpaceKey), testSpaceBytes(encryptedAccessKey))}func testCreatePost(ctx context.Context, module *spacerepo.Module, ownerID int64, spaceID string, encryptedPostKey string, captionCipher *string, keyVersion int, objects []spacerepo.SpacePostAssetRecord) (int64, error) {diff --git a/server/space/models/models.go b/server/space/models/models.goindex 55d67a4cc4..6e0a1660cf 100644--- a/server/space/models/models.go+++ b/server/space/models/models.go@@ -75,13 +75,13 @@ type FriendRelationshipRequest struct {}type SpaceKeyResponse struct {- SpaceID string `json:"spaceId"`- SpaceSlug string `json:"spaceSlug"`- EncryptedSpaceKey string `json:"encryptedSpaceKey"`- PublicKey string `json:"publicKey,omitempty"`- EncryptedSecretKey string `json:"encryptedSecretKey,omitempty"`- EncryptedProfile string `json:"encryptedProfile,omitempty"`- KeyVersion int `json:"keyVersion"`+ SpaceID string `json:"spaceId"`+ SpaceSlug string `json:"spaceSlug"`+ RootWrappedSpaceKey string `json:"rootWrappedSpaceKey"`+ PublicKey string `json:"publicKey,omitempty"`+ EncryptedSecretKey string `json:"encryptedSecretKey,omitempty"`+ EncryptedProfile string `json:"encryptedProfile,omitempty"`+ KeyVersion int `json:"keyVersion"`}type PresignUploadRequest struct {@@ -130,11 +130,11 @@ type SpaceActorResponse struct {}type SpaceLinkCreateRequest struct {- SpaceID string `json:"spaceId"`- AuthKey string `json:"authKey"`- KeyVersion int `json:"keyVersion"`- EncryptedSpaceKey string `json:"encryptedSpaceKey"`- EncryptedAccessKey string `json:"encryptedAccessKey"`+ SpaceID string `json:"spaceId"`+ AuthKey string `json:"authKey"`+ KeyVersion int `json:"keyVersion"`+ LinkWrappedSpaceKey string `json:"linkWrappedSpaceKey"`+ EncryptedAccessKey string `json:"encryptedAccessKey"`}type SpaceLinkStatusResponse struct {@@ -153,26 +153,26 @@ type SpaceLinkLoginRequest struct {}type SpaceLinkLoginResponse struct {- SessionToken string `json:"sessionToken"`- SpaceID string `json:"spaceId"`- SpaceSlug string `json:"spaceSlug"`- Owner string `json:"owner"`- PublicKey string `json:"publicKey,omitempty"`- KeyVersion int `json:"keyVersion"`- EncryptedSpaceKey string `json:"encryptedSpaceKey"`+ SessionToken string `json:"sessionToken"`+ SpaceID string `json:"spaceId"`+ SpaceSlug string `json:"spaceSlug"`+ Owner string `json:"owner"`+ PublicKey string `json:"publicKey,omitempty"`+ KeyVersion int `json:"keyVersion"`+ LinkWrappedSpaceKey string `json:"linkWrappedSpaceKey"`}type AddFriendPayload struct {- TargetSpaceID string `json:"targetSpaceId,omitempty"`- TargetUsername string `json:"targetUsername,omitempty"`- RequesterSpaceID string `json:"requesterSpaceId"`- RequesterEncryptedSpaceKey string `json:"requesterEncryptedSpaceKey"`- RequesterKeyVersion int `json:"requesterKeyVersion"`+ TargetSpaceID string `json:"targetSpaceId,omitempty"`+ TargetUsername string `json:"targetUsername,omitempty"`+ RequesterSpaceID string `json:"requesterSpaceId"`+ RequesterFriendSealedSpaceKey string `json:"requesterFriendSealedSpaceKey"`+ RequesterKeyVersion int `json:"requesterKeyVersion"`}type ConfirmFriendRequestPayload struct {- TargetEncryptedSpaceKey string `json:"targetEncryptedSpaceKey"`- TargetKeyVersion int `json:"targetKeyVersion"`+ TargetFriendSealedSpaceKey string `json:"targetFriendSealedSpaceKey"`+ TargetKeyVersion int `json:"targetKeyVersion"`}type FriendTargetPayload struct {@@ -181,11 +181,11 @@ type FriendTargetPayload struct {}type FriendShareResponse struct {- Friend string `json:"friend"`- SpaceID string `json:"spaceId"`- SpaceSlug string `json:"spaceSlug"`- EncryptedSpaceKey string `json:"encryptedSpaceKey"`- KeyVersion int `json:"keyVersion"`+ Friend string `json:"friend"`+ SpaceID string `json:"spaceId"`+ SpaceSlug string `json:"spaceSlug"`+ FriendSealedSpaceKey string `json:"friendSealedSpaceKey"`+ KeyVersion int `json:"keyVersion"`}type FriendStatusResponse struct {@@ -219,11 +219,11 @@ type UpdateSpaceProfileResponse struct {}type CreateSpaceRequest struct {- SpaceSlug string `json:"spaceSlug"`- EncryptedSpaceKey string `json:"encryptedSpaceKey"`- PublicKey string `json:"publicKey"`- EncryptedSecretKey string `json:"encryptedSecretKey"`- EncryptedProfile string `json:"encryptedProfile"`+ SpaceSlug string `json:"spaceSlug"`+ RootWrappedSpaceKey string `json:"rootWrappedSpaceKey"`+ PublicKey string `json:"publicKey"`+ EncryptedSecretKey string `json:"encryptedSecretKey"`+ EncryptedProfile string `json:"encryptedProfile"`}type SpaceProfileResponse struct {@@ -253,11 +253,11 @@ type SpaceSlugAvailabilityResponse struct {}type RotateSpaceKeyRequest struct {- SpaceID string `json:"spaceId"`- KeyVersion int `json:"keyVersion"`- EncryptedSpaceKey string `json:"encryptedSpaceKey"`- WrappedPrevKey string `json:"wrappedPrevKey"`- EncryptedProfile string `json:"encryptedProfile"`+ SpaceID string `json:"spaceId"`+ KeyVersion int `json:"keyVersion"`+ RootWrappedSpaceKey string `json:"rootWrappedSpaceKey"`+ WrappedPrevKey string `json:"wrappedPrevKey"`+ EncryptedProfile string `json:"encryptedProfile"`}type SpaceKeyVersionResponse struct {@@ -279,8 +279,8 @@ type RefreshFriendSharesRequest struct {}type ShareUpdatePayload struct {- FriendSpaceID string `json:"friendSpaceId"`- EncryptedSpaceKey string `json:"encryptedSpaceKey"`+ FriendSpaceID string `json:"friendSpaceId"`+ FriendSealedSpaceKey string `json:"friendSealedSpaceKey"`}type CreatePostRequest struct {diff --git a/server/space/repo/common.go b/server/space/repo/common.goindex 96c7ff639a..5d86253708 100644--- a/server/space/repo/common.go+++ b/server/space/repo/common.go@@ -80,7 +80,7 @@ const spaceRecordSelectColumns = `s.space_id,s.owner_id,s.space_slug,- s.encrypted_space_key,+ s.root_wrapped_space_key,s.encrypted_profile,s.current_version,s.public_key,diff --git a/server/space/repo/friends.go b/server/space/repo/friends.goindex 8903c511d0..037e5dddfd 100644--- a/server/space/repo/friends.go+++ b/server/space/repo/friends.go@@ -15,12 +15,12 @@ var (ErrSelfFriendship = errors.New("space users cannot friend themselves"))-func (r *FriendsRepository) AddFriend(ctx context.Context, requesterID int64, requesterSpaceID string, targetSpaceID string, targetEncryptedSpaceKey []byte, targetKeyVersion int, requesterEncryptedSpaceKey []byte, requesterKeyVersion int) error {- _, err := r.AddFriendWithCreated(ctx, requesterID, requesterSpaceID, targetSpaceID, targetEncryptedSpaceKey, targetKeyVersion, requesterEncryptedSpaceKey, requesterKeyVersion)+func (r *FriendsRepository) AddFriend(ctx context.Context, requesterID int64, requesterSpaceID string, targetSpaceID string, targetFriendSealedSpaceKey []byte, targetKeyVersion int, requesterFriendSealedSpaceKey []byte, requesterKeyVersion int) error {+ _, err := r.AddFriendWithCreated(ctx, requesterID, requesterSpaceID, targetSpaceID, targetFriendSealedSpaceKey, targetKeyVersion, requesterFriendSealedSpaceKey, requesterKeyVersion)return err}-func (r *FriendsRepository) AddFriendWithCreated(ctx context.Context, requesterID int64, requesterSpaceID string, targetSpaceID string, targetEncryptedSpaceKey []byte, targetKeyVersion int, requesterEncryptedSpaceKey []byte, requesterKeyVersion int) (bool, error) {+func (r *FriendsRepository) AddFriendWithCreated(ctx context.Context, requesterID int64, requesterSpaceID string, targetSpaceID string, targetFriendSealedSpaceKey []byte, targetKeyVersion int, requesterFriendSealedSpaceKey []byte, requesterKeyVersion int) (bool, error) {tx, err := r.DB.BeginTx(ctx, nil)if err != nil {return false, stacktrace.Propagate(err, "")@@ -76,22 +76,22 @@ func (r *FriendsRepository) AddFriendWithCreated(ctx context.Context, requesterI}if _, err := tx.ExecContext(ctx, `- INSERT INTO space_friend_shares (space_id, friend_id, friend_space_id, encrypted_space_key, key_version)+ INSERT INTO space_friend_shares (space_id, friend_id, friend_space_id, friend_sealed_space_key, key_version)VALUES ($1, $2, $3, $4, $5)ON CONFLICT (space_id, friend_space_id) DO UPDATE- SET encrypted_space_key = EXCLUDED.encrypted_space_key,+ SET friend_sealed_space_key = EXCLUDED.friend_sealed_space_key,key_version = EXCLUDED.key_version- `, targetSpaceID, requesterID, requesterSpaceID, targetEncryptedSpaceKey, targetKeyVersion); err != nil {+ `, targetSpaceID, requesterID, requesterSpaceID, targetFriendSealedSpaceKey, targetKeyVersion); err != nil {return false, stacktrace.Propagate(err, "")}if _, err := tx.ExecContext(ctx, `- INSERT INTO space_friend_shares (space_id, friend_id, friend_space_id, encrypted_space_key, key_version)+ INSERT INTO space_friend_shares (space_id, friend_id, friend_space_id, friend_sealed_space_key, key_version)VALUES ($1, $2, $3, $4, $5)ON CONFLICT (space_id, friend_space_id) DO UPDATE- SET encrypted_space_key = EXCLUDED.encrypted_space_key,+ SET friend_sealed_space_key = EXCLUDED.friend_sealed_space_key,key_version = EXCLUDED.key_version- `, requesterSpaceID, targetOwnerID, targetSpaceID, requesterEncryptedSpaceKey, requesterKeyVersion); err != nil {+ `, requesterSpaceID, targetOwnerID, targetSpaceID, requesterFriendSealedSpaceKey, requesterKeyVersion); err != nil {return false, stacktrace.Propagate(err, "")}@@ -110,7 +110,7 @@ func (r *FriendsRepository) AddFriendWithCreated(ctx context.Context, requesterIreturn !alreadyFriends, nil}-func (r *FriendsRepository) CreateFriendRequest(ctx context.Context, requesterID int64, requesterSpaceID string, targetSpaceID string, requesterEncryptedSpaceKey []byte, requesterKeyVersion int) (*SpaceFriendRequestRecord, bool, error) {+func (r *FriendsRepository) CreateFriendRequest(ctx context.Context, requesterID int64, requesterSpaceID string, targetSpaceID string, requesterFriendSealedSpaceKey []byte, requesterKeyVersion int) (*SpaceFriendRequestRecord, bool, error) {tx, err := r.DB.BeginTx(ctx, nil)if err != nil {return nil, false, stacktrace.Propagate(err, "")@@ -179,17 +179,17 @@ func (r *FriendsRepository) CreateFriendRequest(ctx context.Context, requesterIDcase err == nil:if _, err := tx.ExecContext(ctx, `UPDATE space_friend_requests- SET requester_encrypted_space_key = $2,+ SET requester_friend_sealed_space_key = $2,requester_key_version = $3WHERE request_id = $1- `, rec.RequestID, requesterEncryptedSpaceKey, requesterKeyVersion); err != nil {+ `, rec.RequestID, requesterFriendSealedSpaceKey, requesterKeyVersion); err != nil {return nil, false, stacktrace.Propagate(err, "")}rec.RequesterID = requesterIDrec.RequesterSpaceID = requesterSpaceIDrec.TargetID = targetOwnerIDrec.TargetSpaceID = targetSpaceID- rec.RequesterEncryptedSpaceKey = requesterEncryptedSpaceKey+ rec.RequesterFriendSealedSpaceKey = requesterFriendSealedSpaceKeyrec.RequesterKeyVersion = requesterKeyVersionreturn &rec, false, stacktrace.Propagate(tx.Commit(), "")case !errors.Is(err, sql.ErrNoRows):@@ -202,19 +202,19 @@ func (r *FriendsRepository) CreateFriendRequest(ctx context.Context, requesterIDrequester_space_id,target_id,target_space_id,- requester_encrypted_space_key,+ requester_friend_sealed_space_key,requester_key_version)VALUES ($1, $2, $3, $4, $5, $6)RETURNING request_id, created_at- `, requesterID, requesterSpaceID, targetOwnerID, targetSpaceID, requesterEncryptedSpaceKey, requesterKeyVersion).Scan(&rec.RequestID, &rec.CreatedAt); err != nil {+ `, requesterID, requesterSpaceID, targetOwnerID, targetSpaceID, requesterFriendSealedSpaceKey, requesterKeyVersion).Scan(&rec.RequestID, &rec.CreatedAt); err != nil {return nil, false, stacktrace.Propagate(err, "")}rec.RequesterID = requesterIDrec.RequesterSpaceID = requesterSpaceIDrec.TargetID = targetOwnerIDrec.TargetSpaceID = targetSpaceID- rec.RequesterEncryptedSpaceKey = requesterEncryptedSpaceKey+ rec.RequesterFriendSealedSpaceKey = requesterFriendSealedSpaceKeyrec.RequesterKeyVersion = requesterKeyVersionreturn &rec, true, stacktrace.Propagate(tx.Commit(), "")}@@ -226,7 +226,7 @@ func (r *FriendsRepository) ListFriendRequestsForSpace(ctx context.Context, targfr.requester_space_id,fr.target_id,fr.target_space_id,- fr.requester_encrypted_space_key,+ fr.requester_friend_sealed_space_key,fr.requester_key_version,fr.created_at,requester_space.owner_id,@@ -263,7 +263,7 @@ func (r *FriendsRepository) ListFriendRequestsForSpace(ctx context.Context, targ&rec.RequesterSpaceID,&rec.TargetID,&rec.TargetSpaceID,- &rec.RequesterEncryptedSpaceKey,+ &rec.RequesterFriendSealedSpaceKey,&rec.RequesterKeyVersion,&rec.CreatedAt,}@@ -276,7 +276,7 @@ func (r *FriendsRepository) ListFriendRequestsForSpace(ctx context.Context, targreturn out, stacktrace.Propagate(rows.Err(), "")}-func (r *FriendsRepository) ConfirmFriendRequest(ctx context.Context, targetID int64, targetSpaceID string, requestID int64, targetEncryptedSpaceKey []byte, targetKeyVersion int) (int64, bool, error) {+func (r *FriendsRepository) ConfirmFriendRequest(ctx context.Context, targetID int64, targetSpaceID string, requestID int64, targetFriendSealedSpaceKey []byte, targetKeyVersion int) (int64, bool, error) {tx, err := r.DB.BeginTx(ctx, nil)if err != nil {return 0, false, stacktrace.Propagate(err, "")@@ -285,7 +285,7 @@ func (r *FriendsRepository) ConfirmFriendRequest(ctx context.Context, targetID ivar requesterID int64var requesterSpaceID string- var requesterEncryptedSpaceKey []byte+ var requesterFriendSealedSpaceKey []bytevar requesterKeyVersion intvar requesterCurrentVersion intvar targetOwnerID int64@@ -293,7 +293,7 @@ func (r *FriendsRepository) ConfirmFriendRequest(ctx context.Context, targetID iif err := tx.QueryRowContext(ctx, `SELECT fr.requester_id,fr.requester_space_id,- fr.requester_encrypted_space_key,+ fr.requester_friend_sealed_space_key,fr.requester_key_version,requester_space.current_version,target_space.owner_id,@@ -311,7 +311,7 @@ func (r *FriendsRepository) ConfirmFriendRequest(ctx context.Context, targetID i`, requestID, targetID, targetSpaceID).Scan(&requesterID,&requesterSpaceID,- &requesterEncryptedSpaceKey,+ &requesterFriendSealedSpaceKey,&requesterKeyVersion,&requesterCurrentVersion,&targetOwnerID,@@ -341,22 +341,22 @@ func (r *FriendsRepository) ConfirmFriendRequest(ctx context.Context, targetID i}if _, err := tx.ExecContext(ctx, `- INSERT INTO space_friend_shares (space_id, friend_id, friend_space_id, encrypted_space_key, key_version)+ INSERT INTO space_friend_shares (space_id, friend_id, friend_space_id, friend_sealed_space_key, key_version)VALUES ($1, $2, $3, $4, $5)ON CONFLICT (space_id, friend_space_id) DO UPDATE- SET encrypted_space_key = EXCLUDED.encrypted_space_key,+ SET friend_sealed_space_key = EXCLUDED.friend_sealed_space_key,key_version = EXCLUDED.key_version- `, targetSpaceID, requesterID, requesterSpaceID, targetEncryptedSpaceKey, targetKeyVersion); err != nil {+ `, targetSpaceID, requesterID, requesterSpaceID, targetFriendSealedSpaceKey, targetKeyVersion); err != nil {return 0, false, stacktrace.Propagate(err, "")}if _, err := tx.ExecContext(ctx, `- INSERT INTO space_friend_shares (space_id, friend_id, friend_space_id, encrypted_space_key, key_version)+ INSERT INTO space_friend_shares (space_id, friend_id, friend_space_id, friend_sealed_space_key, key_version)VALUES ($1, $2, $3, $4, $5)ON CONFLICT (space_id, friend_space_id) DO UPDATE- SET encrypted_space_key = EXCLUDED.encrypted_space_key,+ SET friend_sealed_space_key = EXCLUDED.friend_sealed_space_key,key_version = EXCLUDED.key_version- `, requesterSpaceID, targetID, targetSpaceID, requesterEncryptedSpaceKey, requesterKeyVersion); err != nil {+ `, requesterSpaceID, targetID, targetSpaceID, requesterFriendSealedSpaceKey, requesterKeyVersion); err != nil {return 0, false, stacktrace.Propagate(err, "")}@@ -412,20 +412,20 @@ func (r *FriendsRepository) DeleteFriendRequest(ctx context.Context, targetID inreturn nil}-func (r *FriendsRepository) UpsertShare(ctx context.Context, spaceID string, friendID int64, friendSpaceID string, encryptedSpaceKey []byte, keyVersion int) error {+func (r *FriendsRepository) UpsertShare(ctx context.Context, spaceID string, friendID int64, friendSpaceID string, friendSealedSpaceKey []byte, keyVersion int) error {_, err := r.DB.ExecContext(ctx, `- INSERT INTO space_friend_shares (space_id, friend_id, friend_space_id, encrypted_space_key, key_version)+ INSERT INTO space_friend_shares (space_id, friend_id, friend_space_id, friend_sealed_space_key, key_version)VALUES ($1, $2, $3, $4, $5)ON CONFLICT (space_id, friend_space_id) DO UPDATE- SET encrypted_space_key = EXCLUDED.encrypted_space_key,+ SET friend_sealed_space_key = EXCLUDED.friend_sealed_space_key,key_version = EXCLUDED.key_version- `, spaceID, friendID, friendSpaceID, encryptedSpaceKey, keyVersion)+ `, spaceID, friendID, friendSpaceID, friendSealedSpaceKey, keyVersion)return stacktrace.Propagate(err, "")}-func (r *FriendsRepository) UpdateShare(ctx context.Context, spaceID string, _ int64, friendSpaceID string, encryptedSpaceKey []byte, keyVersion int) error {+func (r *FriendsRepository) UpdateShare(ctx context.Context, spaceID string, _ int64, friendSpaceID string, friendSealedSpaceKey []byte, keyVersion int) error {return r.UpdateShares(ctx, spaceID, []SpaceShareUpdateRecord{- {FriendSpaceID: friendSpaceID, EncryptedSpaceKey: encryptedSpaceKey},+ {FriendSpaceID: friendSpaceID, FriendSealedSpaceKey: friendSealedSpaceKey},}, keyVersion)}@@ -459,10 +459,10 @@ func (r *FriendsRepository) UpdateShares(ctx context.Context, spaceID string, sh}res, err := tx.ExecContext(ctx, `UPDATE space_friend_shares- SET encrypted_space_key = $3,+ SET friend_sealed_space_key = $3,key_version = $4WHERE space_id = $1 AND friend_space_id = $2- `, spaceID, friendSpaceID, share.EncryptedSpaceKey, keyVersion)+ `, spaceID, friendSpaceID, share.FriendSealedSpaceKey, keyVersion)if err != nil {return stacktrace.Propagate(err, "")}@@ -528,7 +528,7 @@ func (r *FriendsRepository) DeleteShareBySpaceAndFriend(ctx context.Context, spafunc (r *FriendsRepository) GetShareForFriendAndSpace(ctx context.Context, friendID int64, friendSpaceID string, spaceID string) (*SpaceShareRecord, error) {return scanShareRecord(r.DB.QueryRowContext(ctx, `- SELECT s.space_id, s.friend_id, w.owner_id, w.space_slug, s.encrypted_space_key, s.key_version, s.created_at, w.public_key+ SELECT s.space_id, s.friend_id, w.owner_id, w.space_slug, s.friend_sealed_space_key, s.key_version, s.created_at, w.public_keyFROM space_friend_shares sJOIN spaces w ON w.space_id = s.space_idJOIN users u ON u.user_id = w.owner_id AND u.encrypted_email IS NOT NULL@@ -538,7 +538,7 @@ func (r *FriendsRepository) GetShareForFriendAndSpace(ctx context.Context, frienfunc (r *FriendsRepository) ListSharesForFriend(ctx context.Context, friendID int64) ([]SpaceShareRecord, error) {rows, err := r.DB.QueryContext(ctx, `- SELECT s.space_id, s.friend_id, w.owner_id, w.space_slug, s.encrypted_space_key, s.key_version, s.created_at, w.public_key+ SELECT s.space_id, s.friend_id, w.owner_id, w.space_slug, s.friend_sealed_space_key, s.key_version, s.created_at, w.public_keyFROM space_friend_shares sJOIN spaces w ON w.space_id = s.space_idJOIN users u ON u.user_id = w.owner_id AND u.encrypted_email IS NOT NULL@@ -657,7 +657,7 @@ func (r *FriendsRepository) GetRelationship(ctx context.Context, viewerID int64,func scanShareRecord(scanner interface{ Scan(dest ...any) error }) (*SpaceShareRecord, error) {var rec SpaceShareRecord- if err := scanner.Scan(&rec.SpaceID, &rec.FriendID, &rec.OwnerID, &rec.SpaceSlug, &rec.EncryptedSpaceKey, &rec.KeyVersion, &rec.CreatedAt, &rec.PublicKey); err != nil {+ if err := scanner.Scan(&rec.SpaceID, &rec.FriendID, &rec.OwnerID, &rec.SpaceSlug, &rec.FriendSealedSpaceKey, &rec.KeyVersion, &rec.CreatedAt, &rec.PublicKey); err != nil {return nil, stacktrace.Propagate(err, "")}return &rec, nildiff --git a/server/space/repo/links.go b/server/space/repo/links.goindex f4544a9f17..a8cb7b0ac3 100644--- a/server/space/repo/links.go+++ b/server/space/repo/links.go@@ -15,15 +15,15 @@ var (ErrLinkAuthKeyReused = errors.New("space link auth key has already been used"))-func (r *LinksRepository) UpsertLink(ctx context.Context, spaceID string, authKeyHash []byte, keyVersion int, encryptedSpaceKey []byte, encryptedAccessKey []byte) (*SpaceLinkRecord, error) {- return r.writeLink(ctx, spaceID, authKeyHash, keyVersion, encryptedSpaceKey, encryptedAccessKey, false)+func (r *LinksRepository) UpsertLink(ctx context.Context, spaceID string, authKeyHash []byte, keyVersion int, linkWrappedSpaceKey []byte, encryptedAccessKey []byte) (*SpaceLinkRecord, error) {+ return r.writeLink(ctx, spaceID, authKeyHash, keyVersion, linkWrappedSpaceKey, encryptedAccessKey, false)}-func (r *LinksRepository) RotateLink(ctx context.Context, spaceID string, authKeyHash []byte, keyVersion int, encryptedSpaceKey []byte, encryptedAccessKey []byte) (*SpaceLinkRecord, error) {- return r.writeLink(ctx, spaceID, authKeyHash, keyVersion, encryptedSpaceKey, encryptedAccessKey, true)+func (r *LinksRepository) RotateLink(ctx context.Context, spaceID string, authKeyHash []byte, keyVersion int, linkWrappedSpaceKey []byte, encryptedAccessKey []byte) (*SpaceLinkRecord, error) {+ return r.writeLink(ctx, spaceID, authKeyHash, keyVersion, linkWrappedSpaceKey, encryptedAccessKey, true)}-func (r *LinksRepository) writeLink(ctx context.Context, spaceID string, authKeyHash []byte, keyVersion int, encryptedSpaceKey []byte, encryptedAccessKey []byte, rotate bool) (*SpaceLinkRecord, error) {+func (r *LinksRepository) writeLink(ctx context.Context, spaceID string, authKeyHash []byte, keyVersion int, linkWrappedSpaceKey []byte, encryptedAccessKey []byte, rotate bool) (*SpaceLinkRecord, error) {tx, err := r.DB.BeginTx(ctx, nil)if err != nil {return nil, stacktrace.Propagate(err, "")@@ -57,7 +57,7 @@ func (r *LinksRepository) writeLink(ctx context.Context, spaceID string, authKeyreturn nil, ErrLinkAuthKeyReused}return scanLinkRecord(tx.QueryRowContext(ctx, `- SELECT l.space_id, $2::text, $3::bigint, $2::text, l.auth_key_hash, l.key_version, l.encrypted_space_key, l.encrypted_access_key, l.active, l.created_at, l.updated_at+ SELECT l.space_id, $2::text, $3::bigint, $2::text, l.auth_key_hash, l.key_version, l.link_wrapped_space_key, l.encrypted_access_key, l.active, l.created_at, l.updated_atFROM space_links lWHERE l.space_id = $1 AND l.active = TRUE`, spaceID, spaceSlug, ownerID))@@ -96,10 +96,10 @@ func (r *LinksRepository) writeLink(ctx context.Context, spaceID string, authKey}link, err := scanLinkRecord(tx.QueryRowContext(ctx, `- INSERT INTO space_links (space_id, auth_key_hash, key_version, encrypted_space_key, encrypted_access_key, active)+ INSERT INTO space_links (space_id, auth_key_hash, key_version, link_wrapped_space_key, encrypted_access_key, active)VALUES ($1, $2, $3, $4, $5, TRUE)- RETURNING space_id, $6::text, $7::bigint, $6::text, auth_key_hash, key_version, encrypted_space_key, encrypted_access_key, active, created_at, updated_at- `, spaceID, authKeyHash, keyVersion, encryptedSpaceKey, encryptedAccessKey, spaceSlug, ownerID))+ RETURNING space_id, $6::text, $7::bigint, $6::text, auth_key_hash, key_version, link_wrapped_space_key, encrypted_access_key, active, created_at, updated_at+ `, spaceID, authKeyHash, keyVersion, linkWrappedSpaceKey, encryptedAccessKey, spaceSlug, ownerID))if err != nil {if isUniqueViolationFor(err, "uq_space_links_active_space") {return nil, ErrActiveLinkAlreadyExists@@ -117,7 +117,7 @@ func (r *LinksRepository) writeLink(ctx context.Context, spaceID string, authKeyfunc (r *LinksRepository) GetLink(ctx context.Context, spaceID string) (*SpaceLinkRecord, error) {return scanLinkRecord(r.DB.QueryRowContext(ctx, `- SELECT l.space_id, w.space_slug, w.owner_id, w.space_slug, l.auth_key_hash, l.key_version, l.encrypted_space_key, l.encrypted_access_key, l.active, l.created_at, l.updated_at+ SELECT l.space_id, w.space_slug, w.owner_id, w.space_slug, l.auth_key_hash, l.key_version, l.link_wrapped_space_key, l.encrypted_access_key, l.active, l.created_at, l.updated_atFROM space_links lJOIN spaces w ON w.space_id = l.space_idJOIN users u ON u.user_id = w.owner_id AND u.encrypted_email IS NOT NULL@@ -149,7 +149,7 @@ func deleteLinkTx(ctx context.Context, tx *sql.Tx, spaceID string) error {func (r *LinksRepository) GetLinkByAuthHash(ctx context.Context, spaceID string, authHash []byte) (*SpaceLinkRecord, error) {return scanLinkRecord(r.DB.QueryRowContext(ctx, `- SELECT l.space_id, w.space_slug, w.owner_id, w.space_slug, l.auth_key_hash, l.key_version, l.encrypted_space_key, l.encrypted_access_key, l.active, l.created_at, l.updated_at+ SELECT l.space_id, w.space_slug, w.owner_id, w.space_slug, l.auth_key_hash, l.key_version, l.link_wrapped_space_key, l.encrypted_access_key, l.active, l.created_at, l.updated_atFROM space_links lJOIN spaces w ON w.space_id = l.space_idJOIN users u ON u.user_id = w.owner_id AND u.encrypted_email IS NOT NULL@@ -185,7 +185,7 @@ func (r *LinksRepository) CreateSession(ctx context.Context, tokenHash []byte, sfunc (r *LinksRepository) GetSession(ctx context.Context, tokenHash []byte) (*SpaceLinkSessionRecord, error) {row := r.DB.QueryRowContext(ctx, `SELECT s.token_hash, s.space_id, s.owner_id, s.auth_key_hash, s.key_version, s.expires_at, s.created_at,- w.space_slug, w.space_slug, l.encrypted_space_key+ w.space_slug, w.space_slug, l.link_wrapped_space_keyFROM space_link_sessions sJOIN spaces w ON w.space_id = s.space_idJOIN users u ON u.user_id = w.owner_id AND u.encrypted_email IS NOT NULL@@ -195,7 +195,7 @@ func (r *LinksRepository) GetSession(ctx context.Context, tokenHash []byte) (*SpWHERE s.token_hash = $1 AND l.active = TRUE`, tokenHash)var rec SpaceLinkSessionRecord- if err := row.Scan(&rec.TokenHash, &rec.SpaceID, &rec.OwnerID, &rec.AuthKeyHash, &rec.KeyVersion, &rec.ExpiresAt, &rec.CreatedAt, &rec.SpaceSlug, &rec.OwnerSlug, &rec.EncryptedSpaceKey); err != nil {+ if err := row.Scan(&rec.TokenHash, &rec.SpaceID, &rec.OwnerID, &rec.AuthKeyHash, &rec.KeyVersion, &rec.ExpiresAt, &rec.CreatedAt, &rec.SpaceSlug, &rec.OwnerSlug, &rec.LinkWrappedSpaceKey); err != nil {return nil, stacktrace.Propagate(err, "")}return &rec, nil@@ -218,7 +218,7 @@ func (r *LinksRepository) DeleteSession(ctx context.Context, tokenHash []byte) efunc scanLinkRecord(scanner interface{ Scan(dest ...any) error }) (*SpaceLinkRecord, error) {var rec SpaceLinkRecord- if err := scanner.Scan(&rec.SpaceID, &rec.SpaceSlug, &rec.OwnerID, &rec.OwnerSlug, &rec.AuthKeyHash, &rec.KeyVersion, &rec.EncryptedSpaceKey, &rec.EncryptedAccessKey, &rec.Active, &rec.CreatedAt, &rec.UpdatedAt); err != nil {+ if err := scanner.Scan(&rec.SpaceID, &rec.SpaceSlug, &rec.OwnerID, &rec.OwnerSlug, &rec.AuthKeyHash, &rec.KeyVersion, &rec.LinkWrappedSpaceKey, &rec.EncryptedAccessKey, &rec.Active, &rec.CreatedAt, &rec.UpdatedAt); err != nil {return nil, stacktrace.Propagate(err, "")}return &rec, nildiff --git a/server/space/repo/module.go b/server/space/repo/module.goindex f105b80893..4205997614 100644--- a/server/space/repo/module.go+++ b/server/space/repo/module.go@@ -56,22 +56,22 @@ type EntityKeysRepository struct {}type SpaceRecord struct {- SpaceID string- OwnerID int64- SpaceSlug string- EncryptedSpaceKey []byte- PublicKey []byte- EncryptedSecretKey []byte- EncryptedProfile []byte- CurrentVersion int- AvatarObjectID sql.NullString- AvatarBucketID sql.NullString- AvatarSize sql.NullInt64- CoverObjectID sql.NullString- CoverBucketID sql.NullString- CoverSize sql.NullInt64- CreatedAt int64- UpdatedAt int64+ SpaceID string+ OwnerID int64+ SpaceSlug string+ RootWrappedSpaceKey []byte+ PublicKey []byte+ EncryptedSecretKey []byte+ EncryptedProfile []byte+ CurrentVersion int+ AvatarObjectID sql.NullString+ AvatarBucketID sql.NullString+ AvatarSize sql.NullInt64+ CoverObjectID sql.NullString+ CoverBucketID sql.NullString+ CoverSize sql.NullInt64+ CreatedAt int64+ UpdatedAt int64}type ProfileAssetUpdate struct {@@ -81,12 +81,12 @@ type ProfileAssetUpdate struct {}type SpaceVersionRecord struct {- SpaceID string- Version int- EncryptedSpaceKey []byte- EncryptedProfile []byte- WrappedPrevKey []byte- CreatedAt int64+ SpaceID string+ Version int+ RootWrappedSpaceKey []byte+ EncryptedProfile []byte+ WrappedPrevKey []byte+ CreatedAt int64}type SpacePostRecord struct {@@ -222,19 +222,19 @@ type SpaceActorRecord struct {}type SpaceShareRecord struct {- SpaceID string- FriendID int64- OwnerID int64- SpaceSlug string- EncryptedSpaceKey []byte- KeyVersion int- CreatedAt int64- PublicKey []byte+ SpaceID string+ FriendID int64+ OwnerID int64+ SpaceSlug string+ FriendSealedSpaceKey []byte+ KeyVersion int+ CreatedAt int64+ PublicKey []byte}type SpaceShareUpdateRecord struct {- FriendSpaceID string- EncryptedSpaceKey []byte+ FriendSpaceID string+ FriendSealedSpaceKey []byte}type SpaceFriendRecord struct {@@ -244,42 +244,42 @@ type SpaceFriendRecord struct {}type SpaceFriendRequestRecord struct {- RequestID int64- RequesterID int64- RequesterSpaceID string- TargetID int64- TargetSpaceID string- RequesterEncryptedSpaceKey []byte- RequesterKeyVersion int- CreatedAt int64- Requester SpaceActorRecord+ RequestID int64+ RequesterID int64+ RequesterSpaceID string+ TargetID int64+ TargetSpaceID string+ RequesterFriendSealedSpaceKey []byte+ RequesterKeyVersion int+ CreatedAt int64+ Requester SpaceActorRecord}type SpaceLinkRecord struct {- SpaceID string- SpaceSlug string- OwnerID int64- OwnerSlug string- AuthKeyHash []byte- KeyVersion int- EncryptedSpaceKey []byte- EncryptedAccessKey []byte- Active bool- CreatedAt int64- UpdatedAt int64+ SpaceID string+ SpaceSlug string+ OwnerID int64+ OwnerSlug string+ AuthKeyHash []byte+ KeyVersion int+ LinkWrappedSpaceKey []byte+ EncryptedAccessKey []byte+ Active bool+ CreatedAt int64+ UpdatedAt int64}type SpaceLinkSessionRecord struct {- TokenHash []byte- SpaceID string- OwnerID int64- AuthKeyHash []byte- KeyVersion int- ExpiresAt int64- CreatedAt int64- SpaceSlug string- OwnerSlug string- EncryptedSpaceKey []byte+ TokenHash []byte+ SpaceID string+ OwnerID int64+ AuthKeyHash []byte+ KeyVersion int+ ExpiresAt int64+ CreatedAt int64+ SpaceSlug string+ OwnerSlug string+ LinkWrappedSpaceKey []byte}type SpaceBrowserSessionRecord struct {diff --git a/server/space/repo/module_test.go b/server/space/repo/module_test.goindex f43f3f55de..c30eb0f150 100644--- a/server/space/repo/module_test.go+++ b/server/space/repo/module_test.go@@ -27,44 +27,44 @@ func testSpaceBytes(value string) []byte {return []byte(value)}-func testCreateSpace(ctx context.Context, module *Module, ownerID int64, spaceSlug string, encryptedSpaceKey string, publicKey string, encryptedSecretKey string, _ string, encryptedProfile string) (*SpaceRecord, error) {- return module.Spaces.CreateSpace(ctx, ownerID, spaceSlug, testSpaceBytes(encryptedSpaceKey), testSpaceBytes(publicKey), testSpaceBytes(encryptedSecretKey), testSpaceBytes(encryptedProfile))+func testCreateSpace(ctx context.Context, module *Module, ownerID int64, spaceSlug string, rootWrappedSpaceKey string, publicKey string, encryptedSecretKey string, _ string, encryptedProfile string) (*SpaceRecord, error) {+ return module.Spaces.CreateSpace(ctx, ownerID, spaceSlug, testSpaceBytes(rootWrappedSpaceKey), testSpaceBytes(publicKey), testSpaceBytes(encryptedSecretKey), testSpaceBytes(encryptedProfile))}func testUpdateProfile(ctx context.Context, module *Module, ownerID int64, spaceID string, keyVersion int, encryptedProfile string, avatar *ProfileAssetUpdate, cover *ProfileAssetUpdate, removeAvatar bool, removeCover bool) (*SpaceRecord, error) {return module.Spaces.UpdateProfile(ctx, ownerID, spaceID, keyVersion, testSpaceBytes(encryptedProfile), avatar, cover, removeAvatar, removeCover)}-func testRotateKey(ctx context.Context, module *Module, ownerID int64, spaceID string, keyVersion int, encryptedSpaceKey string, wrappedPrevKey string, encryptedProfile string) (*SpaceRecord, error) {- return module.Spaces.RotateKey(ctx, ownerID, spaceID, keyVersion, testSpaceBytes(encryptedSpaceKey), testSpaceBytes(wrappedPrevKey), testSpaceBytes(encryptedProfile))+func testRotateKey(ctx context.Context, module *Module, ownerID int64, spaceID string, keyVersion int, rootWrappedSpaceKey string, wrappedPrevKey string, encryptedProfile string) (*SpaceRecord, error) {+ return module.Spaces.RotateKey(ctx, ownerID, spaceID, keyVersion, testSpaceBytes(rootWrappedSpaceKey), testSpaceBytes(wrappedPrevKey), testSpaceBytes(encryptedProfile))}-func testAddFriend(ctx context.Context, module *Module, requesterID int64, requesterSpaceID string, targetSpaceID string, targetEncryptedSpaceKey string, targetKeyVersion int, requesterEncryptedSpaceKey string, requesterKeyVersion int) error {- return module.Friends.AddFriend(ctx, requesterID, requesterSpaceID, targetSpaceID, testSpaceBytes(targetEncryptedSpaceKey), targetKeyVersion, testSpaceBytes(requesterEncryptedSpaceKey), requesterKeyVersion)+func testAddFriend(ctx context.Context, module *Module, requesterID int64, requesterSpaceID string, targetSpaceID string, targetFriendSealedSpaceKey string, targetKeyVersion int, requesterFriendSealedSpaceKey string, requesterKeyVersion int) error {+ return module.Friends.AddFriend(ctx, requesterID, requesterSpaceID, targetSpaceID, testSpaceBytes(targetFriendSealedSpaceKey), targetKeyVersion, testSpaceBytes(requesterFriendSealedSpaceKey), requesterKeyVersion)}-func testCreateFriendRequest(ctx context.Context, module *Module, requesterID int64, requesterSpaceID string, targetSpaceID string, requesterEncryptedSpaceKey string, requesterKeyVersion int) (*SpaceFriendRequestRecord, bool, error) {- return module.Friends.CreateFriendRequest(ctx, requesterID, requesterSpaceID, targetSpaceID, testSpaceBytes(requesterEncryptedSpaceKey), requesterKeyVersion)+func testCreateFriendRequest(ctx context.Context, module *Module, requesterID int64, requesterSpaceID string, targetSpaceID string, requesterFriendSealedSpaceKey string, requesterKeyVersion int) (*SpaceFriendRequestRecord, bool, error) {+ return module.Friends.CreateFriendRequest(ctx, requesterID, requesterSpaceID, targetSpaceID, testSpaceBytes(requesterFriendSealedSpaceKey), requesterKeyVersion)}-func testConfirmFriendRequest(ctx context.Context, module *Module, targetID int64, targetSpaceID string, requestID int64, targetEncryptedSpaceKey string, targetKeyVersion int) (int64, bool, error) {- return module.Friends.ConfirmFriendRequest(ctx, targetID, targetSpaceID, requestID, testSpaceBytes(targetEncryptedSpaceKey), targetKeyVersion)+func testConfirmFriendRequest(ctx context.Context, module *Module, targetID int64, targetSpaceID string, requestID int64, targetFriendSealedSpaceKey string, targetKeyVersion int) (int64, bool, error) {+ return module.Friends.ConfirmFriendRequest(ctx, targetID, targetSpaceID, requestID, testSpaceBytes(targetFriendSealedSpaceKey), targetKeyVersion)}-func testUpsertShare(ctx context.Context, module *Module, spaceID string, friendID int64, friendSpaceID string, encryptedSpaceKey string, keyVersion int) error {- return module.Friends.UpsertShare(ctx, spaceID, friendID, friendSpaceID, testSpaceBytes(encryptedSpaceKey), keyVersion)+func testUpsertShare(ctx context.Context, module *Module, spaceID string, friendID int64, friendSpaceID string, friendSealedSpaceKey string, keyVersion int) error {+ return module.Friends.UpsertShare(ctx, spaceID, friendID, friendSpaceID, testSpaceBytes(friendSealedSpaceKey), keyVersion)}-func testUpdateShare(ctx context.Context, module *Module, spaceID string, friendID int64, friendSpaceID string, encryptedSpaceKey string, keyVersion int) error {- return module.Friends.UpdateShare(ctx, spaceID, friendID, friendSpaceID, testSpaceBytes(encryptedSpaceKey), keyVersion)+func testUpdateShare(ctx context.Context, module *Module, spaceID string, friendID int64, friendSpaceID string, friendSealedSpaceKey string, keyVersion int) error {+ return module.Friends.UpdateShare(ctx, spaceID, friendID, friendSpaceID, testSpaceBytes(friendSealedSpaceKey), keyVersion)}-func testUpsertLink(ctx context.Context, module *Module, spaceID string, authKeyHash []byte, keyVersion int, encryptedSpaceKey string, encryptedAccessKey string) (*SpaceLinkRecord, error) {- return module.Links.UpsertLink(ctx, spaceID, authKeyHash, keyVersion, testSpaceBytes(encryptedSpaceKey), testSpaceBytes(encryptedAccessKey))+func testUpsertLink(ctx context.Context, module *Module, spaceID string, authKeyHash []byte, keyVersion int, linkWrappedSpaceKey string, encryptedAccessKey string) (*SpaceLinkRecord, error) {+ return module.Links.UpsertLink(ctx, spaceID, authKeyHash, keyVersion, testSpaceBytes(linkWrappedSpaceKey), testSpaceBytes(encryptedAccessKey))}-func testRotateLink(ctx context.Context, module *Module, spaceID string, authKeyHash []byte, keyVersion int, encryptedSpaceKey string, encryptedAccessKey string) (*SpaceLinkRecord, error) {- return module.Links.RotateLink(ctx, spaceID, authKeyHash, keyVersion, testSpaceBytes(encryptedSpaceKey), testSpaceBytes(encryptedAccessKey))+func testRotateLink(ctx context.Context, module *Module, spaceID string, authKeyHash []byte, keyVersion int, linkWrappedSpaceKey string, encryptedAccessKey string) (*SpaceLinkRecord, error) {+ return module.Links.RotateLink(ctx, spaceID, authKeyHash, keyVersion, testSpaceBytes(linkWrappedSpaceKey), testSpaceBytes(encryptedAccessKey))}func testCreatePost(ctx context.Context, module *Module, ownerID int64, spaceID string, encryptedPostKey string, captionCipher *string, keyVersion int, objects []SpacePostAssetRecord) (int64, error) {@@ -696,10 +696,10 @@ func TestConfirmFriendRequestCreatesFriendshipAndNotifiesRequester(t *testing.T)aliceShare, err := module.Friends.GetShareForFriendAndSpace(ctx, aliceID, aliceSpace.SpaceID, bobSpace.SpaceID)require.NoError(t, err)- require.Equal(t, "bob-share-key", aliceShare.EncryptedSpaceKey)+ require.Equal(t, testSpaceBytes("bob-share-key"), aliceShare.FriendSealedSpaceKey)bobShare, err := module.Friends.GetShareForFriendAndSpace(ctx, bobID, bobSpace.SpaceID, aliceSpace.SpaceID)require.NoError(t, err)- require.Equal(t, "alice-share-key", bobShare.EncryptedSpaceKey)+ require.Equal(t, testSpaceBytes("alice-share-key"), bobShare.FriendSealedSpaceKey)requests, err := module.Friends.ListFriendRequestsForSpace(ctx, aliceID, aliceSpace.SpaceID)require.NoError(t, err)require.Empty(t, requests)@@ -992,7 +992,7 @@ func TestSpaceModuleLifecycle(t *testing.T) {Size: 111,}, nil, false, false)require.NoError(t, err)- require.Equal(t, "alice-profile-v2", updatedSpace.EncryptedProfile)+ require.Equal(t, testSpaceBytes("alice-profile-v2"), updatedSpace.EncryptedProfile)require.Equal(t, "avatar.jpg", updatedSpace.AvatarObjectID.String)require.Equal(t, "b2-eu-cen", updatedSpace.AvatarBucketID.String)@@ -1010,12 +1010,12 @@ func TestSpaceModuleLifecycle(t *testing.T) {shares, err := module.Friends.ListSharesForFriend(ctx, bobID)require.NoError(t, err)require.Len(t, shares, 1)- require.Equal(t, "alice-share-key", shares[0].EncryptedSpaceKey)+ require.Equal(t, testSpaceBytes("alice-share-key"), shares[0].FriendSealedSpaceKey)aliceShares, err := module.Friends.ListSharesForFriend(ctx, aliceID)require.NoError(t, err)require.Len(t, aliceShares, 1)- require.Equal(t, "bob-share-key", aliceShares[0].EncryptedSpaceKey)+ require.Equal(t, testSpaceBytes("bob-share-key"), aliceShares[0].FriendSealedSpaceKey)friends, err := module.Friends.ListFriendsForSpace(ctx, aliceSpace.SpaceID)require.NoError(t, err)@@ -1139,7 +1139,7 @@ func TestSpaceModuleLifecycle(t *testing.T) {link, err := testUpsertLink(ctx, module, aliceSpace.SpaceID, []byte("hash"), rotatedSpace.CurrentVersion, "space-link-key", "owner-link-secret")require.NoError(t, err)- require.Equal(t, "space-link-key", link.EncryptedSpaceKey)+ require.Equal(t, testSpaceBytes("space-link-key"), link.LinkWrappedSpaceKey)err = module.Links.CreateSession(ctx, []byte("token-hash"), link.SpaceID, link.AuthKeyHash, link.KeyVersion, timeutil.NMinFromNow(30))require.NoError(t, err)@@ -1306,12 +1306,12 @@ func TestAddFriendCreatesReciprocalSharesAndEvent(t *testing.T) {share, err := module.Friends.GetShareForFriendAndSpace(ctx, bobID, bobSpace.SpaceID, aliceSpace.SpaceID)require.NoError(t, err)- require.Equal(t, "alice-share-key", share.EncryptedSpaceKey)+ require.Equal(t, testSpaceBytes("alice-share-key"), share.FriendSealedSpaceKey)require.Equal(t, aliceSpace.CurrentVersion, share.KeyVersion)reciprocalShare, err := module.Friends.GetShareForFriendAndSpace(ctx, aliceID, aliceSpace.SpaceID, bobSpace.SpaceID)require.NoError(t, err)- require.Equal(t, "bob-share-key", reciprocalShare.EncryptedSpaceKey)+ require.Equal(t, testSpaceBytes("bob-share-key"), reciprocalShare.FriendSealedSpaceKey)require.Equal(t, bobSpace.CurrentVersion, reciprocalShare.KeyVersion)var eventCount int@@ -1351,7 +1351,7 @@ func TestAddFriendIsIdempotentForExistingFriends(t *testing.T) {require.NoError(t, err)share, err := module.Friends.GetShareForFriendAndSpace(ctx, bobID, bobSpace.SpaceID, aliceSpace.SpaceID)require.NoError(t, err)- require.Equal(t, "alice-share-key-v2", share.EncryptedSpaceKey)+ require.Equal(t, testSpaceBytes("alice-share-key-v2"), share.FriendSealedSpaceKey)var eventCount interr = module.Friends.DB.QueryRow(`SELECT COUNT(*) FROM space_friend_events WHERE event_type = 'friend_add' AND actor_id = $1 AND target_id = $2`, bobID, aliceID).Scan(&eventCount)require.NoError(t, err)@@ -1445,7 +1445,7 @@ func TestUpdateShareOnlyRefreshesExistingShares(t *testing.T) {require.NoError(t, err)share, err := module.Friends.GetShareForFriendAndSpace(ctx, bobID, bobSpace.SpaceID, aliceSpace.SpaceID)require.NoError(t, err)- require.Equal(t, "share-key-v2", share.EncryptedSpaceKey)+ require.Equal(t, testSpaceBytes("share-key-v2"), share.FriendSealedSpaceKey)require.Equal(t, rotatedSpace.CurrentVersion, share.KeyVersion)err = module.Friends.DeleteShareBySpaceAndFriend(ctx, aliceSpace.SpaceID, bobID, bobSpace.SpaceID)@@ -1495,7 +1495,7 @@ func TestUpdateProfileRejectsStaleKeyVersion(t *testing.T) {current, err := module.Spaces.GetSpaceByID(ctx, space.SpaceID)require.NoError(t, err)require.Equal(t, rotated.CurrentVersion, current.CurrentVersion)- require.Equal(t, "alice-profile-v2", current.EncryptedProfile)+ require.Equal(t, testSpaceBytes("alice-profile-v2"), current.EncryptedProfile)}func TestRotateKeyRejectsStaleKeyVersion(t *testing.T) {@@ -1516,7 +1516,7 @@ func TestRotateKeyRejectsStaleKeyVersion(t *testing.T) {current, err := module.Spaces.GetSpaceByID(ctx, space.SpaceID)require.NoError(t, err)require.Equal(t, 2, current.CurrentVersion)- require.Equal(t, "alice-space-key-v2", current.EncryptedSpaceKey)+ require.Equal(t, testSpaceBytes("alice-space-key-v2"), current.RootWrappedSpaceKey)versions, err := module.Spaces.ListVersions(ctx, space.SpaceID)require.NoError(t, err)@@ -1565,7 +1565,7 @@ func TestUpdateShareRejectsStaleKeyVersion(t *testing.T) {share, err := module.Friends.GetShareForFriendAndSpace(ctx, bobID, bobSpace.SpaceID, aliceSpace.SpaceID)require.NoError(t, err)- require.Equal(t, "share-key-v1", share.EncryptedSpaceKey)+ require.Equal(t, testSpaceBytes("share-key-v1"), share.FriendSealedSpaceKey)require.Equal(t, aliceSpace.CurrentVersion, share.KeyVersion)}@@ -1579,7 +1579,7 @@ func TestRotateKeyRevokesSpaceLinks(t *testing.T) {link, err := testUpsertLink(ctx, module, space.SpaceID, []byte("hash"), space.CurrentVersion, "space-link-key", "owner-link-secret")require.NoError(t, err)- require.Equal(t, "space-link-key", link.EncryptedSpaceKey)+ require.Equal(t, testSpaceBytes("space-link-key"), link.LinkWrappedSpaceKey)err = module.Links.CreateSession(ctx, []byte("token-hash"), link.SpaceID, link.AuthKeyHash, link.KeyVersion, timeutil.NMinFromNow(30))require.NoError(t, err)@@ -1614,12 +1614,12 @@ func TestGetVersionReturnsHistoricalProfile(t *testing.T) {v1, err := module.Spaces.GetVersion(ctx, space.SpaceID, 1)require.NoError(t, err)require.Equal(t, 1, v1.Version)- require.Equal(t, "alice-profile-v1", v1.EncryptedProfile)+ require.Equal(t, testSpaceBytes("alice-profile-v1"), v1.EncryptedProfile)v2, err := module.Spaces.GetVersion(ctx, space.SpaceID, 2)require.NoError(t, err)require.Equal(t, 2, v2.Version)- require.Equal(t, "alice-profile-v2", v2.EncryptedProfile)+ require.Equal(t, testSpaceBytes("alice-profile-v2"), v2.EncryptedProfile)}func TestUpsertLinkReusesExistingLinkWithoutRevokingSessions(t *testing.T) {@@ -1638,7 +1638,7 @@ func TestUpsertLinkReusesExistingLinkWithoutRevokingSessions(t *testing.T) {reused, err := testUpsertLink(ctx, module, space.SpaceID, []byte("same-hash"), space.CurrentVersion, "new-random-envelope", "new-owner-link-secret")require.NoError(t, err)require.Equal(t, link.AuthKeyHash, reused.AuthKeyHash)- require.Equal(t, link.EncryptedSpaceKey, reused.EncryptedSpaceKey)+ require.Equal(t, link.LinkWrappedSpaceKey, reused.LinkWrappedSpaceKey)require.Equal(t, link.EncryptedAccessKey, reused.EncryptedAccessKey)session, err := module.Links.GetSession(ctx, []byte("token-hash"))@@ -1683,7 +1683,7 @@ func TestDeleteLinkTombstonesAuthHash(t *testing.T) {freshLink, err := testUpsertLink(ctx, module, space.SpaceID, []byte("fresh-hash"), space.CurrentVersion, "fresh-space-link-key", "fresh-owner-link-secret")require.NoError(t, err)- require.Equal(t, "fresh-space-link-key", freshLink.EncryptedSpaceKey)+ require.Equal(t, testSpaceBytes("fresh-space-link-key"), freshLink.LinkWrappedSpaceKey)}func TestCreateSessionRejectsStaleLinkAuthHash(t *testing.T) {diff --git a/server/space/repo/spaces.go b/server/space/repo/spaces.goindex e9cad60aeb..0e08187961 100644--- a/server/space/repo/spaces.go+++ b/server/space/repo/spaces.go@@ -9,7 +9,7 @@ import ("github.com/ente-io/stacktrace")-func (r *SpacesRepository) CreateSpace(ctx context.Context, ownerID int64, spaceSlug string, encryptedSpaceKey, publicKey, encryptedSecretKey, encryptedProfile []byte) (*SpaceRecord, error) {+func (r *SpacesRepository) CreateSpace(ctx context.Context, ownerID int64, spaceSlug string, rootWrappedSpaceKey, publicKey, encryptedSecretKey, encryptedProfile []byte) (*SpaceRecord, error) {normalizedSpaceSlug, err := validateSpaceSlug(spaceSlug)if err != nil {return nil, err@@ -22,15 +22,15 @@ func (r *SpacesRepository) CreateSpace(ctx context.Context, ownerID int64, spacedefer tx.Rollback()if _, err := tx.ExecContext(ctx, `- INSERT INTO spaces (space_id, owner_id, space_slug, encrypted_space_key, public_key, encrypted_secret_key, encrypted_profile, current_version)+ INSERT INTO spaces (space_id, owner_id, space_slug, root_wrapped_space_key, public_key, encrypted_secret_key, encrypted_profile, current_version)VALUES ($1, $2, $3, $4, $5, $6, $7, 1)- `, spaceID, ownerID, normalizedSpaceSlug, encryptedSpaceKey, publicKey, encryptedSecretKey, encryptedProfile); err != nil {+ `, spaceID, ownerID, normalizedSpaceSlug, rootWrappedSpaceKey, publicKey, encryptedSecretKey, encryptedProfile); err != nil {return nil, wrapUnique(err, "space already exists")}if _, err := tx.ExecContext(ctx, `- INSERT INTO space_key_versions (space_id, version, encrypted_space_key, encrypted_profile)+ INSERT INTO space_key_versions (space_id, version, root_wrapped_space_key, encrypted_profile)VALUES ($1, 1, $2, $3)- `, spaceID, encryptedSpaceKey, encryptedProfile); err != nil {+ `, spaceID, rootWrappedSpaceKey, encryptedProfile); err != nil {return nil, stacktrace.Propagate(err, "")}rec, err := scanSpaceRecord(tx.QueryRowContext(ctx, `@@ -217,7 +217,7 @@ func (r *SpacesRepository) UpdateSlug(ctx context.Context, ownerID int64, spaceIreturn rec, nil}-func (r *SpacesRepository) RotateKey(ctx context.Context, ownerID int64, spaceID string, keyVersion int, encryptedSpaceKey, wrappedPrevKey, encryptedProfile []byte) (*SpaceRecord, error) {+func (r *SpacesRepository) RotateKey(ctx context.Context, ownerID int64, spaceID string, keyVersion int, rootWrappedSpaceKey, wrappedPrevKey, encryptedProfile []byte) (*SpaceRecord, error) {tx, err := r.DB.BeginTx(ctx, nil)if err != nil {return nil, stacktrace.Propagate(err, "")@@ -241,16 +241,16 @@ func (r *SpacesRepository) RotateKey(ctx context.Context, ownerID int64, spaceID}newVersion := current.CurrentVersion + 1if _, err := tx.ExecContext(ctx, `- INSERT INTO space_key_versions (space_id, version, encrypted_space_key, encrypted_profile, wrapped_prev_key)+ INSERT INTO space_key_versions (space_id, version, root_wrapped_space_key, encrypted_profile, wrapped_prev_key)VALUES ($1, $2, $3, $4, $5)- `, spaceID, newVersion, encryptedSpaceKey, encryptedProfile, wrappedPrevKey); err != nil {+ `, spaceID, newVersion, rootWrappedSpaceKey, encryptedProfile, wrappedPrevKey); err != nil {return nil, stacktrace.Propagate(err, "")}if _, err := tx.ExecContext(ctx, `UPDATE spaces- SET encrypted_space_key = $1, encrypted_profile = $2, current_version = $3+ SET root_wrapped_space_key = $1, encrypted_profile = $2, current_version = $3WHERE owner_id = $4 AND space_id = $5- `, encryptedSpaceKey, encryptedProfile, newVersion, ownerID, spaceID); err != nil {+ `, rootWrappedSpaceKey, encryptedProfile, newVersion, ownerID, spaceID); err != nil {return nil, stacktrace.Propagate(err, "")}if err := deleteLinkTx(ctx, tx, spaceID); err != nil {@@ -273,7 +273,7 @@ func (r *SpacesRepository) RotateKey(ctx context.Context, ownerID int64, spaceIDfunc (r *SpacesRepository) ListVersions(ctx context.Context, spaceID string) ([]SpaceVersionRecord, error) {rows, err := r.DB.QueryContext(ctx, `- SELECT space_id, version, encrypted_space_key, encrypted_profile, wrapped_prev_key, created_at+ SELECT space_id, version, root_wrapped_space_key, encrypted_profile, wrapped_prev_key, created_atFROM space_key_versionsWHERE space_id = $1ORDER BY version DESC@@ -285,7 +285,7 @@ func (r *SpacesRepository) ListVersions(ctx context.Context, spaceID string) ([]var versions []SpaceVersionRecordfor rows.Next() {var rec SpaceVersionRecord- if err := rows.Scan(&rec.SpaceID, &rec.Version, &rec.EncryptedSpaceKey, &rec.EncryptedProfile, &rec.WrappedPrevKey, &rec.CreatedAt); err != nil {+ if err := rows.Scan(&rec.SpaceID, &rec.Version, &rec.RootWrappedSpaceKey, &rec.EncryptedProfile, &rec.WrappedPrevKey, &rec.CreatedAt); err != nil {return nil, stacktrace.Propagate(err, "")}versions = append(versions, rec)@@ -295,12 +295,12 @@ func (r *SpacesRepository) ListVersions(ctx context.Context, spaceID string) ([]func (r *SpacesRepository) GetVersion(ctx context.Context, spaceID string, version int) (*SpaceVersionRecord, error) {row := r.DB.QueryRowContext(ctx, `- SELECT space_id, version, encrypted_space_key, encrypted_profile, wrapped_prev_key, created_at+ SELECT space_id, version, root_wrapped_space_key, encrypted_profile, wrapped_prev_key, created_atFROM space_key_versionsWHERE space_id = $1 AND version = $2`, spaceID, version)var rec SpaceVersionRecord- if err := row.Scan(&rec.SpaceID, &rec.Version, &rec.EncryptedSpaceKey, &rec.EncryptedProfile, &rec.WrappedPrevKey, &rec.CreatedAt); err != nil {+ if err := row.Scan(&rec.SpaceID, &rec.Version, &rec.RootWrappedSpaceKey, &rec.EncryptedProfile, &rec.WrappedPrevKey, &rec.CreatedAt); err != nil {return nil, stacktrace.Propagate(err, "")}return &rec, nil@@ -312,7 +312,7 @@ func scanSpaceRecord(scanner interface{ Scan(dest ...any) error }) (*SpaceRecord&rec.SpaceID,&rec.OwnerID,&rec.SpaceSlug,- &rec.EncryptedSpaceKey,+ &rec.RootWrappedSpaceKey,&rec.EncryptedProfile,&rec.CurrentVersion,&rec.PublicKey,